Order Book
Live bids and asks with depth bars, price grouping and a spread row, for a trading screen.
c2-order-book shows the resting orders of a market, like the order books of Binance, Coinbase Advanced and Kraken Pro: bids high to low, asks low to high, each row with its size, the running total from the best price and a bar sized by that total. A level whose size changes flashes green when it grew and red when it shrank.
Import
import '@c2n/components/order-book'Usage
Feeding it
bids and asks take a snapshot: { price, size } objects, or the [price, size] pairs exchange feeds send, as numbers or numeric strings. Setting either replaces that side. A stream then patches it with applyDelta(), where a size of 0 removes the level. Deltas that arrive in the same task are drawn in one render, on top of a snapshot set in that task, so replaying buffered deltas right after a snapshot works.
const book = document.querySelector('c2-order-book')!
const socket = new WebSocket('wss://example.com/book/BTC-USD')
socket.onmessage = ({ data }) => {
const message = JSON.parse(data)
if (message.type === 'snapshot') {
book.bids = message.bids
book.asks = message.asks
} else {
book.applyDelta({ bids: message.bids, asks: message.asks })
}
}Only depth levels a side are drawn (10 by default), so a deep book costs no more to render than a shallow one.
Grouping, the spread and own orders
groupmerges levels into price steps: bids round down and asks round up, so a merged level never looks better than it is.groupslists the steps the reader may pick from a select in the header, andgroup-changereports the pick.- The spread row shows the mid price and the spread; set
last-priceto show the last trade there instead, with an arrow against the previous one. own-pricesputs a dot after the prices the user has orders at, read as “your order”.
Picking a price
Clicking a row, or pressing Enter on it, fires price-select with { side, price, size, total }: the hook for filling a trade form. The rows share one tab stop, and the arrow keys, Home and End move between them. Each side is a table, captioned “Asks” and “Bids”, so a screen reader reads its columns. The spread row is deliberately not a live region: a live book would never stop talking.
Colours
The bid and ask colours default to a darker green and red in the light theme and lighter ones in the dark theme (light-dark()), so the prices keep 4.5:1 contrast on their own depth bars. The bars and the flashes are mixed from those two colours, so setting --c2-order-book__bid--color and --c2-order-book__ask--color recolours everything.