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

Trading

API reference for @luxalgo/vela-pro-trading, including the Broker port, paper broker, controller, and trading widgets.

View as Markdown

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, Broker integration, Orders, positions, and brackets.

Functions

averageTrueRange

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

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

Default: period = EXIT_ATR_PERIOD.

buildTradingScene

function buildTradingScene(input: SceneInputs): TradingScene

See also: SceneInputs, TradingScene.

createOrderTicket

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

function createOrderTicket(props: OrderTicketProps): OrderTicketWidget

See also: OrderTicketProps, OrderTicketWidget.

createTradingPanel

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

function createTradingPanel(props: TradingPanelProps): TradingPanelWidget

See also: TradingPanelProps, TradingPanelWidget.

defaultTradingDisplay

function defaultTradingDisplay(): TradingDisplayState

See also: TradingDisplayState.

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. Call ONCE, before constructing shells. Idempotent.

function enableTrading(opts?: EnableTradingOptions): TradingController

See also: EnableTradingOptions, TradingController.

exitDistance

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

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

See also: ExitContext, ExitSpec.

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.

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

See also: ExitContext, ExitSpec.

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.

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

See also: OrderSide.

mergeTradingDisplay

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

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

See also: TradingDisplayState.

orderWords

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

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

See also: PlaceQuestion.

pnlAt

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

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

See also: OrderSide.

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.

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

See also: OrderSize.

roundQty

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

function roundQty(qty: number): number

roundToTick

price on the tick grid (no float dust).

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

sanitizePresets

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

function sanitizePresets(raw: unknown): TradingPreset[]

See also: TradingPreset.

sanitizeRiskLimits

Only the limits that are positive numbers.

function sanitizeRiskLimits(raw: unknown): RiskLimits

See also: RiskLimits.

trading

Trading as a Vela Pro plugin. Its API is the page's TradingController.

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

See also: EnableTradingOptions, TradingController, VelaProPlugin.

tradingController

The page's trading controller, once enableTrading ran.

function tradingController(): TradingController | null

See also: TradingController.

Classes

OrderTicketWidget

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

See also: OrderTicketProps.

PaperBroker

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;
}
MemberTypeDescription
constructor(opts?: PaperBrokerOptions)
capabilitiesBrokerCapabilities
accountsBrokerAccountsSeveral accounts, for a broker that has them.
infoBrokerInfo
state()() => BrokerState
subscribe()(listener: () => void) => () => voidCalled 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) => voidThe 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()() => voidStart over (a simulator's reset).
destroy()() => void
lastPrice()(symbol: string) => number | undefinedThe last price seen for symbol.

See also: Broker, BrokerAccounts, BrokerCapabilities, BrokerInfo, BrokerState, OrderPatch, OrderRequest, PaperBrokerOptions.

TradeCard

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

See also: TradingController.

TradingController class

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;
}
MemberTypeDescription
constructor(opts: TradingControllerOptions)
brokerBroker
qtyPresetsreadonly number[]
displayTradingDisplayState
safetyTradingSafety
draftDraftOrder | null
selectionReadonlySet<string>
lastDraftEnd'submitted' | 'discarded' | nullHow the last draft ended: a surface showing it reacts differently to a Place and a discard.
presetsreadonly TradingPreset[]
sizingOrderSize | nullThe size new orders start with when typed in another unit than the symbol's (null: in units).
displayChangesTradingDisplayPatchThe 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 | undefinedThe 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) => voidThe chart's ATR for symbol; with several charts on it, the last one to report.
setDisplay()(patch: Partial<TradingDisplayState>) => void
restoreDisplayChanges()(changes: unknown) => voidPut 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) => () => voidWhere 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) => voidEvery opening order is checked against limits (an empty object: none).
setQty()(symbol: string, qty: number) => voidA size in units: what charts and the ticket start with on symbol. Sizing in another unit stops.
setSizing()(symbol: string, size: OrderSize) => voidSize new orders by size (in units: as setQty); the draft follows it.
setPresets()(list: readonly TradingPreset[]) => void
savePreset()(name: string) => TradingPreset | nullKeep 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) => voidSet 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 }) => voidA 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) => voidCarry 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, BrokerState, DraftOrder, OrderSide, OrderSize, OrderType, PlaceConfirmer, RiskLimits, TradingChange, TradingControllerOptions, TradingDisplayPatch, TradingDisplayState, TradingIntent, TradingPreset, TradingSafety.

