# Trading (/vela-pro/api/trading)



This page documents `@luxalgo/vela-pro-trading`, including the `Broker` interface, `PaperBroker`, `TradingController`, the order ticket and trading panel widgets, and order, position, bracket, and risk types.

Import symbols on this page from `@luxalgo/vela-pro-trading`. Related guides: [Trading](/vela-pro/modules/trading/overview), [Broker integration](/vela-pro/modules/trading/broker), [Orders, positions, and brackets](/vela-pro/modules/trading/trading-concepts).

## Functions [#functions]

### `averageTrueRange` [#averagetruerange]

Wilder's average true range over the last `period` bars; undefined with fewer than `period + 1`.

```typescript
function averageTrueRange(
    bars: ReadonlyArray<{ high: number; low: number; close: number }>,
    period?: number,
): number | undefined
```

Default: `period = EXIT_ATR_PERIOD`.

### `buildTradingScene` [#buildtradingscene]

```typescript
function buildTradingScene(input: SceneInputs): TradingScene
```

See also: [`SceneInputs`](/vela-pro/api/trading#sceneinputs), [`TradingScene`](/vela-pro/api/trading#tradingscene).

### `createOrderTicket` [#createorderticket]

The order ticket as a widget: `{ el, update, destroy }`.

```typescript
function createOrderTicket(props: OrderTicketProps): OrderTicketWidget
```

See also: [`OrderTicketProps`](/vela-pro/api/trading#orderticketprops), [`OrderTicketWidget`](/vela-pro/api/trading#orderticketwidget).

### `createTradingPanel` [#createtradingpanel]

The trading panel as a widget: `{ el, update, destroy }`.

```typescript
function createTradingPanel(props: TradingPanelProps): TradingPanelWidget
```

See also: [`TradingPanelProps`](/vela-pro/api/trading#tradingpanelprops), [`TradingPanelWidget`](/vela-pro/api/trading#tradingpanelwidget).

### `defaultTradingDisplay` [#defaulttradingdisplay]

```typescript
function defaultTradingDisplay(): TradingDisplayState
```

See also: [`TradingDisplayState`](/vela-pro/api/trading#tradingdisplaystate).

### `enableTrading` [#enabletrading]

Enable TRADING on every shell built afterwards: orders, positions, fills and closed trades drawn on each chart (drag a line to move an order, drag TP/SL grips out of an entry or the position, close and reverse from the labels), the Buy/Sell card under each chart's status line, right-click orders and shortcuts, the order panel and the trading panel. Returns the page's [`TradingController`](/vela-pro/api/trading#tradingcontroller-class). Call ONCE, before constructing shells. Idempotent.

```typescript
function enableTrading(opts?: EnableTradingOptions): TradingController
```

See also: [`EnableTradingOptions`](/vela-pro/api/trading#enabletradingoptions), [`TradingController`](/vela-pro/api/trading#tradingcontroller-class).

### `exitDistance` [#exitdistance]

How far an exit at `price` is from the entry, in `mode`: what a dragged line types back.

```typescript
function exitDistance(mode: ExitSpec['mode'], price: number, ctx: ExitContext): number | undefined
```

See also: [`ExitContext`](/vela-pro/api/trading#exitcontext), [`ExitSpec`](/vela-pro/api/trading#exitspec).

### `exitPrice` [#exitprice]

The price `distance` (in `mode`) away from the entry, on the side `role` belongs: a buy's take profit above it, its stop loss below. Undefined when it cannot be placed.

```typescript
function exitPrice(
    role: 'take-profit' | 'stop-loss',
    mode: ExitSpec['mode'],
    distance: number,
    ctx: ExitContext,
): number | undefined
```

See also: [`ExitContext`](/vela-pro/api/trading#exitcontext), [`ExitSpec`](/vela-pro/api/trading#exitspec).

### `inferEntryType` [#inferentrytype]

What rests at `price` for a `side` order, given the last price: a buy below it (a sell above it) is a limit, the other way round a stop. Without a last price: a limit.

```typescript
function inferEntryType(side: OrderSide, price: number, last: number | undefined): 'limit' | 'stop'
```

See also: [`OrderSide`](/vela-pro/api/trading#orderside).

### `mergeTradingDisplay` [#mergetradingdisplay]

Merge a partial (persisted, untrusted) display state over the defaults.

```typescript
function mergeTradingDisplay(base: TradingDisplayState, patch: unknown): TradingDisplayState
```

See also: [`TradingDisplayState`](/vela-pro/api/trading#tradingdisplaystate).

### `orderWords` [#orderwords]

The words for an order: `Buy 1 BTCUSDT at market`, `Sell limit 2 ETHUSDT at 2,410.00`.

```typescript
function orderWords(
    q: Pick<PlaceQuestion, 'side' | 'type' | 'qty' | 'symbol' | 'price'>,
    tick: number,
): string
```

See also: [`PlaceQuestion`](/vela-pro/api/trading#placequestion).

### `pnlAt` [#pnlat]

The P\&L of closing `qty` from `entry` at `exit` on a `side` position (`'buy'` = long). Positive is a gain.

```typescript
function pnlAt(side: OrderSide, qty: number, entry: number, exit: number): number
```

See also: [`OrderSide`](/vela-pro/api/trading#orderside).

### `qtyForSize` [#qtyforsize]

The quantity `size` asks for, or undefined while it cannot be read: a cash size needs an entry, an equity size the equity too, a risk size a stop loss away from the entry.

```typescript
function qtyForSize(
    size: OrderSize,
    ctx: { entry?: number; stopLoss?: number; equity?: number },
): number | undefined
```

See also: [`OrderSize`](/vela-pro/api/trading#ordersize).

### `roundQty` [#roundqty]

A derived size on four significant digits (no float dust).

```typescript
function roundQty(qty: number): number
```

### `roundToTick` [#roundtotick]

`price` on the tick grid (no float dust).

```typescript
function roundToTick(price: number, tick: number): number
```

### `sanitizePresets` [#sanitizepresets]

The presets that are whole (an older shape or a hand edit is dropped), at most nine.

```typescript
function sanitizePresets(raw: unknown): TradingPreset[]
```

See also: [`TradingPreset`](/vela-pro/api/trading#tradingpreset).

### `sanitizeRiskLimits` [#sanitizerisklimits]

Only the limits that are positive numbers.

```typescript
function sanitizeRiskLimits(raw: unknown): RiskLimits
```

See also: [`RiskLimits`](/vela-pro/api/trading#risklimits).

### `trading` [#trading]

Trading as a Vela Pro plugin. Its API is the page's [`TradingController`](/vela-pro/api/trading#tradingcontroller-class).

```typescript
function trading(opts?: EnableTradingOptions): VelaProPlugin<TradingController>
```

See also: [`EnableTradingOptions`](/vela-pro/api/trading#enabletradingoptions), [`TradingController`](/vela-pro/api/trading#tradingcontroller-class), [`VelaProPlugin`](/vela-pro/api/module-sdk#velaproplugin).

### `tradingController` [#tradingcontroller]

The page's trading controller, once [`enableTrading`](/vela-pro/api/trading#enabletrading) ran.

```typescript
function tradingController(): TradingController | null
```

See also: [`TradingController`](/vela-pro/api/trading#tradingcontroller-class).

## Classes [#classes]

### `OrderTicketWidget` [#orderticketwidget]

```typescript
class OrderTicketWidget {
    constructor(props: OrderTicketProps);
    readonly el: HTMLElement;
    update(next: Partial<Omit<OrderTicketProps, 'controller'>>): void;
    destroy(): void;
}
```

See also: [`OrderTicketProps`](/vela-pro/api/trading#orderticketprops).

### `PaperBroker` [#paperbroker]

```typescript
class PaperBroker implements Broker {
    constructor(opts?: PaperBrokerOptions);
    readonly capabilities: BrokerCapabilities;
    readonly accounts: BrokerAccounts;
    readonly info: BrokerInfo;
    state(): BrokerState;
    subscribe(listener: () => void): () => void;
    placeOrder(req: OrderRequest): Promise<void>;
    modifyOrder(orderId: string, patch: OrderPatch): Promise<void>;
    cancelOrder(orderId: string): Promise<void>;
    closePosition(symbol: string, qty?: number): Promise<void>;
    reversePosition(symbol: string): Promise<void>;
    onPrice(symbol: string, price: number, time: number): void;
    reset(): void;
    destroy(): void;
    lastPrice(symbol: string): number | undefined;
}
```

| Member              | Type                                                    | Description                                                                                                                                               |
| ------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `constructor`       | `(opts?: PaperBrokerOptions)`                           |                                                                                                                                                           |
| `capabilities`      | `BrokerCapabilities`                                    |                                                                                                                                                           |
| `accounts`          | `BrokerAccounts`                                        | Several accounts, for a broker that has them.                                                                                                             |
| `info`              | `BrokerInfo`                                            |                                                                                                                                                           |
| `state()`           | `() => BrokerState`                                     |                                                                                                                                                           |
| `subscribe()`       | `(listener: () => void) => () => void`                  | Called after every change of `state()`. Returns the unsubscribe.                                                                                          |
| `placeOrder()`      | `(req: OrderRequest) => Promise<void>`                  |                                                                                                                                                           |
| `modifyOrder()`     | `(orderId: string, patch: OrderPatch) => Promise<void>` |                                                                                                                                                           |
| `cancelOrder()`     | `(orderId: string) => Promise<void>`                    |                                                                                                                                                           |
| `closePosition()`   | `(symbol: string, qty?: number) => Promise<void>`       | Close `qty` of the position (default: all of it).                                                                                                         |
| `reversePosition()` | `(symbol: string) => Promise<void>`                     |                                                                                                                                                           |
| `onPrice()`         | `(symbol: string, price: number, time: number) => void` | The charts' prices, as they arrive. A simulator fills against them; a real broker, which has its own feed, may ignore them or use them to mark positions. |
| `reset()`           | `() => void`                                            | Start over (a simulator's reset).                                                                                                                         |
| `destroy()`         | `() => void`                                            |                                                                                                                                                           |
| `lastPrice()`       | `(symbol: string) => number \| undefined`               | The last price seen for `symbol`.                                                                                                                         |

See also: [`Broker`](/vela-pro/api/trading#broker), [`BrokerAccounts`](/vela-pro/api/trading#brokeraccounts), [`BrokerCapabilities`](/vela-pro/api/trading#brokercapabilities), [`BrokerInfo`](/vela-pro/api/trading#brokerinfo), [`BrokerState`](/vela-pro/api/trading#brokerstate), [`OrderPatch`](/vela-pro/api/trading#orderpatch), [`OrderRequest`](/vela-pro/api/trading#orderrequest), [`PaperBrokerOptions`](/vela-pro/api/trading#paperbrokeroptions).

### `TradeCard` [#tradecard]

```typescript
class TradeCard {
    constructor(controller: () => TradingController | null);
    readonly el: HTMLDivElement;
    update(symbol: string): void;
    destroy(): void;
}
```

See also: [`TradingController`](/vela-pro/api/trading#tradingcontroller-class).

### `TradingController` class [#tradingcontroller-class]

```typescript
class TradingController {
    constructor(opts: TradingControllerOptions);
    readonly broker: Broker;
    readonly qtyPresets: readonly number[];
    readonly display: TradingDisplayState;
    readonly safety: TradingSafety;
    readonly draft: DraftOrder | null;
    readonly selection: ReadonlySet<string>;
    readonly lastDraftEnd: 'submitted' | 'discarded' | null;
    readonly presets: readonly TradingPreset[];
    readonly sizing: OrderSize | null;
    readonly displayChanges: TradingDisplayPatch;
    state(): BrokerState;
    lastPrice(symbol: string): number | undefined;
    lastTime(symbol: string): number | undefined;
    tickSize(symbol: string): number;
    qtyFor(symbol: string): number;
    atrOf(symbol: string): number | undefined;
    notePrice(symbol: string, price: number, time: number): void;
    noteTick(symbol: string, tick: number): void;
    noteAtr(symbol: string, atr: number): void;
    setDisplay(patch: Partial<TradingDisplayState>): void;
    restoreDisplayChanges(changes: unknown): void;
    setAskBeforePlacing(on: boolean): void;
    setKillSwitch(on: boolean): Promise<{ canceled: number; stillOpen: number }>;
    setConfirmer(confirmer: PlaceConfirmer): () => void;
    setRiskLimits(limits: RiskLimits): void;
    setQty(symbol: string, qty: number): void;
    setSizing(symbol: string, size: OrderSize): void;
    setPresets(list: readonly TradingPreset[]): void;
    savePreset(name: string): TradingPreset | null;
    removePreset(id: string): void;
    applyPreset(id: string, symbol: string): void;
    trade(
        symbol: string,
        side: OrderSide,
        opts?: { price?: number; qty?: number; forceDraft?: boolean },
    ): void;
    openDraft(draft: DraftOrder): void;
    setDraft(patch: Partial<DraftOrder>): void;
    discardDraft(): void;
    submitDraft(): Promise<boolean>;
    cancelOrder(orderId: string): Promise<boolean>;
    closePosition(symbol: string, qty?: number): Promise<boolean>;
    reversePosition(symbol: string): Promise<boolean>;
    cancelAll(symbol?: string): Promise<boolean>;
    flatten(symbol: string): Promise<boolean>;
    breakEven(symbol: string): Promise<boolean>;
    handleIntent(symbol: string, intent: TradingIntent): void;
    onChange(cb: (what: TradingChange) => void): () => void;
    onError(cb: (message: string) => void): () => void;
    destroy(): void;
    riskRefusal(order: { symbol: string; side: OrderSide; type: OrderType; qty: number; price?: number; reduceOnly?: boolean }): string | null;
}
```

| Member                    | Type                                                                                                       | Description                                                                                                                                                                                                          |
| ------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `constructor`             | `(opts: TradingControllerOptions)`                                                                         |                                                                                                                                                                                                                      |
| `broker`                  | `Broker`                                                                                                   |                                                                                                                                                                                                                      |
| `qtyPresets`              | `readonly number[]`                                                                                        |                                                                                                                                                                                                                      |
| `display`                 | `TradingDisplayState`                                                                                      |                                                                                                                                                                                                                      |
| `safety`                  | `TradingSafety`                                                                                            |                                                                                                                                                                                                                      |
| `draft`                   | `DraftOrder \| null`                                                                                       |                                                                                                                                                                                                                      |
| `selection`               | `ReadonlySet<string>`                                                                                      |                                                                                                                                                                                                                      |
| `lastDraftEnd`            | `'submitted' \| 'discarded' \| null`                                                                       | How the last draft ended: a surface showing it reacts differently to a Place and a discard.                                                                                                                          |
| `presets`                 | `readonly TradingPreset[]`                                                                                 |                                                                                                                                                                                                                      |
| `sizing`                  | `OrderSize \| null`                                                                                        | The size new orders start with when typed in another unit than the symbol's (null: in units).                                                                                                                        |
| `displayChanges`          | `TradingDisplayPatch`                                                                                      | The display settings that differ from the ones the controller was built with: the user's own. Saving these, not the whole state, lets a setting the user never touched keep following the host's option.             |
| `state()`                 | `() => BrokerState`                                                                                        |                                                                                                                                                                                                                      |
| `lastPrice()`             | `(symbol: string) => number \| undefined`                                                                  |                                                                                                                                                                                                                      |
| `lastTime()`              | `(symbol: string) => number \| undefined`                                                                  |                                                                                                                                                                                                                      |
| `tickSize()`              | `(symbol: string) => number`                                                                               |                                                                                                                                                                                                                      |
| `qtyFor()`                | `(symbol: string) => number`                                                                               |                                                                                                                                                                                                                      |
| `atrOf()`                 | `(symbol: string) => number \| undefined`                                                                  | The chart's average true range for `symbol` (14 bars of its timeframe), once reported.                                                                                                                               |
| `notePrice()`             | `(symbol: string, price: number, time: number) => void`                                                    |                                                                                                                                                                                                                      |
| `noteTick()`              | `(symbol: string, tick: number) => void`                                                                   |                                                                                                                                                                                                                      |
| `noteAtr()`               | `(symbol: string, atr: number) => void`                                                                    | The chart's ATR for `symbol`; with several charts on it, the last one to report.                                                                                                                                     |
| `setDisplay()`            | `(patch: Partial<TradingDisplayState>) => void`                                                            |                                                                                                                                                                                                                      |
| `restoreDisplayChanges()` | `(changes: unknown) => void`                                                                               | Put saved `displayChanges` back, over the settings the controller was built with (untrusted input).                                                                                                                  |
| `setAskBeforePlacing()`   | `(on: boolean) => void`                                                                                    |                                                                                                                                                                                                                      |
| `setKillSwitch()`         | `(on: boolean) => Promise<{ canceled: number; stillOpen: number }>`                                        | Turn the kill switch on (refuse every new order and cancel the working ones; open positions stay open) or off. Returns how many working orders were canceled and how many are still working.                         |
| `setConfirmer()`          | `(confirmer: PlaceConfirmer) => () => void`                                                                | Where questions go when asking before placing is on (the trading UI sets a dialog). Several can be set, one per shell: the newest asks. Returns the release, which hands the question back to the one set before it. |
| `setRiskLimits()`         | `(limits: RiskLimits) => void`                                                                             | Every opening order is checked against `limits` (an empty object: none).                                                                                                                                             |
| `setQty()`                | `(symbol: string, qty: number) => void`                                                                    | A size in units: what charts and the ticket start with on `symbol`. Sizing in another unit stops.                                                                                                                    |
| `setSizing()`             | `(symbol: string, size: OrderSize) => void`                                                                | Size new orders by `size` (in units: as `setQty`); the draft follows it.                                                                                                                                             |
| `setPresets()`            | `(list: readonly TradingPreset[]) => void`                                                                 |                                                                                                                                                                                                                      |
| `savePreset()`            | `(name: string) => TradingPreset \| null`                                                                  | Keep the draft's setup (its size, exits as distances, time in force) as a preset; null without a draft or room.                                                                                                      |
| `removePreset()`          | `(id: string) => void`                                                                                     |                                                                                                                                                                                                                      |
| `applyPreset()`           | `(id: string, symbol: string) => void`                                                                     | Set the order up as the preset says: on `symbol`'s draft, or a new buy at the market.                                                                                                                                |
| `trade()`                 | `(symbol: string, side: OrderSide, opts?: { price?: number; qty?: number; forceDraft?: boolean }) => void` | A Buy/Sell press: at the market (or resting at `price`), at once when one-click trading is on (else set up as the draft for the user to review and place).                                                           |
| `openDraft()`             | `(draft: DraftOrder) => void`                                                                              |                                                                                                                                                                                                                      |
| `setDraft()`              | `(patch: Partial<DraftOrder>) => void`                                                                     |                                                                                                                                                                                                                      |
| `discardDraft()`          | `() => void`                                                                                               |                                                                                                                                                                                                                      |
| `submitDraft()`           | `() => Promise<boolean>`                                                                                   | Send the draft; it closes once the broker accepted it.                                                                                                                                                               |
| `cancelOrder()`           | `(orderId: string) => Promise<boolean>`                                                                    |                                                                                                                                                                                                                      |
| `closePosition()`         | `(symbol: string, qty?: number) => Promise<boolean>`                                                       |                                                                                                                                                                                                                      |
| `reversePosition()`       | `(symbol: string) => Promise<boolean>`                                                                     |                                                                                                                                                                                                                      |
| `cancelAll()`             | `(symbol?: string) => Promise<boolean>`                                                                    |                                                                                                                                                                                                                      |
| `flatten()`               | `(symbol: string) => Promise<boolean>`                                                                     | Cancel the symbol's orders and close its position.                                                                                                                                                                   |
| `breakEven()`             | `(symbol: string) => Promise<boolean>`                                                                     | Move the position's stop to its entry price (or add one there).                                                                                                                                                      |
| `handleIntent()`          | `(symbol: string, intent: TradingIntent) => void`                                                          | Carry out a gesture made on `symbol`'s chart.                                                                                                                                                                        |
| `onChange()`              | `(cb: (what: TradingChange) => void) => () => void`                                                        |                                                                                                                                                                                                                      |
| `onError()`               | `(cb: (message: string) => void) => () => void`                                                            |                                                                                                                                                                                                                      |
| `destroy()`               | `() => void`                                                                                               |                                                                                                                                                                                                                      |
| `riskRefusal()`           | `(order: { symbol: string; side: OrderSide; type: OrderType; qty: number; …` (truncated; see declaration)  | Why the risk limits refuse `order`, or null. An order that only reduces the position is never refused; prices default to the last one.                                                                               |

See also: [`Broker`](/vela-pro/api/trading#broker), [`BrokerState`](/vela-pro/api/trading#brokerstate), [`DraftOrder`](/vela-pro/api/trading#draftorder), [`OrderSide`](/vela-pro/api/trading#orderside), [`OrderSize`](/vela-pro/api/trading#ordersize), [`OrderType`](/vela-pro/api/trading#ordertype), [`PlaceConfirmer`](/vela-pro/api/trading#placeconfirmer), [`RiskLimits`](/vela-pro/api/trading#risklimits), [`TradingChange`](/vela-pro/api/trading#tradingchange), [`TradingControllerOptions`](/vela-pro/api/trading#tradingcontrolleroptions), [`TradingDisplayPatch`](/vela-pro/api/trading#tradingdisplaypatch), [`TradingDisplayState`](/vela-pro/api/trading#tradingdisplaystate), [`TradingIntent`](/vela-pro/api/trading#tradingintent), [`TradingPreset`](/vela-pro/api/trading#tradingpreset), [`TradingSafety`](/vela-pro/api/trading#tradingsafety).

### `TradingPanelWidget` [#tradingpanelwidget]

```typescript
class TradingPanelWidget {
    constructor(props: TradingPanelProps);
    readonly el: HTMLElement;
    update(next: Partial<Omit<TradingPanelProps, 'controller'>>): void;
    destroy(): void;
}
```

See also: [`TradingPanelProps`](/vela-pro/api/trading#tradingpanelprops).

## Interfaces and types [#interfaces-and-types]

### `AccountSummary` [#accountsummary]

```typescript
interface AccountSummary {
    currency: string;
    balance: number;
    equity: number;
    unrealizedPnl: number;
    realizedPnl: number;
    initialBalance?: number;
}
```

| Member            | Type     | Description                                                        |
| ----------------- | -------- | ------------------------------------------------------------------ |
| `currency`        | `string` |                                                                    |
| `balance`         | `number` | Cash, realized P\&L included.                                      |
| `equity`          | `number` | Balance plus the open positions' unrealized P\&L.                  |
| `unrealizedPnl`   | `number` |                                                                    |
| `realizedPnl`     | `number` |                                                                    |
| `initialBalance?` | `number` | What the account started with (a simulator's), for return figures. |

### `Broker` [#broker]

A broker the trading UI drives. Methods reject with an `Error` whose message the UI shows; state changes reach the UI through `subscribe`, never through return values: an order placed shows once the broker reports it.

```typescript
interface Broker {
    readonly info: BrokerInfo;
    readonly capabilities: BrokerCapabilities;
    readonly accounts?: BrokerAccounts;
    state(): BrokerState;
    subscribe(listener: () => void): () => void;
    placeOrder(req: OrderRequest): Promise<void>;
    modifyOrder(orderId: string, patch: OrderPatch): Promise<void>;
    cancelOrder(orderId: string): Promise<void>;
    closePosition(symbol: string, qty?: number): Promise<void>;
    reversePosition?(symbol: string): Promise<void>;
    onPrice?(symbol: string, price: number, time: number): void;
    setKillSwitch?(on: boolean): Promise<{ canceled: number; stillOpen: number }>;
    reset?(): void;
    destroy?(): void;
}
```

| Member               | Type                                                                | Description                                                                                                                                                                                   |
| -------------------- | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `info`               | `BrokerInfo`                                                        |                                                                                                                                                                                               |
| `capabilities`       | `BrokerCapabilities`                                                |                                                                                                                                                                                               |
| `accounts?`          | `BrokerAccounts`                                                    | Several accounts, for a broker that has them.                                                                                                                                                 |
| `state()`            | `() => BrokerState`                                                 |                                                                                                                                                                                               |
| `subscribe()`        | `(listener: () => void) => () => void`                              | Called after every change of `state()`. Returns the unsubscribe.                                                                                                                              |
| `placeOrder()`       | `(req: OrderRequest) => Promise<void>`                              |                                                                                                                                                                                               |
| `modifyOrder()`      | `(orderId: string, patch: OrderPatch) => Promise<void>`             |                                                                                                                                                                                               |
| `cancelOrder()`      | `(orderId: string) => Promise<void>`                                |                                                                                                                                                                                               |
| `closePosition()`    | `(symbol: string, qty?: number) => Promise<void>`                   | Close `qty` of the position (default: all of it).                                                                                                                                             |
| `reversePosition?()` | `(symbol: string) => Promise<void>`                                 |                                                                                                                                                                                               |
| `onPrice?()`         | `(symbol: string, price: number, time: number) => void`             | The charts' prices, as they arrive. A simulator fills against them; a real broker, which has its own feed, may ignore them or use them to mark positions.                                     |
| `setKillSwitch?()`   | `(on: boolean) => Promise<{ canceled: number; stillOpen: number }>` | The account's own kill switch, for a broker that keeps one: refuse new orders and cancel the working ones. Without it the UI refuses orders itself and cancels the working orders one by one. |
| `reset?()`           | `() => void`                                                        | Start over (a simulator's reset).                                                                                                                                                             |
| `destroy?()`         | `() => void`                                                        |                                                                                                                                                                                               |

See also: [`BrokerAccounts`](/vela-pro/api/trading#brokeraccounts), [`BrokerCapabilities`](/vela-pro/api/trading#brokercapabilities), [`BrokerInfo`](/vela-pro/api/trading#brokerinfo), [`BrokerState`](/vela-pro/api/trading#brokerstate), [`OrderPatch`](/vela-pro/api/trading#orderpatch), [`OrderRequest`](/vela-pro/api/trading#orderrequest).

### `BrokerAccount` [#brokeraccount]

One account a broker can trade on.

```typescript
interface BrokerAccount {
    id: string;
    name: string;
    paper?: boolean;
    currency?: string;
    initialBalance?: number;
}
```

| Member            | Type      | Description                           |
| ----------------- | --------- | ------------------------------------- |
| `id`              | `string`  |                                       |
| `name`            | `string`  |                                       |
| `paper?`          | `boolean` |                                       |
| `currency?`       | `string`  |                                       |
| `initialBalance?` | `number`  | What a simulated account starts with. |

### `BrokerAccounts` [#brokeraccounts]

A broker's accounts: the trading UI lists them and switches between them, and manages the simulated ones when the broker offers the optional methods. After a switch, `state()` and `info` describe the account switched to.

```typescript
interface BrokerAccounts {
    list(): readonly BrokerAccount[];
    activeId(): string;
    switchTo(id: string): Promise<void>;
    create?(opts: { name: string; initialBalance?: number; currency?: string }): Promise<string>;
    rename?(id: string, name: string): Promise<void>;
    reset?(id: string, opts?: { initialBalance?: number }): Promise<void>;
    remove?(id: string): Promise<void>;
}
```

| Member       | Type                                                                                      | Description                                                             |
| ------------ | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `list()`     | `() => readonly BrokerAccount[]`                                                          |                                                                         |
| `activeId()` | `() => string`                                                                            |                                                                         |
| `switchTo()` | `(id: string) => Promise<void>`                                                           |                                                                         |
| `create?()`  | `(opts: { name: string; initialBalance?: number; currency?: string }) => Promise<string>` | Open a simulated account; resolves with its id (it is not switched to). |
| `rename?()`  | `(id: string, name: string) => Promise<void>`                                             |                                                                         |
| `reset?()`   | `(id: string, opts?: { initialBalance?: number }) => Promise<void>`                       | Start the account over, with a new starting balance when given.         |
| `remove?()`  | `(id: string) => Promise<void>`                                                           | Drop the account; the last one stays.                                   |

See also: [`BrokerAccount`](/vela-pro/api/trading#brokeraccount).

### `BrokerCapabilities` [#brokercapabilities]

```typescript
interface BrokerCapabilities {
    orderTypes: readonly OrderType[];
    brackets: boolean;
    modify: boolean;
    reverse: boolean;
    timeInForce?: readonly TimeInForce[];
    postOnly?: boolean;
    extendedHours?: boolean;
}
```

| Member           | Type                     | Description                                                                       |
| ---------------- | ------------------------ | --------------------------------------------------------------------------------- |
| `orderTypes`     | `readonly OrderType[]`   |                                                                                   |
| `brackets`       | `boolean`                | Take-profit / stop-loss exits attached to an entry.                               |
| `modify`         | `boolean`                | Live orders can be changed in place (else a move cancels and replaces).           |
| `reverse`        | `boolean`                |                                                                                   |
| `timeInForce?`   | `readonly TimeInForce[]` | The times in force it accepts, its default first. Without: orders go without one. |
| `postOnly?`      | `boolean`                | Limits can be marked post-only.                                                   |
| `extendedHours?` | `boolean`                | Orders can work outside regular trading hours.                                    |

See also: [`OrderType`](/vela-pro/api/trading#ordertype), [`TimeInForce`](/vela-pro/api/trading#timeinforce).

### `BrokerInfo` [#brokerinfo]

```typescript
interface BrokerInfo {
    id: string;
    name: string;
    paper?: boolean;
}
```

| Member   | Type      | Description                                                       |
| -------- | --------- | ----------------------------------------------------------------- |
| `id`     | `string`  |                                                                   |
| `name`   | `string`  | What the UI calls the account (`Paper Trading`, an account name). |
| `paper?` | `boolean` | A simulated account (the UI badges it).                           |

### `BrokerState` [#brokerstate]

```typescript
interface BrokerState {
    account: AccountSummary;
    positions: Position[];
    orders: Order[];
    history: Order[];
    fills: Fill[];
    trades: ClosedTrade[];
}
```

| Member      | Type             | Description                             |
| ----------- | ---------------- | --------------------------------------- |
| `account`   | `AccountSummary` |                                         |
| `positions` | `Position[]`     |                                         |
| `orders`    | `Order[]`        | Live orders: working, held and pending. |
| `history`   | `Order[]`        | Finished orders, newest first.          |
| `fills`     | `Fill[]`         | Fills, newest first.                    |
| `trades`    | `ClosedTrade[]`  | Closed round trips, newest first.       |

See also: [`AccountSummary`](/vela-pro/api/trading#accountsummary), [`ClosedTrade`](/vela-pro/api/trading#closedtrade), [`Fill`](/vela-pro/api/trading#fill), [`Order`](/vela-pro/api/trading#order), [`Position`](/vela-pro/api/trading#position).

### `ClosedTrade` [#closedtrade]

One finished round trip: an entry and the exit that closed it.

```typescript
interface ClosedTrade {
    id: string;
    symbol: string;
    side: 'long' | 'short';
    qty: number;
    entryPrice: number;
    exitPrice: number;
    entryTime: number;
    exitTime: number;
    pnl: number;
}
```

### `DraftOrder` [#draftorder]

The order being set up: shown on the chart as draft lines and in the order panel.

```typescript
interface DraftOrder {
    symbol: string;
    side: OrderSide;
    type: Exclude<OrderType, 'stop-limit'>;
    qty: number;
    price?: number;
    takeProfit?: number;
    stopLoss?: number;
    timeInForce?: TimeInForce;
    postOnly?: boolean;
    extendedHours?: boolean;
    size?: OrderSize;
    exits?: ExitSpec;
}
```

| Member           | Type                               | Description                                                                               |
| ---------------- | ---------------------------------- | ----------------------------------------------------------------------------------------- |
| `symbol`         | `string`                           |                                                                                           |
| `side`           | `OrderSide`                        |                                                                                           |
| `type`           | `Exclude<OrderType, 'stop-limit'>` |                                                                                           |
| `qty`            | `number`                           |                                                                                           |
| `price?`         | `number`                           | The limit/stop price (absent for market).                                                 |
| `takeProfit?`    | `number`                           |                                                                                           |
| `stopLoss?`      | `number`                           |                                                                                           |
| `timeInForce?`   | `TimeInForce`                      |                                                                                           |
| `postOnly?`      | `boolean`                          |                                                                                           |
| `extendedHours?` | `boolean`                          |                                                                                           |
| `size?`          | `OrderSize`                        | The size as typed in another unit than the symbol's: `qty` follows it as the price moves. |
| `exits?`         | `ExitSpec`                         | The exits typed as distances from the entry: `takeProfit` and `stopLoss` follow it.       |

See also: [`ExitSpec`](/vela-pro/api/trading#exitspec), [`OrderSide`](/vela-pro/api/trading#orderside), [`OrderSize`](/vela-pro/api/trading#ordersize), [`OrderType`](/vela-pro/api/trading#ordertype), [`TimeInForce`](/vela-pro/api/trading#timeinforce).

### `EnableTradingOptions` [#enabletradingoptions]

Options for [`enableTrading`](/vela-pro/api/trading#enabletrading).

```typescript
interface EnableTradingOptions {
    broker?: Broker;
    paper?: PaperBrokerOptions;
    defaultQty?: number;
    qtyPresets?: readonly number[];
    display?: Partial<TradingDisplayState>;
    safety?: Partial<TradingSafety>;
    presets?: readonly TradingPreset[];
    orderPanel?: boolean | { width?: number; order?: number };
    tradingPanel?: boolean | { order?: number };
    contextMenu?: boolean;
    shortcuts?: boolean;
    phoneSheet?: boolean;
}
```

| Member          | Type                                            | Description                                                                                                                                                                                                           |
| --------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `broker?`       | `Broker`                                        | What the UI trades through. Default: a [`PaperBroker`](/vela-pro/api/trading#paperbroker) (in-browser simulation).                                                                                                    |
| `paper?`        | `PaperBrokerOptions`                            | The default paper broker's options (ignored with `broker`).                                                                                                                                                           |
| `defaultQty?`   | `number`                                        | The order size charts start with (default 1).                                                                                                                                                                         |
| `qtyPresets?`   | `readonly number[]`                             | The sizes the size pickers offer.                                                                                                                                                                                     |
| `display?`      | `Partial<TradingDisplayState>`                  | Initial display settings (the user's changes persist over them).                                                                                                                                                      |
| `safety?`       | `Partial<TradingSafety>`                        | Initial safety settings: ask before placing, the kill switch, risk limits (the user's changes persist over them).                                                                                                     |
| `presets?`      | `readonly TradingPreset[]`                      | Initial order presets, at most nine: Shift+1 to Shift+9 apply them (the user's own persist over them).                                                                                                                |
| `orderPanel?`   | `boolean \| { width?: number; order?: number }` | The order panel (a side panel). `false` leaves it out: orders are then set up on the chart.                                                                                                                           |
| `tradingPanel?` | `boolean \| { order?: number }`                 | The trading panel in the bottom dock (positions, orders, history, trades).                                                                                                                                            |
| `contextMenu?`  | `boolean`                                       | Buy / sell at the pointer's price in the chart's right-click menu.                                                                                                                                                    |
| `shortcuts?`    | `boolean`                                       | Shift+B / Shift+S buy and sell the active chart's symbol.                                                                                                                                                             |
| `phoneSheet?`   | `boolean`                                       | In the shell's mobile layout, a Trade button in the bottom bar opening a sheet with the order ticket and the trading panel (default true). `false` leaves phones the order panel from the menu and the on-chart card. |

See also: [`Broker`](/vela-pro/api/trading#broker), [`PaperBrokerOptions`](/vela-pro/api/trading#paperbrokeroptions), [`TradingDisplayState`](/vela-pro/api/trading#tradingdisplaystate), [`TradingPreset`](/vela-pro/api/trading#tradingpreset), [`TradingSafety`](/vela-pro/api/trading#tradingsafety).

### `ExitContext` [#exitcontext]

What an exit distance is measured against.

```typescript
interface ExitContext {
    side: OrderSide;
    entry: number;
    qty: number;
    tick: number;
    atr?: number;
}
```

| Member  | Type        | Description                                             |
| ------- | ----------- | ------------------------------------------------------- |
| `side`  | `OrderSide` |                                                         |
| `entry` | `number`    |                                                         |
| `qty`   | `number`    |                                                         |
| `tick`  | `number`    |                                                         |
| `atr?`  | `number`    | The chart's ATR for the symbol (ATR distances need it). |

See also: [`OrderSide`](/vela-pro/api/trading#orderside).

### `ExitMode` [#exitmode]

How exits are typed: a price, or a distance from the entry in percent, ticks, ATRs or cash.

```typescript
type ExitMode = 'price' | 'pct' | 'ticks' | 'atr' | 'usd';
```

### `ExitSpec` [#exitspec]

Exits typed as distances from the entry (each leg optional).

```typescript
interface ExitSpec {
    mode: Exclude<ExitMode, 'price'>;
    takeProfit?: number;
    stopLoss?: number;
}
```

See also: [`ExitMode`](/vela-pro/api/trading#exitmode).

### `Fill` [#fill]

```typescript
interface Fill {
    id: string;
    orderId: string;
    symbol: string;
    side: OrderSide;
    qty: number;
    price: number;
    time: number;
    effect: 'open' | 'close';
    realizedPnl?: number;
    commission?: number;
}
```

| Member         | Type                | Description                                               |
| -------------- | ------------------- | --------------------------------------------------------- |
| `id`           | `string`            |                                                           |
| `orderId`      | `string`            |                                                           |
| `symbol`       | `string`            |                                                           |
| `side`         | `OrderSide`         |                                                           |
| `qty`          | `number`            |                                                           |
| `price`        | `number`            |                                                           |
| `time`         | `number`            |                                                           |
| `effect`       | `'open' \| 'close'` | Opened (or added to) a position, or closed (part of) one. |
| `realizedPnl?` | `number`            | P\&L this fill realized (closing fills).                  |
| `commission?`  | `number`            |                                                           |

See also: [`OrderSide`](/vela-pro/api/trading#orderside).

### `Order` [#order]

```typescript
interface Order {
    id: string;
    symbol: string;
    side: OrderSide;
    type: OrderType;
    qty: number;
    filledQty: number;
    limitPrice?: number;
    stopPrice?: number;
    status: OrderStatus;
    role: OrderRole;
    parentId?: string;
    ocoGroup?: string;
    reduceOnly?: boolean;
    timeInForce?: TimeInForce;
    postOnly?: boolean;
    extendedHours?: boolean;
    avgFillPrice?: number;
    createdAt: number;
    updatedAt: number;
    reason?: string;
}
```

| Member           | Type          | Description                                                               |
| ---------------- | ------------- | ------------------------------------------------------------------------- |
| `id`             | `string`      |                                                                           |
| `symbol`         | `string`      |                                                                           |
| `side`           | `OrderSide`   |                                                                           |
| `type`           | `OrderType`   |                                                                           |
| `qty`            | `number`      |                                                                           |
| `filledQty`      | `number`      |                                                                           |
| `limitPrice?`    | `number`      | A limit's price (a stop-limit's limit).                                   |
| `stopPrice?`     | `number`      | A stop's trigger.                                                         |
| `status`         | `OrderStatus` |                                                                           |
| `role`           | `OrderRole`   |                                                                           |
| `parentId?`      | `string`      | The entry a bracket exit belongs to.                                      |
| `ocoGroup?`      | `string`      | Orders sharing a group cancel each other when one fills.                  |
| `reduceOnly?`    | `boolean`     |                                                                           |
| `timeInForce?`   | `TimeInForce` |                                                                           |
| `postOnly?`      | `boolean`     | A limit refused when it would fill at once (it only ever adds liquidity). |
| `extendedHours?` | `boolean`     | Worked outside regular trading hours too.                                 |
| `avgFillPrice?`  | `number`      |                                                                           |
| `createdAt`      | `number`      |                                                                           |
| `updatedAt`      | `number`      |                                                                           |
| `reason?`        | `string`      | Why a rejected order was refused.                                         |

See also: [`OrderRole`](/vela-pro/api/trading#orderrole), [`OrderSide`](/vela-pro/api/trading#orderside), [`OrderStatus`](/vela-pro/api/trading#orderstatus), [`OrderType`](/vela-pro/api/trading#ordertype), [`TimeInForce`](/vela-pro/api/trading#timeinforce).

### `OrderPatch` [#orderpatch]

```typescript
interface OrderPatch {
    qty?: number;
    limitPrice?: number;
    stopPrice?: number;
}
```

### `OrderRequest` [#orderrequest]

```typescript
interface OrderRequest {
    symbol: string;
    side: OrderSide;
    type: OrderType;
    qty: number;
    limitPrice?: number;
    stopPrice?: number;
    takeProfit?: number;
    stopLoss?: number;
    parentId?: string;
    role?: OrderRole;
    reduceOnly?: boolean;
    timeInForce?: TimeInForce;
    postOnly?: boolean;
    extendedHours?: boolean;
}
```

| Member           | Type          | Description                                                                                |
| ---------------- | ------------- | ------------------------------------------------------------------------------------------ |
| `symbol`         | `string`      |                                                                                            |
| `side`           | `OrderSide`   |                                                                                            |
| `type`           | `OrderType`   |                                                                                            |
| `qty`            | `number`      |                                                                                            |
| `limitPrice?`    | `number`      |                                                                                            |
| `stopPrice?`     | `number`      |                                                                                            |
| `takeProfit?`    | `number`      | Exits to attach: held until the entry fills, then cancelling each other.                   |
| `stopLoss?`      | `number`      |                                                                                            |
| `parentId?`      | `string`      | Attach this order to a live entry as one of its exits.                                     |
| `role?`          | `OrderRole`   |                                                                                            |
| `reduceOnly?`    | `boolean`     |                                                                                            |
| `timeInForce?`   | `TimeInForce` | Only one the broker lists in `capabilities.timeInForce`; without it, the broker's default. |
| `postOnly?`      | `boolean`     | Only when `capabilities.postOnly`.                                                         |
| `extendedHours?` | `boolean`     | Only when `capabilities.extendedHours`.                                                    |

See also: [`OrderRole`](/vela-pro/api/trading#orderrole), [`OrderSide`](/vela-pro/api/trading#orderside), [`OrderType`](/vela-pro/api/trading#ordertype), [`TimeInForce`](/vela-pro/api/trading#timeinforce).

### `OrderRole` [#orderrole]

What an order does for its position: exits take the take-profit/stop-loss colors.

```typescript
type OrderRole = 'entry' | 'take-profit' | 'stop-loss' | 'exit';
```

### `OrderSide` [#orderside]

```typescript
type OrderSide = 'buy' | 'sell';
```

### `OrderSize` [#ordersize]

```typescript
interface OrderSize {
    mode: SizeMode;
    value: number;
}
```

See also: [`SizeMode`](/vela-pro/api/trading#sizemode).

### `OrderStatus` [#orderstatus]

`working` rests at the broker; `held` waits for its parent entry to fill (a bracket's exit); `pending` was sent and not acknowledged yet. The rest are final.

```typescript
type OrderStatus = 'pending' | 'working' | 'held' | 'filled' | 'cancelled' | 'rejected';
```

### `OrderTicketProps` [#orderticketprops]

The order ticket's props. `controller` is read once; the others can change through `update`.

```typescript
interface OrderTicketProps {
    controller: TradingController;
    symbol?: string;
    host?: HTMLElement;
    active?: boolean;
    onDiscard?: () => void;
    onNotify?: (message: string, kind: 'info' | 'success' | 'error') => void;
}
```

| Member       | Type                                                              | Description                                                                   |
| ------------ | ----------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `controller` | `TradingController`                                               | The account, its draft and its orders.                                        |
| `symbol?`    | `string`                                                          | The symbol orders are set up on.                                              |
| `host?`      | `HTMLElement`                                                     | Where confirmations mount (default: the widget's own element).                |
| `active?`    | `boolean`                                                         | Shown: it keeps a draft on the symbol. Hidden: it drops the draft.            |
| `onDiscard?` | `() => void`                                                      | The draft was discarded (the chart's ✕): a host closes what shows the ticket. |
| `onNotify?`  | `(message: string, kind: 'info' \| 'success' \| 'error') => void` | Tell the user something (the kill switch's outcome).                          |

See also: [`TradingController`](/vela-pro/api/trading#tradingcontroller-class).

### `OrderType` [#ordertype]

```typescript
type OrderType = 'market' | 'limit' | 'stop' | 'stop-limit';
```

### `PaperBrokerOptions` [#paperbrokeroptions]

```typescript
interface PaperBrokerOptions {
    initialBalance?: number;
    currency?: string;
    commissionRate?: number;
    persist?: string | false;
    name?: string;
    now?: () => number;
}
```

| Member            | Type              | Description                                                                                            |
| ----------------- | ----------------- | ------------------------------------------------------------------------------------------------------ |
| `initialBalance?` | `number`          | Starting cash (default 100,000).                                                                       |
| `currency?`       | `string`          |                                                                                                        |
| `commissionRate?` | `number`          | Commission per fill as a fraction of its notional (default 0).                                         |
| `persist?`        | `string \| false` | localStorage key the accounts persist under; `false` keeps them in memory. Default `'vela-pro.paper'`. |
| `name?`           | `string`          | The first account's name in the UI (default `Paper Trading`).                                          |
| `now?`            | `() => number`    | A clock for tests.                                                                                     |

### `PlaceConfirmer` [#placeconfirmer]

Shows the question and resolves with the user's answer (`dontAskAgain` turns asking off).

```typescript
type PlaceConfirmer = (q: PlaceQuestion) => Promise<{ ok: boolean; dontAskAgain?: boolean }>;
```

See also: [`PlaceQuestion`](/vela-pro/api/trading#placequestion).

### `PlaceQuestion` [#placequestion]

What a confirmation asks about.

```typescript
interface PlaceQuestion {
    kind: 'place' | 'move';
    symbol: string;
    side: OrderSide;
    type: OrderType;
    qty: number;
    price?: number;
    takeProfit?: number;
    stopLoss?: number;
}
```

See also: [`OrderSide`](/vela-pro/api/trading#orderside), [`OrderType`](/vela-pro/api/trading#ordertype).

### `Position` [#position]

```typescript
interface Position {
    symbol: string;
    qty: number;
    avgPrice: number;
    realizedPnl: number;
    markPrice?: number;
    unrealizedPnl?: number;
    openedAt: number;
}
```

| Member           | Type     | Description                                                            |
| ---------------- | -------- | ---------------------------------------------------------------------- |
| `symbol`         | `string` |                                                                        |
| `qty`            | `number` | Signed: long above zero, short below.                                  |
| `avgPrice`       | `number` |                                                                        |
| `realizedPnl`    | `number` | P\&L realized on this position's reductions since it opened.           |
| `markPrice?`     | `number` | The price the unrealized P\&L is marked at, when the broker knows one. |
| `unrealizedPnl?` | `number` |                                                                        |
| `openedAt`       | `number` |                                                                        |

### `RiskLimits` [#risklimits]

Limits every opening order is checked against; orders that only reduce a position never are. Unset: no limit.

```typescript
interface RiskLimits {
    maxOrderQty?: number;
    maxOrderValue?: number;
    maxPositionValue?: number;
    maxDailyLoss?: number;
    maxOpenOrders?: number;
}
```

| Member              | Type     | Description                                                            |
| ------------------- | -------- | ---------------------------------------------------------------------- |
| `maxOrderQty?`      | `number` | The largest order, in units.                                           |
| `maxOrderValue?`    | `number` | The largest order value (quantity × price), in the account's currency. |
| `maxPositionValue?` | `number` | The largest position value once the order fills.                       |
| `maxDailyLoss?`     | `number` | No new positions once the day's realized loss reaches this much.       |
| `maxOpenOrders?`    | `number` | The most working orders at once.                                       |

### `SceneInputs` [#sceneinputs]

```typescript
interface SceneInputs {
    symbol: string;
    state: BrokerState;
    draft: DraftOrder | null;
    selection: ReadonlySet<string>;
    lastPrice: number | undefined;
    tickSize: number;
}
```

See also: [`BrokerState`](/vela-pro/api/trading#brokerstate), [`DraftOrder`](/vela-pro/api/trading#draftorder).

### `SizeMode` [#sizemode]

How an order's size is typed: units of the symbol, a cash amount, a percent of the account's equity, or the cash lost should the stop loss fill.

```typescript
type SizeMode = 'units' | 'usd' | 'equity' | 'risk';
```

### `TimeInForce` [#timeinforce]

How long an order stays working: `gtc` until canceled, `day` until the session ends (a simulator: the UTC day), `ioc` fills what it can at once and cancels the rest, `fok` fills whole at once or not at all, `opg` / `cls` work only at the session's open / close.

```typescript
type TimeInForce = 'gtc' | 'day' | 'ioc' | 'fok' | 'opg' | 'cls';
```

### `TradingChange` [#tradingchange]

```typescript
type TradingChange =
    | 'broker'
    | 'draft'
    | 'display'
    | 'price'
    | 'selection'
    | 'qty'
    | 'safety'
    | 'presets';
```

### `TradingControllerOptions` [#tradingcontrolleroptions]

```typescript
interface TradingControllerOptions {
    broker: Broker;
    defaultQty?: number;
    qtyPresets?: readonly number[];
    display?: Partial<TradingDisplayState>;
    safety?: Partial<TradingSafety>;
    presets?: readonly TradingPreset[];
    sizing?: OrderSize | null;
}
```

| Member        | Type                           | Description                                           |
| ------------- | ------------------------------ | ----------------------------------------------------- |
| `broker`      | `Broker`                       |                                                       |
| `defaultQty?` | `number`                       | The order size a fresh chart starts with (default 1). |
| `qtyPresets?` | `readonly number[]`            | The sizes the size pickers offer.                     |
| `display?`    | `Partial<TradingDisplayState>` |                                                       |
| `safety?`     | `Partial<TradingSafety>`       |                                                       |
| `presets?`    | `readonly TradingPreset[]`     | Order setups kept for later (at most nine).           |
| `sizing?`     | `OrderSize \| null`            | The size new orders start with when not in units.     |

See also: [`Broker`](/vela-pro/api/trading#broker), [`OrderSize`](/vela-pro/api/trading#ordersize), [`TradingDisplayState`](/vela-pro/api/trading#tradingdisplaystate), [`TradingPreset`](/vela-pro/api/trading#tradingpreset), [`TradingSafety`](/vela-pro/api/trading#tradingsafety).

### `TradingDisplayPatch` [#tradingdisplaypatch]

Some display settings: the ones to change, or the ones that differ.

```typescript
type TradingDisplayPatch = Partial<Omit<TradingDisplayState, 'colors'>> & { colors?: Partial<TradingDisplayState['colors']> };
```

See also: [`TradingDisplayState`](/vela-pro/api/trading#tradingdisplaystate).

### `TradingDisplayState` [#tradingdisplaystate]

What the trading layer shows, and how.

```typescript
interface TradingDisplayState {
    visible: boolean;
    orders: boolean;
    positions: boolean;
    executions: boolean;
    tradePaths: boolean;
    zones: 'always' | 'hover' | 'never';
    pnl: boolean;
    quantity: boolean;
    clusterExecutions: boolean;
    labels: 'right' | 'left';
    buttons: boolean;
    spread: boolean;
    oneClick: boolean;
    lineWidth: number;
    colors: {
        buy: string;
        sell: string;
        takeProfit: string;
        stopLoss: string;
        profit: string;
        loss: string;
    };
}
```

| Member              | Type                                                                                                 | Description                                                                          |
| ------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `visible`           | `boolean`                                                                                            |                                                                                      |
| `orders`            | `boolean`                                                                                            |                                                                                      |
| `positions`         | `boolean`                                                                                            |                                                                                      |
| `executions`        | `boolean`                                                                                            |                                                                                      |
| `tradePaths`        | `boolean`                                                                                            |                                                                                      |
| `zones`             | `'always' \| 'hover' \| 'never'`                                                                     |                                                                                      |
| `pnl`               | `boolean`                                                                                            |                                                                                      |
| `quantity`          | `boolean`                                                                                            |                                                                                      |
| `clusterExecutions` | `boolean`                                                                                            |                                                                                      |
| `labels`            | `'right' \| 'left'`                                                                                  |                                                                                      |
| `buttons`           | `boolean`                                                                                            | The on-chart Buy/Sell card.                                                          |
| `spread`            | `boolean`                                                                                            | The bid/ask spread on the card.                                                      |
| `oneClick`          | `boolean`                                                                                            | A Buy/Sell press trades at once; off, it sets the order up in the order panel first. |
| `lineWidth`         | `number`                                                                                             |                                                                                      |
| `colors`            | `{ buy: string; sell: string; takeProfit: string; stopLoss: string; profit: string; loss: string; }` |                                                                                      |

### `TradingExecutionMark` [#tradingexecutionmark]

```typescript
interface TradingExecutionMark {
    id: string;
    time: number;
    price: number;
    side: 'buy' | 'sell';
    qty: number;
    effect?: 'open' | 'close';
    label: string;
}
```

### `TradingGroupLink` [#tradinggrouplink]

```typescript
interface TradingGroupLink {
    groupId: string;
    lineIds: string[];
}
```

### `TradingIntent` [#tradingintent]

A user gesture on the layer, proposed to the controller (the layer changes nothing itself).

```typescript
type TradingIntent =
    | { kind: 'drag'; lineId: string; price: number | null }
    | { kind: 'move'; lineId: string; price: number }
    | { kind: 'move-selection'; lineIds: string[]; delta: number }
    | { kind: 'action'; lineId: string; action: TradingLineActionId }
    | { kind: 'create-exit'; lineId: string; role: 'take-profit' | 'stop-loss'; price: number }
    | { kind: 'select'; lineIds: string[]; additive: boolean }
    | { kind: 'execution-click'; ids: string[] };
```

See also: [`TradingLineActionId`](/vela-pro/api/trading#tradinglineactionid).

### `TradingLine` [#tradingline]

```typescript
interface TradingLine {
    id: string;
    kind: 'order' | 'position' | 'draft';
    role: TradingLineRole;
    side: 'buy' | 'sell';
    price: number;
    limitPrice?: number;
    pendingPrice?: number;
    qty: number;
    tag: string;
    text: string;
    detail?: string;
    tone?: 'profit' | 'loss' | 'neutral';
    state: TradingLineState;
    lineStyle?: 'solid' | 'dashed' | 'dotted' | 'none';
    axisLabel?: boolean;
    draggable: boolean;
    carries?: readonly string[];
    actions: TradingLineAction[];
    buttons?: TradingLineButton[];
    menu?: TradingMenuItem[];
    handles: Array<'take-profit' | 'stop-loss'>;
    closeMenu?: TradingMenuItem[];
    selected?: boolean;
}
```

| Member          | Type                                        | Description                                                                    |
| --------------- | ------------------------------------------- | ------------------------------------------------------------------------------ |
| `id`            | `string`                                    |                                                                                |
| `kind`          | `'order' \| 'position' \| 'draft'`          |                                                                                |
| `role`          | `TradingLineRole`                           |                                                                                |
| `side`          | `'buy' \| 'sell'`                           |                                                                                |
| `price`         | `number`                                    |                                                                                |
| `limitPrice?`   | `number`                                    |                                                                                |
| `pendingPrice?` | `number`                                    |                                                                                |
| `qty`           | `number`                                    |                                                                                |
| `tag`           | `string`                                    |                                                                                |
| `text`          | `string`                                    |                                                                                |
| `detail?`       | `string`                                    |                                                                                |
| `tone?`         | `'profit' \| 'loss' \| 'neutral'`           |                                                                                |
| `state`         | `TradingLineState`                          |                                                                                |
| `lineStyle?`    | `'solid' \| 'dashed' \| 'dotted' \| 'none'` |                                                                                |
| `axisLabel?`    | `boolean`                                   |                                                                                |
| `draggable`     | `boolean`                                   |                                                                                |
| `carries?`      | `readonly string[]`                         | Lines that move along while this one is dragged (an entry's exits).            |
| `actions`       | `TradingLineAction[]`                       |                                                                                |
| `buttons?`      | `TradingLineButton[]`                       |                                                                                |
| `menu?`         | `TradingMenuItem[]`                         |                                                                                |
| `handles`       | `Array<'take-profit' \| 'stop-loss'>`       | Grips that drag a new exit out of the line.                                    |
| `closeMenu?`    | `TradingMenuItem[]`                         | The ✕ opens this menu instead of acting at once (a position's partial closes). |
| `selected?`     | `boolean`                                   |                                                                                |

See also: [`TradingLineAction`](/vela-pro/api/trading#tradinglineaction), [`TradingLineButton`](/vela-pro/api/trading#tradinglinebutton), [`TradingLineRole`](/vela-pro/api/trading#tradinglinerole), [`TradingLineState`](/vela-pro/api/trading#tradinglinestate), [`TradingMenuItem`](/vela-pro/api/trading#tradingmenuitem).

### `TradingLineAction` [#tradinglineaction]

Buttons the layer draws with its own glyph: `✕` (cancel/close/discard), `⇅` (reverse), and **Place** (submit).

```typescript
type TradingLineAction = 'cancel' | 'close' | 'discard' | 'reverse' | 'submit';
```

### `TradingLineActionId` [#tradinglineactionid]

What a press reports: a glyph button's name, or the id of a text button or menu entry.

```typescript
type TradingLineActionId = TradingLineAction | (string & {});
```

See also: [`TradingLineAction`](/vela-pro/api/trading#tradinglineaction).

### `TradingLineButton` [#tradinglinebutton]

A text button on a line's label: a single action, or a dropdown with `menu`.

```typescript
interface TradingLineButton {
    id: TradingLineActionId;
    text: string;
    title?: string;
    placement?: 'pill' | 'after';
    menu?: TradingMenuItem[];
    disabled?: boolean;
}
```

| Member       | Type                  | Description                                                             |
| ------------ | --------------------- | ----------------------------------------------------------------------- |
| `id`         | `TradingLineActionId` |                                                                         |
| `text`       | `string`              |                                                                         |
| `title?`     | `string`              |                                                                         |
| `placement?` | `'pill' \| 'after'`   | A segment of the info pill (default), or a button of its own beside it. |
| `menu?`      | `TradingMenuItem[]`   |                                                                         |
| `disabled?`  | `boolean`             |                                                                         |

See also: [`TradingLineActionId`](/vela-pro/api/trading#tradinglineactionid), [`TradingMenuItem`](/vela-pro/api/trading#tradingmenuitem).

### `TradingLineRole` [#tradinglinerole]

```typescript
type TradingLineRole = 'entry' | 'take-profit' | 'stop-loss' | 'exit' | 'position';
```

### `TradingLineState` [#tradinglinestate]

`working`/`position` solid; `pending`/`held`/`draft` dashed; `cancelling` faded.

```typescript
type TradingLineState = 'working' | 'pending' | 'held' | 'cancelling' | 'position' | 'draft';
```

### `TradingMenuItem` [#tradingmenuitem]

```typescript
interface TradingMenuItem {
    action: TradingLineActionId;
    label: string;
    disabled?: boolean;
    separatorBefore?: boolean;
    checked?: boolean;
    hint?: string;
}
```

See also: [`TradingLineActionId`](/vela-pro/api/trading#tradinglineactionid).

### `TradingPanelProps` [#tradingpanelprops]

The trading panel's props. `controller` is read once; the others can change through `update`.

```typescript
interface TradingPanelProps {
    controller: TradingController;
    symbol?: string;
    host?: HTMLElement;
    icons?: () => SymbolIcons | null;
    active?: boolean;
    onSelectSymbol?: (symbol: string) => void;
    onNotify?: (message: string, kind: 'info' | 'success' | 'error') => void;
    onSettingsChange?: () => void;
    onClose?: () => void;
    onCount?: (count: number | null) => void;
}
```

| Member              | Type                                                              | Description                                                              |
| ------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `controller`        | `TradingController`                                               | The account, its positions, orders and trades.                           |
| `symbol?`           | `string`                                                          | The symbol in view elsewhere: a click on another one asks to open it.    |
| `host?`             | `HTMLElement`                                                     | Where menus mount (default: the widget's own element).                   |
| `icons?`            | `() => SymbolIcons \| null`                                       | Symbol logos (the chart's data, or anything that answers `symbolIcon`).  |
| `active?`           | `boolean`                                                         | Shown or hidden: hidden, it skips drawing its tab.                       |
| `onSelectSymbol?`   | `(symbol: string) => void`                                        | A position or an order's symbol was clicked.                             |
| `onNotify?`         | `(message: string, kind: 'info' \| 'success' \| 'error') => void` | Tell the user something (the paper account was reset).                   |
| `onSettingsChange?` | `() => void`                                                      | A display setting changed, for a host that keeps them.                   |
| `onClose?`          | `() => void`                                                      | The close button: shown only with it.                                    |
| `onCount?`          | `(count: number \| null) => void`                                 | Open positions plus working orders, for a host's own badge (null: none). |

See also: [`SymbolIcons`](/vela-pro/api/module-sdk#symbolicons), [`TradingController`](/vela-pro/api/trading#tradingcontroller-class).

### `TradingPreset` [#tradingpreset]

An order setup kept for later. Shift+1 to Shift+9 apply the first nine.

```typescript
interface TradingPreset {
    id: string;
    name: string;
    size?: OrderSize;
    exits?: ExitSpec;
    timeInForce?: TimeInForce;
}
```

See also: [`ExitSpec`](/vela-pro/api/trading#exitspec), [`OrderSize`](/vela-pro/api/trading#ordersize), [`TimeInForce`](/vela-pro/api/trading#timeinforce).

### `TradingSafety` [#tradingsafety]

The user's safety settings.

```typescript
interface TradingSafety {
    askBeforePlacing: boolean;
    killSwitch: boolean;
    limits: RiskLimits;
}
```

| Member             | Type         | Description                                                                                    |
| ------------------ | ------------ | ---------------------------------------------------------------------------------------------- |
| `askBeforePlacing` | `boolean`    | Confirm orders from the order panel and moves on the chart before they go out.                 |
| `killSwitch`       | `boolean`    | Refuse every new order, closing orders included; working orders were canceled when it went on. |
| `limits`           | `RiskLimits` |                                                                                                |

See also: [`RiskLimits`](/vela-pro/api/trading#risklimits).

### `TradingScene` [#tradingscene]

```typescript
interface TradingScene {
    lines: TradingLine[];
    zones?: TradingZone[];
    groups?: TradingGroupLink[];
    executions?: TradingExecutionMark[];
    trades?: TradingTradePath[];
    tickSize?: number;
    lastPrice?: number;
}
```

| Member        | Type                     | Description                                                                                                         |
| ------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| `lines`       | `TradingLine[]`          |                                                                                                                     |
| `zones?`      | `TradingZone[]`          |                                                                                                                     |
| `groups?`     | `TradingGroupLink[]`     |                                                                                                                     |
| `executions?` | `TradingExecutionMark[]` |                                                                                                                     |
| `trades?`     | `TradingTradePath[]`     |                                                                                                                     |
| `tickSize?`   | `number`                 | Dragged prices snap to it.                                                                                          |
| `lastPrice?`  | `number`                 | The last price: dragging the position's label out sets a take profit on its far side, a stop loss on its near side. |

See also: [`TradingExecutionMark`](/vela-pro/api/trading#tradingexecutionmark), [`TradingGroupLink`](/vela-pro/api/trading#tradinggrouplink), [`TradingLine`](/vela-pro/api/trading#tradingline), [`TradingTradePath`](/vela-pro/api/trading#tradingtradepath), [`TradingZone`](/vela-pro/api/trading#tradingzone).

### `TradingSurface` [#tradingsurface]

Where the confirmations mount and how they tell the user: a shell, or a widget's host and its notices.

```typescript
interface TradingSurface {
    readonly host: HTMLElement;
    toast(message: string, kind?: 'info' | 'success' | 'error'): void;
}
```

### `TradingTradePath` [#tradingtradepath]

```typescript
interface TradingTradePath {
    id: string;
    side: 'long' | 'short';
    qty: number;
    entryTime: number;
    entryPrice: number;
    exitTime: number;
    exitPrice: number;
    tone: 'profit' | 'loss' | 'neutral';
}
```

### `TradingZone` [#tradingzone]

```typescript
interface TradingZone {
    trade: string;
    from: number;
    to: number;
    tone: 'profit' | 'loss';
    fromLine: string;
    toLine: string;
    start?: number;
    focused?: boolean;
}
```

## Constants [#constants]

### `EXIT_ATR_PERIOD` [#exit_atr_period]

The bars an ATR distance counts, on the chart's own timeframe.

```typescript
const EXIT_ATR_PERIOD: 14;
```

### `KILL_SWITCH_REFUSAL` [#kill_switch_refusal]

```typescript
const KILL_SWITCH_REFUSAL: 'Trading stopped: the kill switch is on. Turn it off in the order panel to trade again.';
```

### `MAX_PRESETS` [#max_presets]

One preset per Shift+digit.

```typescript
const MAX_PRESETS: 9;
```

### `ORDER_PANEL_ID` [#order_panel_id]

```typescript
const ORDER_PANEL_ID: 'vela-pro.order';
```

### `TRADE_MENU_IDS` [#trade_menu_ids]

```typescript
const TRADE_MENU_IDS: { readonly buy: 'vela-pro.trade.buy-at'; readonly sell: 'vela-pro.trade.sell-at'; readonly close: 'vela-pro.trade.close'; readonly reverse: 'vela-pro.trade.reverse'; readonly cancelAll: 'vela-pro.trade.cancel-all'; readonly buttons: 'vela-pro.trade.toggle-buttons'; readonly fills: 'vela-pro.trade.toggle-fills'; readonly paths: 'vela-pro.trade.toggle-paths' };
```

### `TRADING_NATIVE_TYPE` [#trading_native_type]

```typescript
const TRADING_NATIVE_TYPE: 'vela-pro.trading';
```

### `TRADING_PANEL_ID` [#trading_panel_id]

```typescript
const TRADING_PANEL_ID: 'vela-pro.trading';
```
