Trading
API reference for @luxalgo/vela-pro-trading, including the Broker port, paper broker, controller, and trading widgets.
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 | undefinedDefault: period = EXIT_ATR_PERIOD.
buildTradingScene
function buildTradingScene(input: SceneInputs): TradingSceneSee also: SceneInputs, TradingScene.
createOrderTicket
The order ticket as a widget: { el, update, destroy }.
function createOrderTicket(props: OrderTicketProps): OrderTicketWidgetSee also: OrderTicketProps, OrderTicketWidget.
createTradingPanel
The trading panel as a widget: { el, update, destroy }.
function createTradingPanel(props: TradingPanelProps): TradingPanelWidgetSee also: TradingPanelProps, TradingPanelWidget.
defaultTradingDisplay
function defaultTradingDisplay(): TradingDisplayStateSee 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): TradingControllerSee 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 | undefinedSee 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 | undefinedSee 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): TradingDisplayStateSee 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,
): stringSee 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): numberSee 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 | undefinedSee also: OrderSize.
roundQty
A derived size on four significant digits (no float dust).
function roundQty(qty: number): numberroundToTick
price on the tick grid (no float dust).
function roundToTick(price: number, tick: number): numbersanitizePresets
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): RiskLimitsSee 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 | nullSee 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;
}| 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, 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;
}| 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, 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;
}| 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
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;
}| 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, 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;
}| Member | Type | Description |
|---|---|---|
id | string | |
name | string | |
paper? | boolean | |
currency? | string | |
initialBalance? | number | What 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>;
}| 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.
BrokerCapabilities
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, TimeInForce.
BrokerInfo
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
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, 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;
}| 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, 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;
}| Member | Type | Description |
|---|---|---|
broker? | Broker | What the UI trades through. Default: a 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, PaperBrokerOptions, TradingDisplayState, TradingPreset, TradingSafety.
ExitContext
What an exit distance is measured against.
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.
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;
}| 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.
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;
}| 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, 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;
}| 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, 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;
}| 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.
OrderType
type OrderType = 'market' | 'limit' | 'stop' | 'stop-limit';PaperBrokerOptions
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
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;
}| 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
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;
}| 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
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;
}| 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, 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;
};
}| 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
interface TradingExecutionMark {
id: string;
time: number;
price: number;
side: 'buy' | 'sell';
qty: number;
effect?: 'open' | 'close';
label: string;
}TradingGroupLink
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;
}| 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, 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;
}| 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, 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;
}| 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, 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;
}| 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.
TradingScene
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, 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';