TradingPanelWidget

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

See also: TradingPanelProps.

Interfaces and types

AccountSummary

interface AccountSummary {
    currency: string;
    balance: number;
    equity: number;
    unrealizedPnl: number;
    realizedPnl: number;
    initialBalance?: number;
}
MemberTypeDescription
currencystring
balancenumberCash, realized P&L included.
equitynumberBalance plus the open positions' unrealized P&L.
unrealizedPnlnumber
realizedPnlnumber
initialBalance?numberWhat the account started with (a simulator's), for return figures.

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.

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;
}
MemberTypeDescription
infoBrokerInfo
capabilitiesBrokerCapabilities
accounts?BrokerAccountsSeveral accounts, for a broker that has them.
state()() => BrokerState
subscribe()(listener: () => void) => () => voidCalled 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) => voidThe 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?()() => voidStart over (a simulator's reset).
destroy?()() => void

See also: BrokerAccounts, BrokerCapabilities, BrokerInfo, BrokerState, OrderPatch, OrderRequest.

BrokerAccount

One account a broker can trade on.

interface BrokerAccount {
    id: string;
    name: string;
    paper?: boolean;
    currency?: string;
    initialBalance?: number;
}
MemberTypeDescription
idstring
namestring
paper?boolean
currency?string
initialBalance?numberWhat a simulated account starts with.

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.

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>;
}
MemberTypeDescription
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.

BrokerCapabilities

interface BrokerCapabilities {
    orderTypes: readonly OrderType[];
    brackets: boolean;
    modify: boolean;
    reverse: boolean;
    timeInForce?: readonly TimeInForce[];
    postOnly?: boolean;
    extendedHours?: boolean;
}
MemberTypeDescription
orderTypesreadonly OrderType[]
bracketsbooleanTake-profit / stop-loss exits attached to an entry.
modifybooleanLive orders can be changed in place (else a move cancels and replaces).
reverseboolean
timeInForce?readonly TimeInForce[]The times in force it accepts, its default first. Without: orders go without one.
postOnly?booleanLimits can be marked post-only.
extendedHours?booleanOrders can work outside regular trading hours.

See also: OrderType, TimeInForce.

BrokerInfo

interface BrokerInfo {
    id: string;
    name: string;
    paper?: boolean;
}
MemberTypeDescription
idstring
namestringWhat the UI calls the account (Paper Trading, an account name).
paper?booleanA simulated account (the UI badges it).

BrokerState

interface BrokerState {
    account: AccountSummary;
    positions: Position[];
    orders: Order[];
    history: Order[];
    fills: Fill[];
    trades: ClosedTrade[];
}
MemberTypeDescription
accountAccountSummary
positionsPosition[]
ordersOrder[]Live orders: working, held and pending.
historyOrder[]Finished orders, newest first.
fillsFill[]Fills, newest first.
tradesClosedTrade[]Closed round trips, newest first.

See also: AccountSummary, ClosedTrade, Fill, Order, Position.

ClosedTrade

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

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

DraftOrder

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

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;
}
MemberTypeDescription
symbolstring
sideOrderSide
typeExclude<OrderType, 'stop-limit'>
qtynumber
price?numberThe limit/stop price (absent for market).
takeProfit?number
stopLoss?number
timeInForce?TimeInForce
postOnly?boolean
extendedHours?boolean
size?OrderSizeThe size as typed in another unit than the symbol's: qty follows it as the price moves.
exits?ExitSpecThe exits typed as distances from the entry: takeProfit and stopLoss follow it.

