Halaman ini belum diterjemahkan, jadi ditampilkan dalam bahasa Inggris.
Trading overlay
Render positions, orders, signal markers, and trade zones directly on the chart. Designed to integrate with both manual and algorithmic trading flows.
Disabling trading
The trading overlay is on by default; the right-click order menu is not (since 1.3).
// Drop the entire trading subsystem (no orders, no positions, no overlay)
new Chart(host, { features: { trading: false } })
// Opt in to the right-click "Buy / Sell here" order menu
new Chart(host, { features: { tradingContextMenu: true } })
new ChartWidget(host, { chartOptions: { features: { tradingContextMenu: true } } }) Without the menu, native browser right-click works on the chart as expected.
Positions
chart.setPositions([{
id: 'pos-1',
side: 'buy',
entryPrice: 65_200,
quantity: 0.5,
closedQuantity: 0.1, // partial-close band on the left edge
stopLoss: 64_800,
takeProfit: 66_000,
}]) Each line has a tag at its right end, by the price axis. The entry's gives the quantity, the side and the open profit or loss, then ⇅ and ×; the stop's and the target's say what the position would make or lose there. Every price is on the axis too. Tags that would cover each other stand side by side, and the badges on the axis move apart. Drag a stop or a target by its line or by its tag.
A position with no stop-loss or no take-profit has an SL or a TP button on its
entry's tag. Press it and drag the new line where you want it, or just click to set it where it starts. A stop
starts 1% of the entry away and a target at twice the stop's distance, as a bracket does, and both start at
least 1% beyond the price now, so neither is hit the moment it is set. Letting go sends positionModify, as dragging a stop does, so a connected execution adapter applies it. lineButtons: { addStops: false } leaves the buttons out.
While a line is dragged to a price, the crosshair draws no horizontal line and no price on the axis: the
line's own tag has the price.
A price set by hand keeps to the market's grid: an order, a stop, a target or a level dragged, a bracket's and a draft order's lines, an alert dragged, the price a right-click or the “+” by the axis gives. It is on the market's price step (setMarket, or the symbol's minTick), else to the decimals the price axis shows: chart.roundPrice. The crosshair writes the price under the pointer on the same grid, so what it reads is what the “+” beside it places at.
On a market with a ceiling and a floor for the day (setPriceLimits), an order's own price keeps inside them too: its line stops at the limit when dragged past it, a bracket's entry and a draft order start and stay inside, and the menu offers no order past them, nor does the depth ladder place one. A position's stop, target and levels are not held: they are no orders of today's.
The positions, the orders and their fills can be hidden, and their lines locked. Hidden, none is drawn and none can be pressed; they are still kept and still follow the execution adapter, and a bracket or an order being placed still shows. Locked, no line or tag of theirs can be dragged, and a position offers no SL or TP to drag out; their buttons (close, cancel, reverse, trail, remove a stop) still act. In the widget, the hide and lock buttons' menus on the drawing sidebar do it.
chart.setTradingVisible(false) // isTradingVisible()
chart.setTradingLocked(true) // isTradingLocked()
chart.setIndicatorsVisible(ids, false) // several indicators at once, one undo step Orders
chart.setOrders([{
id: 'ord-1',
side: 'sell',
type: 'limit',
price: 65_500,
quantity: 0.25,
stopLoss: 66_000, // dotted until it fills
takeProfit: 64_500,
}]) The order's tag gives its quantity and its kind (0.25, Sell limit), then × to cancel it; its tag on the price axis carries the price, written as the axis writes it.
An order that opens with a stop and a target shows them as dotted lines, with what they would make. Drag the
line, or its tag, to modify; subscribe via chart.on('orderModify', ...).
Live execution (connect an adapter)
By default the chart emits order/position intents (orderPlace, orderModify, orderCancel, positionModify, positionClose) for your backend — it never trades itself. Connect an ExecutionAdapter and the chart instead routes those intents into the
adapter and renders the authoritative orders/positions it emits back (the adapter is
the single source of truth).
import { PaperExecutionAdapter } from '@tradecanvas/chart'
chart.connectExecution(new PaperExecutionAdapter({ markPrice: 64_000 }))
chart.on('executionError', (e) => toast(e.payload.message)) // e.payload.command: the intent that failed
// A confirmed bracket goes to it too: see Bracket orders
// chart.disconnectExecution() Implement ExecutionAdapter (it mirrors DataAdapter) to wire a
real broker / OMS: placeOrder, modifyOrder, cancelOrder, modifyPosition, closePosition, plus orders / positions / fill / error events. PaperExecutionAdapter is a virtual-fill sandbox for demos and tests.
What became of an order
Every order asked for goes out with a clientOrderId, an id of its own: the one it came with, else one
the chart gives it, and placeOrderIntent returns the order as it was sent. Until the adapter answers,
the order is on its way. orderPlaced says the adapter took it, with the order it made of it; executionError with command: 'orderPlace' and the same clientOrderId says it
was refused. An adapter's placeOrder must settle either way: resolve with the order, or reject with
why. Send the id on to a broker that takes one, and answer a repeat of it with the order already made, so that a
press sent twice is one order (the paper account does).
const sent = chart.placeOrderIntent({ side: 'buy', type: 'limit', price: 63_500, quantity: 1 })
chart.on('orderPlaced', (e) => { if (e.payload.intent.clientOrderId === sent?.clientOrderId) done(e.payload.order) })
chart.on('executionError', (e) => { if (e.payload.clientOrderId === sent?.clientOrderId) failed(e.payload.cause) }) Orders that work together, and for how long
An order's intent (chart.placeOrderIntent, the adapter's placeOrder) says more than
its price:
ocoGroup: a name shared by orders of which one cancels the others, as a target and a stop for the same exit. When one fills, the rest of the group are cancelled. Their tags on the chart read OCO.timeInForce:'gtc'(good till cancelled),'day','gtd'(good till a date:expireTime, in milliseconds), and'ioc'or'fok'for an order that fills at once or not at all.type: 'stopLimit':stopPriceis where it starts working andpricethe limit it then works at. Its line on the chart is its limit, and its stop has a line of its own in dashes and dots, tagged STOP, with its price on the axis. Dragging the order's line moves both, the room between them kept; dragging the stop's, or its tag, moves the stop alone.orderModifythen carriesnewStopPricebesidenewPrice, which the paper account follows.
// A target and a stop for one exit: whichever fills first takes the other off
chart.placeOrderIntent({ side: 'sell', type: 'limit', price: 66_000, quantity: 1, ocoGroup: 'exit' })
chart.placeOrderIntent({ side: 'sell', type: 'stop', price: 63_000, stopPrice: 63_000, quantity: 1, ocoGroup: 'exit' })
// Works until midnight UTC
chart.placeOrderIntent({ side: 'buy', type: 'limit', price: 63_500, quantity: 1, timeInForce: 'gtd', expireTime: Date.UTC(2027, 0, 1) }) The paper account does what a broker would with each. Of a group, the first to fill cancels the rest. A
stop-limit becomes a limit order at its price once the price reaches its stop, and fills only
within that limit (at the price that reached the stop, when that is within it). A 'gtd' order
comes off when the time given with setMarkPrice reaches its date (the clock's, with no time
given), and one whose date has passed is refused. An 'ioc' or 'fok' limit fills at
once, at the price there is, when that is within it, and is refused when it is not (executionError). The paper market has no size of its own, so the two are the
same there, unless it is given one (below). The widget's order ticket offers both for a limit order, and its account panel writes OCO beside
an order of a group and a dated order's date. It leaves 'day' to the app, which knows when its market's day ends.
The ticket offers good till a date for a limit and a stop order: a date and a time on the chart's own clock, a day from now to start with, and it places no order that would end in the past.
A limit that fills at once or not at all may be priced through the market: it fills at the market, and the ticket counts its value, its risk and its targets from there.
The ticket takes a stop-limit order too, with a stop price and a limit price, good till cancelled, for the day or till a date. It may fill anywhere from its stop to its limit, so its stop-loss goes beyond its stop and its take-profit beyond its limit; the account panel names it and writes both prices, the stop first.
One net position. By default the paper account opens a position for each filled order, a buy
beside a sell (positions: 'hedge'). new PaperExecutionAdapter({ positions: 'net' }) keeps one position, as a futures account does: a fill the same way adds to it at the average of their prices, a
fill the other way takes from it and realises that part (pnl on the fill), and a larger one turns
it round, the rest opening at the fill's price. A fill that adds to it brings its stops when it has them; one
that takes from it leaves the position's stops as they are; one that turns it round brings its own.
Orders that fill in parts
A limit order rests in the market and is filled as others come to it, often a part at a time. Given a fillSize, the paper account fills no more than that of a limit order at one price: a larger one
fills a part at each price that reaches its limit (each setMarkPrice), and works on for the
rest. The order stays in chart.getOrders() with its filledQuantity; each part is a
fill of its own (executionFill), whose remaining is what it left working, and the
last part takes the order off. The chart writes what has filled on the order's tag (2/5), and
the widget's account panel in its row; the tags on the order's stop and target say what the rest of it would
make, since what has filled is a position with tags of its own.
const broker = new PaperExecutionAdapter({ fillSize: 2 }) // two of a limit order at each price
chart.connectExecution(broker)
chart.placeOrderIntent({ side: 'buy', type: 'limit', price: 95, quantity: 5 })
chart.on('executionFill', (e) => console.log(e.payload.quantity, e.payload.remaining)) // 2 3, then 2 1, then 1 undefined
chart.on('ordersChange', (e) => console.log(e.payload.orders[0]?.filledQuantity)) // 2, 4, then no order The parts of one order build one position, at the average of their prices; on a net account they add to its
position, or take from it. The position has the order's stop-loss, take-profit and levels from its first
part, and a later part brings them no second time: a stop you moved since, or took off, stays as you left
it. A part that fills after its position was closed opens another, with the order's stops again. A level is
a size of the whole plan, so the first parts may not fill it: it takes no more than is open. A stop-limit
fills in parts too, once it works as a limit. A part pays its own commission, and one the account can no longer carry cancels what is left of the
order (executionError). What is left can be moved, cancelled, or end at its date, and the first
part cancels the rest of the order's group. Of an 'ioc' order what fills at once fills and the
rest is dropped (its fill says how much: its dropped, beside a quantity of less than was asked, and the
order that placeOrder gives back has its filledQuantity; the activity log writes the
rest as cancelled, and the widget says how much filled); a 'fok' order larger than the size is refused. A market order and
a stop fill whole, as do closes: the paper market takes them at the price there is, and models no slippage.
An adapter of your own reports its broker's parts the same way: the order with its filledQuantity in orders, and a fill for each.
Taking profit in parts
A position can be taken off in parts. takeProfits on an order's intent, or on a position
(chart.modifyPositionIntent), is a list of levels, each a price and the quantity that closes there. As the price reaches a level, its part is closed at the level's price
and the level goes; what the levels leave stays open for takeProfit to close, or the stop-loss.
The stop-loss closes all that is left whatever levels were waiting, a level past the take-profit is never
reached, and a level takes no more than is still open.
The chart draws a line and a tag for each (TP1 is the nearest), with its part and what that would make, and
the widget's account panel writes the nearest level and how many more there are.
chart.placeOrderIntent({
side: 'buy', type: 'market', price: 64_000, quantity: 3,
stopLoss: 63_000,
takeProfits: [{ price: 65_000, quantity: 1 }, { price: 66_000, quantity: 1 }], // a third at each
takeProfit: 67_000, // the rest
})
chart.modifyPositionIntent({ positionId: 'pos-1', takeProfits: [{ price: 65_500, quantity: 2 }] }) // all of them, anew
chart.modifyPositionIntent({ positionId: 'pos-1', takeProfits: null }) // none The paper account closes the parts (a fill each, with reason: 'takeProfit' and what it
realised) and counts them in the position's closedQuantity. It takes only levels that are a
profit from the entry, and on a net account an order that brings levels gives the position its levels, as it
gives it its stops. TP1 on the chart is the nearest level still waiting. An adapter of your own reports its
broker's. In the widget's order ticket, a take-profit can be reached in one, two or three Targets: with more than one, an even part of the quantity comes off at each target on the
way, evenly spaced from the entry, and the take-profit closes what is left. The ticket lists what comes off
where before it is placed.
A position's level is dragged on the chart as its stop-loss and take-profit are, by its line or by its tag:
the line follows the pointer, with where it was left faint behind it, and letting go raises positionModify with all the position's takeProfits, that one moved, the nearest
first. A level is a profit, so one let go at the entry or past it the losing way goes back where it was, and
nothing is raised. Of two levels within reach of a press the nearer is taken; an order's line, the stop-loss
or the take-profit at the same place is taken before a level, which its tag still moves. The levels of an
order that still waits are a plan the order brings and are not handles; nor is any while the lines are
locked.
An account with money
Given a balance, the paper account keeps its money as a broker does. What a close makes or loses
goes into the balance, open positions hold margin (their value, over leverage), and each fill
pays its commission. An order the free margin cannot carry is refused
(executionError), and so is a reverse; a waiting order whose money has gone by the time its
price comes is cancelled, which executionError says too. multiplier is what a move
of one in price is worth for one unit (a futures contract's money per point, or 1,000 where a share's
price is in thousands, as on HOSE). Without one the account takes the market's contractMultiplier from the chart it is connected to, which the widget's panel counts the positions' profit by. The account is told
before the fill that changed it, so chart.getAccount() in an executionFill listener
reads it as the fill left it. Without a balance there is no account, and any order is taken, as
before.
While positions hold margin the account says how its equity stands to it: marginLevel, the
equity as a part of the margin used (1.5 is 150%). Two levels act on it, each left out unless
given. Under marginCallLevel the account warns once, the marginCall event, and
again only after the equity has been back over the level; it closes nothing. Under stopOutLevel it closes positions at the price there is, the one losing most first, until it is
back over the level or holds none: closing one frees its margin, which may be enough. Each is a fill with reason: 'liquidation'. Both are counted as each price comes, after the orders and the stops it
reached, so a stop-loss closes its position first, and a fill that brings the equity under a level is acted
on at the next price. A position's margin is held at its entry's price, so the level moves with the equity
alone. A stop-out leaves the orders that wait working: one whose money has gone is cancelled when its price
comes. With neither level, nothing is closed and a balance can go below zero.
const broker = new PaperExecutionAdapter({
balance: 10_000,
leverage: 10, // a position holds a tenth of its value
commission: { rate: 0.0004, min: 0.1 }, // 0.04% of each fill's value, no less than 0.1; perUnit: an amount a unit
positions: 'net',
marginCallLevel: 1, // warn when the equity falls under the margin held
stopOutLevel: 0.5, // close positions when it falls under half of it
})
chart.connectExecution(broker)
chart.getAccount() // { balance, equity, unrealisedPnl, realisedPnl, marginUsed, freeMargin, commission, marginLevel? } or null
chart.on('accountChange', (e) => console.log(e.payload.account?.equity))
chart.on('executionFill', (e) => console.log(e.payload.commission, e.payload.reason)) // 'liquidation' for a stop-out
chart.on('marginCall', (e) => warn(e.payload)) // { marginLevel: 0.9, level: 1, equity, marginUsed } The widget's account panel heads its totals with the balance, the equity and the free margin, and the margin
level while there is one; it shows a margin call as a warning, and names a stop-out's fill in its history. An
adapter of your own does the same by implementing getAccount() and emitting account with an AccountSummary as its money changes, and marginCall when its broker warns.
An account of more than one symbol
A chart shows one symbol, and an account may hold many. An order, a position and a fill can each name the symbol
it is of (symbol). The chart draws those of the symbol it shows, and those that name none; what
names another symbol it keeps, and draws again when that symbol is shown. getOrders(), getPositions() and getFills() give the whole account, as ordersChange and positionsChange do; chart.getSymbol() says which of it is on the chart. An order the
chart asks for names the symbol shown (symbol in orderPlace), and the paper account
keeps it on the order, on the position it opens and on their fills. An adapter of your own for an account of
several symbols names it on each. The chart never guesses: what names no symbol is drawn on every symbol, as
before. Two names are one symbol in any case of letters, and by their ticker where one alone names its venue
(BTCUSDT and BINANCE:BTCUSDT); two that each name a venue must name the same.
A fill is a mark on one symbol's bars, so the chart gives each a symbol: its own, else its position's or its
order's, else the one shown as it came. The widget's account panel lists every symbol's rows and names the
symbol once one is of another; a position of another symbol shows the adapter's own price for it
(markPrice on the position) and the profit at that price, or neither: the chart's price is not its
own. The depth ladder marks the orders of the symbol whose book it shows.
A broker counts a position at its mark, which is not always the last trade the chart shows. Where the adapter
gives a position its markPrice, the panel's row and the chart's tag count the profit at it, for a
position of the chart's own symbol too, so the rows agree with the account's Open P&L. Send the positions
again as the mark moves. Without one, a position of the chart's symbol is counted at the chart's latest price.
With a stream (connect, switchStream) the chart knows its symbol. With bars you set
yourself, say it as you change them; ChartWidget does when its symbol is picked.
chart.setData(barsOf('ETHUSDT'))
chart.setSymbol('ETHUSDT') // draws ETHUSDT's orders and positions; '' draws all again
chart.getSymbol() // 'ETHUSDT'
chart.setPositions([
{ id: 'p1', symbol: 'BTCUSDT', side: 'buy', entryPrice: 64_000, quantity: 1, markPrice: 64_250 }, // kept, not drawn
{ id: 'p2', symbol: 'ETHUSDT', side: 'sell', entryPrice: 3_150, quantity: 2 }, // drawn
]) A price is of one symbol too. Name it as you feed the paper account, and each price works only that symbol's orders and stops and values its positions alone; a position is closed, reversed and stopped out at its own symbol's latest price, and a net account keeps one position a symbol. A price that names no symbol is the price of everything the account holds, as before. Name it on every price you feed, or on none: one that names none makes the account one market again. In a replay the chart names the symbol on the prices it feeds.
feed.onTrade((trade) => broker.setMarkPrice(trade.price, trade.time, trade.symbol)) Give it the quote too, and a market order fills at it: a buy at the ask, a sell at the bid, as the chart's
buttons and the order ticket show it, and a position closed or reversed by hand at the side that takes it out (a
long at the bid). Without both sides, with a bid over its ask, or with null, a market order fills at
the last price, as before; limit orders, stops and what positions are worth stay on the last price. A chart tells
the account connected to it the quote it shows (setBidAsk, or the ticks of its feed), of the symbol it
shows, and takes it back when another symbol is shown, when its stream is disconnected and during a replay. Feed it
yourself to an account no chart
is connected to, and say null when the quotes stop.
feed.onQuote((q) => broker.setQuote({ bid: q.bid, ask: q.ask }, q.symbol)) A price that is no longer live
The price on the chart is live while the widget's feed is connected and telling. A feed that is not connected, or
that is connected and has told nothing for a minute (feedQuietAfter, seconds), leaves the last price
standing: the status bar then says so in place of “Live”, and the ticket sends no market order and warns on any
other, whose price is the trader's own. While the feed is not connected, an order asked for in one press (the
right-click menu, the depth ladder) and a bracket or a draft order confirmed on the chart are held back too, with a
note (chart.setOrderGate is what holds the last two). Closing a position and cancelling an order are
never held back. A market that is shut (the symbol's sessions) is quiet by nature and is not judged,
and neither are a replay or bars of your own (no adapter): hold orders back there in your own orderPlace handler.
new ChartWidget(host, { adapter, symbol: 'BTCUSDT', trading: true, feedQuietAfter: 30 }) // seconds; 0: never
chart.getFeedTime() // when the stream last told anything, ms; null before it has Confirmations
A trade that one press would make is confirmed first in ChartWidget: a position closed or reversed
(its row in the account panel, its buttons on the chart), and an order from the right-click menu or the depth
ladder. The dialog says the trade in full (the side, the quantity, the price, the symbol); Enter does it, Escape
leaves it undone. confirmOrders: false is one-click trading, for a broker whose traders ask for it.
The order ticket is not asked about twice: its Place is the confirmation. On the depth ladder a press on a bid
places a buy limit at that price, joining the bids there, and a press on an ask a sell limit; each cell says so,
with the quantity, before it is pressed.
new ChartWidget(host, { adapter, symbol: 'BTCUSDT', trading: true, confirmOrders: false }) // one-click trading
chart.setPositionGuard((action, positionId, send) => ask(action, positionId).then((yes) => yes && send())) // your own, on a headless Chart The broker's order rules
An exchange's preset (setMarket) has its price steps and its lot. What a broker takes for a symbol in a
session is the broker's own, and changes with no release of the library: give it as orderRules, and
again with widget.setOrderRules as the symbol or the session changes. orderKinds are the
kinds of order the ticket offers in place of Market, Limit, Stop and Stop-limit, each by the exchange's name
(code) and the kind the chart knows it as (type): that decides whether the ticket asks a
price for it and how it is drawn, and the name goes with the order as exchangeType, for the broker. timesInForce are those taken (a kind may have its own), and lot stands over the market's.
The paper account keeps the name on the order and trades it as its type: an opening or a closing
auction is not simulated. An order from the right-click menu or the depth ladder goes out as the broker's kind of
its type, with a time in force it takes, or not at all where the broker has none (a stop on HOSE). A bracket, a
draft order dragged on the chart, and a position closed or reversed are not named: your adapter gives those the
exchange's kind. An order at the market never carries a time in force.
const widget = new ChartWidget(host, {
adapter, symbol: 'VNM', trading: true,
orderRules: {
orderKinds: [
{ code: 'LO', type: 'limit' },
{ code: 'ATO', type: 'market' },
{ code: 'ATC', type: 'market' },
{ code: 'MP', type: 'market' },
],
timesInForce: ['day'],
lot: 100,
},
})
// Another session, another list: an open ticket takes it at once
widget.setOrderRules({ orderKinds: [{ code: 'ATC', type: 'market' }, { code: 'LO', type: 'limit' }], timesInForce: ['day'], lot: 100 })
chart.on('orderPlace', (e) => send(e.payload.exchangeType ?? e.payload.type, e.payload)) // 'ATO', and type: 'market' Act on orders and positions from the chart
Order and position lines carry small buttons at their right end: × cancels an order or closes a position, ⇅ reverses a position, and an
× on a stop-loss or take-profit line removes it. They raise the same intents as the
API (orderCancel, positionClose, positionReverse, positionModify with null), so a connected adapter acts on them
and a host without one gets the events. A button acts when it is released over it:
a press that slides off does nothing. Turn any of them off with lineButtons in setTradingConfig.
chart.setTradingConfig({ lineButtons: { reverse: false } }) // keep cancel, close and remove-stops
chart.cancelOrderIntent('ord-1')
chart.closePositionIntent('pos-1')
chart.reversePositionIntent('pos-1') // close, then the same size the other way
chart.modifyPositionIntent({ positionId: 'pos-1', stopLoss: null }) // null removes the stop
chart.modifyPositionIntent({ positionId: 'pos-1', trailingStop: 150 }) // the stop trails the price by 150; null ends the trail An adapter that can reverse in one step implements reversePosition;
without it the chart closes the position and sends a market order the other way.
Orders take a stopLoss, a takeProfit and a
trailing distance that carry over to the position they open.
For adapter authors: in PositionModifyIntent, stopLoss: null (or takeProfit: null) means remove it, while a
missing field means leave it as it is. Code written as intent.stopLoss ?? position.stopLoss would keep a stop the user removed.
A trailing stop is a stop-loss that follows the price: a position's trailingStop is the distance, in price, its stop keeps behind the best price, up for a long and down for a short, and it never moves back. On the chart its tag reads TSL. A button on the stop's tag starts a trail at the stop's distance from the price now, or ends one; lineButtons: { trailStop: false } hides it. The paper account moves the stop itself. An adapter for a broker passes trailingStop on from modifyPosition (a number starts the trail, null ends it and leaves the stop where it is) and reports the position's stopLoss as the broker moves it. An order carries it too: trailingStop on an order makes the position it opens trail from the start, and a waiting order's stop reads TSL. In the order ticket it is the Trailing stop switch under the stop-loss, which trails at the stop's distance from the entry. The trail button on a stop's tag is filled while its stop is trailing.
Fills on the chart
Each fill shows as a small mark on its bar: solid where it opened a position,
hollow where it closed one. The chart records the fills an adapter reports and
emits executionFill with why it happened ('order', 'close', 'reverse', 'stopLoss', 'takeProfit') and the profit or loss it realised.
chart.on('executionFill', (e) => {
const { side, price, quantity, reason, pnl } = e.payload
})
chart.addFill({ orderId: 'o-7', side: 'buy', price: 64_150, quantity: 1, time: Date.now() })
chart.getFills() // the latest 1000
chart.getRealisedPnl() // every fill's P&L since the last clearFills
chart.clearFills()
chart.setTradingConfig({ fillMarks: false }) // no marks Right-click menus and the “+” by the price axis
A right-click on the chart emits chartContextMenu with the part that was
clicked ('plot', 'pane', 'priceAxis' or 'timeAxis') and the price and time there. With features.priceAxisAddButton a “+” follows the crosshair along the price
axis; pressing it emits priceAxisAdd with its price. While it shows, the order
and position tags end left of it, so it never covers their buttons.
const chart = new Chart(host, { features: { priceAxisAddButton: true } })
chart.on('chartContextMenu', (e) => {
const { area, x, y, price, time } = e.payload
openMyMenu(x, y)
})
chart.on('priceAxisAdd', (e) => openMyMenu(e.payload.x, e.payload.y, e.payload.price)) ChartWidget builds its menus on these. Right-click the plot for an alert, a buy and a sell at that price (a limit on the side of the market where it would wait, a stop on the other), an order ticket and a horizontal line; then reset view, paste the drawings you copied, hide or remove the drawings, remove the indicators (a comparison with another symbol stays), export the data, and the settings.
Right-click the price axis for its reset, auto scale, the inverted and the left-hand scale, one of its four modes (regular, logarithmic, percentage, indexed to 100), the labels on it and the lines across the chart in two submenus, an alert at the price, and the settings open on their Scales tab. The time axis has its reset, go to date and the time zone.
An entry shows the widget's shortcut for it while that key is on: Alt + R reset view, Alt + I invert the scale, Alt + G go to date. A submenu opens on a click, Enter, → or a
pointer resting on it, and ← or Escape goes back; on a phone, where
menus open from the bottom, its first row leads back. Add your own entries with chartMenuItems (see the API reference).
Order ticket and account panel (ChartWidget)
Account in the toolbar's Trade menu opens an account panel under the chart: open positions
with their profit and loss, working orders, the fills so far with the P&L
realised, and a log of what happened to the orders. Each row closes, reverses or cancels. New order opens an
order ticket: buy or sell, market, limit or stop, quantity, price, an optional
stop-loss and take-profit, and time in force. It checks the order as you fill it in
(a buy limit goes below the market, a stop-loss on the losing side of the entry…)
and shows the reward:risk, and over the order's value what the account has free to pay for it
(freeMargin), followed by the account's currency where the adapter names one.
Placing it sends an orderPlace intent. With a
market set (chart.setMarket), it also keeps its prices on the market's step and
the order's price inside the day's ceiling and floor, starts at one lot, and takes whole lots above one
(fewer shares are an odd-lot order of their own).
Where the feed gives a bid and an ask, the ticket values, checks and sends a Buy at the ask and a Sell at the bid;
else both at the last price. With an execution adapter connected it waits for the adapter's answer: it stays open
with Sending… in place of its button and nothing to be changed, shuts once the order is taken, and
when the order is refused it keeps what was typed and says why until the order is changed. After ten seconds with no answer it says so, and waits on: check your orders before sending again. A press outside the
ticket does not shut it; Escape, Cancel and the cross do. An order asked for in one press, from the right-click menu
or a rung of the depth ladder, is for the market's lot (volumeUnit) where it has one, else for one.
The ticket names the symbol beside its title. The type and the time in force are choices in a row (the arrow keys move between them); − and + move the quantity by a lot and a price by the market's step, and a price from the chart starts rounded to that step. A stop-loss or a take-profit, switched on, says how far it is from the entry in percent and what it would make or lose; under them a receipt sums the order up: its value, its risk, its reward and the one over the other. Switching between buy and sell keeps a waiting order where it was put (a buy stop over the market becomes a sell limit), and Place takes the side's colour.
In the widget, a selected Long/Short Position drawing offers Create order in its toolbar while trading is on. It opens this ticket filled from the drawing: its side, entry as the price, stop-loss and take-profit, and the quantity its risk buys, taken down to the decimals the drawing writes. The order type follows the entry against the market, and nothing is sent until Place.
The account panel's head keeps the open P&L and the P&L realised in sight on every tab. Its figures are set right in the mono type, money to the price step's decimals in the number locale; on a phone each row is a card of named figures.
The widget says what became of an order it sent: one the adapter refused, in the adapter's own words, and one that filled in part with the rest dropped, how much of it filled.
The Log tab lists what happened to the orders, the newest first: each one placed, moved,
cancelled or filled, and what the broker refused with its reason. The chart keeps it, for a chart of your own
too: chart.getActivityLog() gives the latest 200 entries, oldest first, each { time, kind, orderId, side, type, quantity, price, reason, pnl, message } with what its kind has ('placed', 'moved', 'cancelled', 'filled', 'rejected'). It is read from the orders, fills and errors the chart is told,
by an execution adapter or by setOrders and addFill. The orders there when it began
are not in it, nor those there when an adapter is connected or taken away, or (with no adapter) when the symbol
changes: they are what is there, not orders placed. An order filled in part and then taken off is logged
cancelled. chart.clearActivityLog() empties it.
Sell and Buy on the chart. While an execution adapter is connected, the widget shows two
buttons under the chart's legend, each with the price it would trade at: the best bid on Sell and the best ask
on Buy with the spread between them (chart.setBidAsk, or a feed whose ticks carry them), else the
last price on both, as on a replay or when the feed gives one side only. A press opens the order ticket on that
side. executionChange says when an adapter is connected or taken away, bidAskChange when the bid and the ask change, and the tradeButtons switch turns the buttons off.
const widget = new ChartWidget(host, {
trading: true, // default
accountPanel: true, // default when trading is on
features: { tradeButtons: true }, // default: Sell and Buy under the legend, with a broker connected
})
widget.getChart().connectExecution(new PaperExecutionAdapter({ markPrice: 64_000 }))
widget.toggleAccountPanel(true)
// The panel follows ordersChange, positionsChange, executionFill and each tick.
widget.getChart().getActivityLog().at(-1) // { time, kind: 'filled', side: 'buy', quantity: 1, price: 64_000, reason: 'order' } Fill marks belong to the symbol on the chart: switching symbol in the widget starts the next one with none.
Drag-to-create orders
Start a single draggable order line, drag it to a price, and confirm — the order type
(limit vs stop) is inferred from where you drop it relative to the current price. Pairs
with connectExecution so a confirmed draft fills immediately.
chart.startOrderDraft('buy') // draggable line at the latest close
chart.confirmOrderDraft() // emits orderPlace -> a connected adapter fills it
chart.cancelOrderDraft() Bracket orders (drag to place)
Start a draggable bracket — entry plus stop-loss and take-profit zones — then
drag the three lines to tune entry, risk, and reward. Confirm with Enter (or the Place button), cancel with Esc. In the
widget, the green/red toolbar arrows start a long/short bracket. The chart
emits a single bracketPlace event, and sends the bracket to a connected
execution adapter (below); with none, the event is for your backend to act on.
Its size. A bracket is for the quantity it is sized with. { quantity: 2 } is
that quantity. { risk: 50 } is the money lost at the stop: the quantity is then 50 over the
stop's distance from the entry (times multiplier, what a move of one in price is worth for one
unit), rounded down to quantityStep, and follows the lines as they are dragged. The quantity is
written on the entry's tag, and bracketPlace carries it. In the widget it is typed in a field
on the bracket's bar, which starts at the quantity last typed, else at the market's lot, and widget.startBracket(side, size) takes a size too: a bracket sized by its risk has no field. bracketQuantity(bracket, size) is the same sum for your own code.
With an execution adapter connected, the chart also sends a confirmed bracket to the
adapter as one order: the entry, a limit when the price has to come back to it and a stop when it has to
run on to it, its quantity, and its stop-loss and take-profit on it. Once the adapter took it, the chart
sends bracketOrder with the order. If the adapter refuses it, it sends executionError with command: 'bracketPlace'. The widget says "placed" only then,
and says why when it was refused. A bracket with no quantity is not confirmed, since no one saw a size to
place: confirmBracket() returns false, and the bracket stays on the chart to be given one. One
confirmed before the chart has a price to tell a limit entry from a stop is not sent. executionError gives the reason ('noQuantity', 'noPrice'),
and the widget says so. An app that places the event's bracket itself connects with brackets: 'event': the bracket then stays an event, and the widget says it was confirmed.
Before 3.0 that was the default (see Moving to 3.0).
chart.startBracket('buy') // entry defaults to the latest close
chart.startBracket('sell', 64_800) // or pin the entry price
chart.startBracket('buy', undefined, { quantity: 2 }) // for two
chart.startBracket('buy', undefined, { risk: 50, quantityStep: 0.001 }) // for what loses 50 at the stop
chart.setBracketSize({ quantity: 3 }) // while it is placed
chart.getBracket() // { side, entry, stopLoss, takeProfit, quantity } or null
chart.on('bracketPlace', (e) => {
const { side, entry, stopLoss, takeProfit, quantity, riskReward } = e.payload
// with no adapter (or brackets: 'event'): submit to your OMS, then reflect fills back via chart.setOrders/setPositions
})
// The connected adapter places it
chart.connectExecution(broker)
chart.placesBrackets() // true
chart.on('bracketOrder', (e) => console.log(e.payload.order.id))
// chart.connectExecution(broker, { brackets: 'event' }) // only the event: your code places it
chart.confirmBracket() // same as Enter
chart.cancelBracket() // same as Esc Depth ladder (click to trade)
An opt-in depth-of-market ladder renders the order book as price rows with
bid/ask size columns — click an ask cell to buy, a bid cell to sell at that
price. Enable with depthLadder: true and feed the book via widget.setDepth; clicks emit orderPlace intents for
your OMS (the chart never trades itself). The same data also drives the
on-chart depth overlay.
The ladder is a page of the dock beside the chart (a sheet on a phone): open it from the Trade menu, its rail
button or widget.openPanel('depthLadder'), and take its rail button away with dock.depthLadder: false. Asks sit over bids with the spread between them, each size on a bar grown from
the price; the rows where your working orders wait carry their quantity.
const widget = new ChartWidget(host, { depthLadder: true })
widget.openPanel('depthLadder') // a page of the dock; the Trade menu opens it too
widget.setDepth({
bids: [{ price: 64_190, volume: 3.1 }, { price: 64_185, volume: 5.4 }],
asks: [{ price: 64_205, volume: 2.0 }, { price: 64_210, volume: 8.7 }],
})
widget.getChart().on('orderPlace', (e) => {
// { side, type: 'limit', price } — submit to your backend
}) Order book on the plot
features.depth draws the order book on the plot, from the right edge, for a chart that only shows
prices: it needs no orders and no trading UI, and works with trading: false. Feed it with chart.setDepthData (widget.setDepth does that too); the overlay is on once features.depth is, and setDepthOverlay changes how it looks.
mode:'cumulative'(default) adds each level to the ones nearer the market, so the bars grow away from it;'level'draws the size at each price alone, so a wall shows as one long bar.rowSize: a bar's height in price. The levels are added up into rows that far apart, so a dense book under a coarse scale, or one with empty levels, still draws even bars (match it to your footprint's rows).markBestthen lines the middle of the best rows.rowOrigin: where the rows start, in price. Row k then runs fromrowOrigin + k × rowSizeto the next row's start, and a level on a row's start is in that row. A footprint whose cells start at multiples of its row size, each tick centred on its price, lines up withrowOrigin: -tick / 2. Without it each row is centred on a multiple ofrowSize.markBest: a line at the best bid and the best ask (bestBidColor,bestAskColor).maxWidth: the longest bar in pixels (never more than the plot),bidColor,askColor.
The bars sit over the newest candles. To make room, raise rightMargin and set maxWidth to about that many bars. With trading on, setTradingConfig({ depthOverlay: { enabled: true } }) still turns it on as before.
const chart = new Chart(host, {
features: { trading: false, depth: true }, // display only: no orders, no trading UI
depthOverlay: { mode: 'level', markBest: true, maxWidth: 140 },
rightMargin: 14, // empty slots past the newest bar, room for the bars
})
chart.setDepthData(orderBook) // { bids, asks }; null clears it
chart.setDepthOverlay({ mode: 'cumulative' }) // change the look later Liquidity heatmap
Accumulate order-book snapshots into a heatmap behind the candles — each
snapshot is a vertical strip where resting size lights up per price level
(bids green, asks red). Liquidity walls that persist over time stand out.
Toggle from the settings sheet (or chart.setDepthHeatmapVisible); widget.setDepth records a snapshot on every book update.
During a replay, a book recorded with no time belongs to the live series' last bar, the heatmap
shows only the books of the bars the replay has shown, and the order book at the plot's edge,
the live market's, is hidden until the replay ends.
chart.setDepthHeatmapVisible(true)
chart.setDepthHeatmapConfig({ opacity: 0.7, capacity: 240 })
chart.setDepthHeatmapConfig({ bidColor: '#1e88e5', askColor: '#fb8c00' }) // colours of its own; null: the theme's candles'
// each book update both draws the overlay/ladder and records a heatmap column
widget.setDepth(orderBook)
// low-level: chart.pushDepthSnapshot(orderBook) · chart.clearDepthHeatmap()
// books recorded for older bars, oldest first: chart.pushDepthSnapshot(orderBook, bar.time) Signal markers
Bot or signal-trading integrations can place directional arrows on the overlay.
chart.addSignalMarker({
id: 'sig-12',
time: bar.time,
price: bar.close,
direction: 'long',
confidence: 0.86,
source: 'momentum-bot',
label: 'EMA cross',
})
// A marker under the pointer, and a click on one
chart.on('signalMarkerHover', (e) => showNote(e.payload.marker, e.payload.x, e.payload.y)) // marker null: off it
chart.on('signalMarkerClick', (e) => openSignal(e.payload.marker)) ChartWidget shows a note by a marker under the pointer: its label and source, side, price, confidence and time.
Marks
What happened at a time (a headline, an earnings date, a dividend, a split) as a small badge at the foot of the price pane, on the bar that holds its time. The pointer over a badge reads its title and text; badges that would overlap gather into one with a count. A replay shows each mark as it reaches it. Renko, Kagi, line break, point & figure and range bars draw none: their bars are not times.
chart.setMarks([
{ id: 'q3', time: reportedAt, kind: 'earnings', title: 'Q3 earnings', text: 'EPS 1.42 vs 1.31 expected' },
{ id: 'div', time: exDate, kind: 'dividend', title: 'Dividend 0.24 a share' },
{ id: 'n1', time: publishedAt, kind: 'news', title: headline, text: source, url: 'https://example.com/story' },
])
const id = chart.addMark({ time: Date.now(), title: 'Trading halted', label: 'H', color: '#e5484d' })
chart.removeMark('div')
chart.getMarks() // earliest first
chart.clearMarks()
chart.on('markClick', (e) => openStory(e.payload.marks)) // one mark, or the several a badge gathers
// a click on a badge is a markClick, not a click or a barClick
chart.on('markHover', (e) => e.payload.marks) // null: the pointer left the badge
chart.on('marksChange', (e) => e.payload.count)
new Chart(host, { features: { marks: false } }) // or chart.setFeatures({ marks: false }) kind picks the letter and the colour: news N, earnings E, dividend D, split S, and event (or none) i. label (one or two characters) and color replace them. A mark needs a title and
a time; only http(s) links are kept; a chart keeps up to 2,000. Marks are the feed's,
not the user's: saveState does not hold them, so set them again after a load.
ChartWidget puts the symbol's headlines on the chart from its news source (news, or
the adapter's fetchNews); newsMarks: false keeps them to the symbol info
panel. A click on a mark opens its link in a new tab; on a badge of several, a list of them, newest
first. The widget's marks feature switch hides every mark. Your own setMarks and clearMarks leave the widget's headlines on the chart.
Trade zones
Visualize entry → exit rectangles with P&L coloring and direction badges.
chart.addTradeZone({
id: 'tz-1',
direction: 'long',
entryTime: openedAt,
exitTime: closedAt,
entryPrice: 65_100,
exitPrice: 65_800,
}) Position label tokens
Write a position's tag your way: positionLabel takes the place of the side and the profit
after its quantity. It accepts a template string or a function returning a string.
chart.setTradingConfig({
positionLabel: '{side} @ {entry} · {pnlSign}{pnlPct}%',
}) Available tokens: {side}, {qty}, {openQty}, {closedQty}, {entry}, {price}, {pnl}, {pnlPct}, {pnlSign}.
P&L gradient stops
chart.setTradingConfig({
pnlThresholds: [
{ pnl: -Infinity, color: '#ef4444' },
{ pnl: 0, color: '#94a3b8' },
{ pnl: 500, color: '#10b981' }, // 500 or more in profit
],
}) The open profit on the tag and the band to the price take the colour of the highest stop whose pnl is at or under the position's profit or loss, in money.