← Back to blog

Building a Crypto Feed Handler in the Browser for a Trading UI

What a feed handler does and how to build one client-side - subscriptions, normalisation, stale-message guards, caching, and conflation over exchange websockets.

Oliver Benns
Oliver Benns

Software engineer · Creator of Hedge UI


In institutional trading, a feed handler is the piece of infrastructure that sits between an exchange and everything else. It holds the connection, speaks the exchange's wire protocol, decodes the messages, normalises them into an internal format, and hands them to whatever needs market data. Banks run racks of them, written in C++ and tuned to the microsecond.

A crypto trading UI that connects straight to an exchange's public websocket has the same job to do at a much smaller scale. There is no server of yours in the middle. The browser is the feed handler. If that responsibility is not given a home, it ends up smeared across every component: a socket here, a JSON.parse there, a field called c leaking into a table cell.

This post covers what a crypto feed handler is responsible for, how to build a compact one in the browser with React, and where the one in the Hedge UI demo is honest about its limits. The whole thing is a single 242-line file, src/binance/binance-stream.ts, plus a mapper.

What a feed handler is responsible for

Strip away the scale and a feed handler has six jobs:

JobQuestion it answers
ConnectionWhich endpoint, and is it up?
SubscriptionWhich streams do we want right now?
DecodingWhat shape is this message?
ValidationIs this message still relevant?
NormalisationWhat does it mean in our model?
DistributionWho needs it, and how often?

A server-side feed handler adds sequencing, gap detection, and replay. A browser one for public market data can skip most of that, for reasons covered below, but the six jobs remain.

Connection: choosing the endpoint

The first decision is where to connect. For Binance that is not one answer. The global exchange and Binance US are separate venues with separate hosts, and a user in the United States cannot use the global one. The demo picks the base URL from a client location provider:

const useBaseUrl = () => { const location = useClientLocation(); if (location === "US") { return "wss://stream.binance.us:9443"; } return "wss://stream.binance.com"; };

The wire contracts are the same on both, so nothing downstream needs to know which venue it is talking to. The location detection itself, and its failure modes, are covered in geolocation-aware API routing.

The path matters as well. Binance offers raw streams at /ws/<streamName> and combined streams at /stream. The demo always connects to /stream, because combined streams wrap every payload in an envelope that names its source:

type Message<T> = { stream: string; data: T; };

That stream field is what makes the rest of the handler possible. Without it, a ticker message for BTC and one for ETH arriving on the same socket are distinguishable only by digging into the payload, and every message type digs differently.

Subscription: diff, do not reconnect

The naive way to change subscriptions is to close the socket and open a new one with different streams in the URL. It works, and it costs a TLS handshake and a gap in data every time the user switches market.

Binance supports live subscription management over an open connection with JSON control frames:

{ "method": "SUBSCRIBE", "params": ["btcusdt@aggTrade", "btcusdt@depth10@100ms"], "id": 1 }

So the handler's job is to keep the set of subscribed streams in sync with the set the UI currently wants. The demo does this with a hook called useMessenger, which takes the wanted stream names and diffs them against a ref of what is already subscribed:

const subs = useRef<Record<string, number>>({}); useEffect(() => { if (readyState !== ReadyState.OPEN) { return; } const newStreamNames = []; const subId = buildSubId(1, 1000000); for (const streamName of streamNames) { const existingSubId = subs.current[streamName]; if (!existingSubId) { subs.current[streamName] = subId; newStreamNames.push(streamName); } } if (newStreamNames.length === 0) { return; } sendJsonMessage({ method: "SUBSCRIBE", params: newStreamNames, id: subId, }); }, [streamNames, sendJsonMessage, readyState]);

New streams are sent in one SUBSCRIBE frame under one ID. A mirror-image effect finds streams that are subscribed but no longer wanted, groups them by the ID they were subscribed under, and sends one UNSUBSCRIBE per group. Add a symbol to a watchlist and exactly one stream is added. Nothing else on the connection is disturbed.

The calling code only declares what it wants:

const streamNames = useMemo( () => (productId ? [`${productId.toLowerCase()}@depth10@100ms`] : []), [productId], ); const { lastMessage } = useBinanceStream<BinanceOrderBook>(streamNames);

The useMemo is load-bearing. The diff runs whenever the streamNames array identity changes, so an array rebuilt on every render would re-run the effects on every render. They would find nothing to do, but it is wasted work on the hottest path in the app. The wider set of patterns for managing subscriptions is in websocket state management for crypto trading apps.

Decoding: type the wire format once

Exchange payloads are optimised for bytes on the wire. Binance's ticker message has 23 fields with single-letter names. The feed handler is where those get types and comments, so nobody has to look up the documentation twice:

export type AggTrade = { e: string; // Event type E: number; // Event time s: string; // Symbol a: number; // Aggregate trade ID p: string; // Price q: string; // Quantity f: number; // First trade ID l: number; // Last trade ID T: number; // Trade time m: boolean; // Is the buyer the market maker? M: boolean; // Ignore };

Note that p and q are typed as string. That is accurate, since Binance sends decimals as strings to avoid precision loss in JSON, and it is useful. Any code that tries to do arithmetic on a price without an explicit conversion gets a compile error. The type system is enforcing a decision point about numeric handling at the exact place it matters. More on that approach in TypeScript patterns for financial data.

useBinanceStream<T> is generic over the payload, so each caller states which message shape it expects. There is no runtime schema validation in the demo. For a public feed from a major exchange with a stable contract, that is a reasonable saving. For a feed you do not control, or one where a malformed message could mislead a user into a trade, validate at this layer.

Validation: the stale message problem

Here is the bug every hand-rolled feed handler ships at least once. The user is watching BTC. They switch to ETH. The handler sends UNSUBSCRIBE for BTC and SUBSCRIBE for ETH. For a few hundred milliseconds, the most recent message on the socket is still a BTC message. If the UI renders "the latest message", the ETH order book shows BTC prices until the first ETH message lands.

The envelope's stream field makes the fix cheap. Before a message is handed to a panel, it is checked against the streams that panel currently wants:

if (typeof lastJsonMessage === "object" && "stream" in lastJsonMessage) { const message = lastJsonMessage as Message<T>; // If we have changed products, then last message might be stale from old product. const isCurrentProduct = streamNames.includes(message.stream); if (!isCurrentProduct) { return; } return message; }

A stale message returns undefined, the panel treats that as "loading", and the spinner shows until relevant data arrives. A spinner for 200 milliseconds is correct. The wrong market's prices for 200 milliseconds is a bug report.

The same check quietly handles subscription acknowledgements. Binance answers a SUBSCRIBE with { "result": null, "id": 123 }, which has no stream key and so never reaches a panel as data.

Caching: last value per stream

Some panels want only the latest message from one stream. The order book is like that: each depth10 message is a complete picture of the top ten levels and replaces the last.

Other panels watch many streams and need the latest value of each. A watchlist of six symbols receives six interleaved ticker streams, and "the last message" is whichever symbol happened to tick most recently. For those, the handler keeps a last-value cache keyed by stream name:

const [lastMessages, setLastMessages] = useState<Record<string, T>>({}); useEffect(() => { if (!lastMessage) { return; } setLastMessages((prev) => ({ ...prev, [lastMessage.stream]: lastMessage.data, })); }, [lastMessage]);

A second effect in useStreamCache prunes entries whose stream is no longer wanted, so removing a symbol from the watchlist also drops its cached ticker. Without that, the cache grows for as long as the tab is open.

Normalisation: keep exchange shapes at the edge

The handler delivers Binance-shaped data. Panels should not render Binance-shaped data. Between the two sits a mapping step that turns wire formats into the application's own types.

For reference data, that is binance-mapper.ts, which converts an exchangeInfo symbol into a Product with display precisions derived from the PRICE_FILTER tick size and LOT_SIZE step size. For streaming data, the mapping happens at the top of each panel:

const buildMarketTrade = ( trade: RestAggTrade | StreamAggTrade, ): MarketTrade => { return { id: trade.a.toString(), price: Number(trade.p), quantity: Number(trade.q), time: trade.T, side: trade.m ? "sell" : "buy", }; };

After this function, nothing downstream knows that m means "buyer is the maker" or that it implies the aggressor was a seller. The presentational component receives side: "sell". If the kit is pointed at a different exchange, the mappers and the stream file change and the nine panels do not. That boundary is why the demo's components can be tested with plain props and no socket at all.

The same function accepts both the REST and the stream variant of an aggregate trade, which matters for the next point.

Snapshot plus stream

A stream only tells you what happens from now on. A trades list that starts empty and fills one print at a time looks broken on a quiet market. So the handler pattern for anything list-shaped is a REST snapshot for history, then the stream for updates.

The market trades panel fetches the 20 most recent aggregate trades from /api/v3/aggTrades, then merges stream messages on top, de-duplicating by aggregate trade ID because the snapshot and the stream can overlap. The source has a comment admitting a small race: trades that arrive on the stream while the snapshot is still loading are dropped. For a display-only tape that is acceptable. For an order book built from diff updates it would not be, and you would buffer stream events and reconcile them against the snapshot's update ID.

This is the main reason a browser feed handler for a trading UI can be so much simpler than a server one. The demo subscribes to partial book depth (depth10@100ms), where every message is a full top-ten snapshot. There are no deltas to apply and no sequence to verify. A missed message heals itself 100 milliseconds later. If you need the full book, you take on sequencing, and the approach is in the real-time order book deep dive.

Distribution: conflate before you render

The last job is deciding how often consumers hear about new data. Delivering every message to React is rarely right.

There are three places conflation happens in the demo, and they are worth separating:

  1. At the exchange. The @100ms suffix on the depth stream asks Binance to conflate for us. Ticker streams arrive about once a second. Choosing the slowest stream that satisfies the UI is the cheapest optimisation there is.
  2. By count. The trades panel collects messages in a ref and releases them in batches of five.
  3. By time. The open orders table passes its ticker cache through a useThrottledValue hook with a 1,000ms delay before computing rows.

The details and trade-offs of each are in throttling and batching market data, and how the budget is spent end to end is in latency budgets for trading UIs.

Where the demo's handler stops

A few limits, stated plainly, because a feed handler is exactly the kind of code where assumed behaviour causes incidents.

Connections are per hook, not per app. useBinanceStream calls useWebSocket(streamUrl) from react-use-websocket with default options. Each call owns a socket, so the multiplexing happens per panel: the watchlist's streams share one connection and the order book has another. The library's share: true option collapses hooks with the same URL onto one socket, and for a production build with many panels that is the setting to turn on. Binance limits streams per connection and connections per IP, so check both numbers against your panel count.

Reconnection is not configured. react-use-websocket only reconnects when given a shouldReconnect callback, and the demo does not pass one. Binance also closes every connection after 24 hours. A production handler needs shouldReconnect, a backoff, and one more thing that is easy to miss: on reconnect the server has forgotten your subscriptions, so the subs ref in useMessenger must be cleared when the socket closes or the diff will conclude there is nothing to send. What the user should see during all this is covered in connection status and loading states.

No heartbeat monitoring. A socket can be open and silent. A staleness timer per stream, raising a flag when a normally chatty stream goes quiet, catches the half-dead connection that readyState cannot.

It is websocket only. That is the right transport for Binance. If you control the server side, the comparison in SSE versus WebSockets for market data is worth reading before you commit.

Closing guidance

A feed handler in the browser is a small amount of code with a large effect on everything above it. Give it one home. Have it own the connection, diff subscriptions instead of reconnecting, tag every message with its source, refuse to deliver messages nobody asked for, and translate exchange vocabulary into your own before a component sees it.

Then decide deliberately how much of the production checklist you need: sharing, reconnection with resubscription, and heartbeats. A demo against a public feed can leave them out and say so. A platform that people trade on cannot.

Kickstart Your Trading Application

Hedge UI is a React starter kit with production-ready trading components, real-time data handling, and customisable layouts — so you can ship faster.

Get Hedge UI