See also: ExitSpec, OrderSide, OrderSize, OrderType, TimeInForce.

EnableTradingOptions

Options for enableTrading.

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;
}
MemberTypeDescription
broker?BrokerWhat the UI trades through. Default: a PaperBroker (in-browser simulation).
paper?PaperBrokerOptionsThe default paper broker's options (ignored with broker).
defaultQty?numberThe 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?booleanBuy / sell at the pointer's price in the chart's right-click menu.
shortcuts?booleanShift+B / Shift+S buy and sell the active chart's symbol.
phoneSheet?booleanIn 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, PaperBrokerOptions, TradingDisplayState, TradingPreset, TradingSafety.

ExitContext

What an exit distance is measured against.

interface ExitContext {
    side: OrderSide;
    entry: number;
    qty: number;
    tick: number;
    atr?: number;
}
MemberTypeDescription
sideOrderSide
entrynumber
qtynumber
ticknumber
atr?numberThe chart's ATR for the symbol (ATR distances need it).

See also: OrderSide.

ExitMode

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

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

ExitSpec

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

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

See also: ExitMode.

Fill

interface Fill {
    id: string;
    orderId: string;
    symbol: string;
    side: OrderSide;
    qty: number;
    price: number;
    time: number;
    effect: 'open' | 'close';
    realizedPnl?: number;
    commission?: number;
}
MemberTypeDescription
idstring
orderIdstring
symbolstring
sideOrderSide
qtynumber
pricenumber
timenumber
effect'open' | 'close'Opened (or added to) a position, or closed (part of) one.
realizedPnl?numberP&L this fill realized (closing fills).
commission?number

See also: OrderSide.

Order

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;
}
MemberTypeDescription
idstring
symbolstring
sideOrderSide
typeOrderType
qtynumber
filledQtynumber
limitPrice?numberA limit's price (a stop-limit's limit).
stopPrice?numberA stop's trigger.
statusOrderStatus
roleOrderRole
parentId?stringThe entry a bracket exit belongs to.
ocoGroup?stringOrders sharing a group cancel each other when one fills.
reduceOnly?boolean
timeInForce?TimeInForce
postOnly?booleanA limit refused when it would fill at once (it only ever adds liquidity).
extendedHours?booleanWorked outside regular trading hours too.
avgFillPrice?number
createdAtnumber
updatedAtnumber
reason?stringWhy a rejected order was refused.

See also: OrderRole, OrderSide, OrderStatus, OrderType, TimeInForce.

OrderPatch

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

OrderRequest

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;
}
MemberTypeDescription
symbolstring
sideOrderSide
typeOrderType
qtynumber
limitPrice?number
stopPrice?number
takeProfit?numberExits to attach: held until the entry fills, then cancelling each other.
stopLoss?number
parentId?stringAttach this order to a live entry as one of its exits.
role?OrderRole
reduceOnly?boolean
timeInForce?TimeInForceOnly one the broker lists in capabilities.timeInForce; without it, the broker's default.
postOnly?booleanOnly when capabilities.postOnly.
extendedHours?booleanOnly when capabilities.extendedHours.

See also: OrderRole, OrderSide, OrderType, TimeInForce.

OrderRole

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

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

OrderSide

type OrderSide = 'buy' | 'sell';

OrderSize

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

See also: SizeMode.

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.

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

OrderTicketProps

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

interface OrderTicketProps {
    controller: TradingController;
    symbol?: string;
    host?: HTMLElement;
    active?: boolean;
    onDiscard?: () => void;
    onNotify?: (message: string, kind: 'info' | 'success' | 'error') => void;
}
MemberTypeDescription
controllerTradingControllerThe account, its draft and its orders.
symbol?stringThe symbol orders are set up on.
host?HTMLElementWhere confirmations mount (default: the widget's own element).
active?booleanShown: it keeps a draft on the symbol. Hidden: it drops the draft.
onDiscard?() => voidThe draft was discarded (the chart's ✕): a host closes what shows the ticket.
onNotify?(message: string, kind: 'info' | 'success' | 'error') => voidTell the user something (the kill switch's outcome).

See also: TradingController.

OrderType

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

PaperBrokerOptions

interface PaperBrokerOptions {
    initialBalance?: number;
    currency?: string;
    commissionRate?: number;
    persist?: string | false;
    name?: string;
    now?: () => number;
}
MemberTypeDescription
initialBalance?numberStarting cash (default 100,000).
currency?string
commissionRate?numberCommission per fill as a fraction of its notional (default 0).
persist?string | falselocalStorage key the accounts persist under; false keeps them in memory. Default 'vela-pro.paper'.
name?stringThe first account's name in the UI (default Paper Trading).
now?() => numberA clock for tests.

PlaceConfirmer

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

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

See also: PlaceQuestion.

PlaceQuestion

What a confirmation asks about.

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

See also: OrderSide, OrderType.

Position

interface Position {
    symbol: string;
    qty: number;
    avgPrice: number;
    realizedPnl: number;
    markPrice?: number;
    unrealizedPnl?: number;
    openedAt: number;
}
MemberTypeDescription
symbolstring
qtynumberSigned: long above zero, short below.
avgPricenumber
realizedPnlnumberP&L realized on this position's reductions since it opened.
markPrice?numberThe price the unrealized P&L is marked at, when the broker knows one.
unrealizedPnl?number
openedAtnumber

RiskLimits

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

interface RiskLimits {
    maxOrderQty?: number;
    maxOrderValue?: number;
    maxPositionValue?: number;
    maxDailyLoss?: number;
    maxOpenOrders?: number;
}
MemberTypeDescription
maxOrderQty?numberThe largest order, in units.
maxOrderValue?numberThe largest order value (quantity × price), in the account's currency.
maxPositionValue?numberThe largest position value once the order fills.
maxDailyLoss?numberNo new positions once the day's realized loss reaches this much.
maxOpenOrders?numberThe most working orders at once.

SceneInputs

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

See also: BrokerState, DraftOrder.

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.

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

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.

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

TradingChange

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

TradingControllerOptions

interface TradingControllerOptions {
    broker: Broker;
    defaultQty?: number;
    qtyPresets?: readonly number[];
    display?: Partial<TradingDisplayState>;
    safety?: Partial<TradingSafety>;
    presets?: readonly TradingPreset[];
    sizing?: OrderSize | null;
}
MemberTypeDescription
brokerBroker
defaultQty?numberThe 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 | nullThe size new orders start with when not in units.

See also: Broker, OrderSize, TradingDisplayState, TradingPreset, TradingSafety.

TradingDisplayPatch

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

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

See also: TradingDisplayState.

TradingDisplayState

What the trading layer shows, and how.

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;
    };
}
MemberTypeDescription
visibleboolean
ordersboolean
positionsboolean
executionsboolean
tradePathsboolean
zones'always' | 'hover' | 'never'
pnlboolean
quantityboolean
clusterExecutionsboolean
labels'right' | 'left'
buttonsbooleanThe on-chart Buy/Sell card.
spreadbooleanThe bid/ask spread on the card.
oneClickbooleanA Buy/Sell press trades at once; off, it sets the order up in the order panel first.
lineWidthnumber
colors{ buy: string; sell: string; takeProfit: string; stopLoss: string; profit: string; loss: string; }

TradingExecutionMark

interface TradingExecutionMark {
    id: string;
    time: number;
    price: number;
    side: 'buy' | 'sell';
    qty: number;
    effect?: 'open' | 'close';
    label: string;
}
interface TradingGroupLink {
    groupId: string;
    lineIds: string[];
}

TradingIntent

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

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.

TradingLine

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;
}
MemberTypeDescription
idstring
kind'order' | 'position' | 'draft'
roleTradingLineRole
side'buy' | 'sell'
pricenumber
limitPrice?number
pendingPrice?number
qtynumber
tagstring
textstring
detail?string
tone?'profit' | 'loss' | 'neutral'
stateTradingLineState
lineStyle?'solid' | 'dashed' | 'dotted' | 'none'
axisLabel?boolean
draggableboolean
carries?readonly string[]Lines that move along while this one is dragged (an entry's exits).
actionsTradingLineAction[]
buttons?TradingLineButton[]
menu?TradingMenuItem[]
handlesArray<'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, TradingLineButton, TradingLineRole, TradingLineState, TradingMenuItem.

TradingLineAction

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

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

TradingLineActionId

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

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

See also: TradingLineAction.

TradingLineButton

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

interface TradingLineButton {
    id: TradingLineActionId;
    text: string;
    title?: string;
    placement?: 'pill' | 'after';
    menu?: TradingMenuItem[];
    disabled?: boolean;
}
MemberTypeDescription
idTradingLineActionId
textstring
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, TradingMenuItem.

TradingLineRole

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

TradingLineState

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

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

TradingMenuItem

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

See also: TradingLineActionId.

TradingPanelProps

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

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;
}
MemberTypeDescription
controllerTradingControllerThe account, its positions, orders and trades.
symbol?stringThe symbol in view elsewhere: a click on another one asks to open it.
host?HTMLElementWhere menus mount (default: the widget's own element).
icons?() => SymbolIcons | nullSymbol logos (the chart's data, or anything that answers symbolIcon).
active?booleanShown or hidden: hidden, it skips drawing its tab.
onSelectSymbol?(symbol: string) => voidA position or an order's symbol was clicked.
onNotify?(message: string, kind: 'info' | 'success' | 'error') => voidTell the user something (the paper account was reset).
onSettingsChange?() => voidA display setting changed, for a host that keeps them.
onClose?() => voidThe close button: shown only with it.
onCount?(count: number | null) => voidOpen positions plus working orders, for a host's own badge (null: none).

See also: SymbolIcons, TradingController.

TradingPreset

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

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

See also: ExitSpec, OrderSize, TimeInForce.

TradingSafety

The user's safety settings.

interface TradingSafety {
    askBeforePlacing: boolean;
    killSwitch: boolean;
    limits: RiskLimits;
}
MemberTypeDescription
askBeforePlacingbooleanConfirm orders from the order panel and moves on the chart before they go out.
killSwitchbooleanRefuse every new order, closing orders included; working orders were canceled when it went on.
limitsRiskLimits

See also: RiskLimits.

TradingScene

interface TradingScene {
    lines: TradingLine[];
    zones?: TradingZone[];
    groups?: TradingGroupLink[];
    executions?: TradingExecutionMark[];
    trades?: TradingTradePath[];
    tickSize?: number;
    lastPrice?: number;
}
MemberTypeDescription
linesTradingLine[]
zones?TradingZone[]
groups?TradingGroupLink[]
executions?TradingExecutionMark[]
trades?TradingTradePath[]
tickSize?numberDragged prices snap to it.
lastPrice?numberThe 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, TradingGroupLink, TradingLine, TradingTradePath, TradingZone.

TradingSurface

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

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

TradingTradePath

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

TradingZone

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

Constants

EXIT_ATR_PERIOD

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

const EXIT_ATR_PERIOD: 14;

KILL_SWITCH_REFUSAL

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

MAX_PRESETS

One preset per Shift+digit.

const MAX_PRESETS: 9;

ORDER_PANEL_ID

const ORDER_PANEL_ID: 'vela-pro.order';

TRADE_MENU_IDS

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

const TRADING_NATIVE_TYPE: 'vela-pro.trading';

TRADING_PANEL_ID

const TRADING_PANEL_ID: 'vela-pro.trading';

On this page