Build a Real-Time Forex Dashboard with an FX Rates WebSocket
Subscribe to live bid/ask in JavaScript, flash ticks on the board, reconnect with backoff, and fall back to 1-second polling.
Hourly FX widgets look fine in a screenshot and stale once London and New York are both open. Majors such as the EUR/USD live rate can print a new bid or ask many times per minute, and operators on a treasury screen, brokerage board, or checkout widget act on the number in front of them.
This tutorial builds a minimal browser dashboard: subscribe to an FX rates WebSocket, render bid and ask with movement flashes, reconnect with backoff, and fall back to one-second REST polling. Both transports share one tick shape so the renderer stays small.
Key takeaways
- Real-time data belongs on screens people act on; hourly feeds belong in books and invoices.
- Prefer a WebSocket for many pairs; keep 1-second REST polling as a first-class fallback.
- Flash bid and ask independently so the moved side of the market is obvious.
- Reconnect with exponential backoff, jitter, and a 30-second cap; do not stampede the API.
- Start with a few majors and check them against all live rates.
When a dashboard justifies real-time data
Hourly and daily reference feeds are the right source for invoicing and accounting close, which need a stable print. A live dashboard needs the opposite: a quote that is still valid a second later if someone acts on it. Streams or a one-second snapshot fit dealer boards, conversion widgets, spread alerts, and exposure walls. A marketing module that shows a daily rate does not.
| Job | Acceptable lag | Feed |
|---|---|---|
| Invoices, month-end translation | Hours | Hourly or daily fix |
| Informational website widget | Minutes | Infrequent REST |
| Internal FX board, conversion UI | ~1 second | Polled snapshot |
| Dealer or brokerage live board | Ticks | FX rates WebSocket |
If the product owner cannot name an action that happens while someone is looking at the board, an hourly feed is simpler to audit. If they can, real-time is the baseline.
Unify ticks from a stream or a 1s poll
Normalize every update to pair, bid, ask, and a timestamp so the renderer does not care whether a WebSocket or a 1,000 ms REST snapshot delivered it. A Live-Rates subscription can supply those fields; the browser handles transport, display, and recovery. Polling faster than once per second on a shared key rarely helps the UX and burns quota.
Subscribe only to pairs the board actually shows. A first dashboard usually starts with EUR/USD, GBP/USD live rate, and USD/JPY live rate. Requesting the full catalog and hiding most symbols still costs bandwidth and makes reconnect storms worse.
Subscribe to an FX rates WebSocket
On open, the client sends a subscribe payload with the API key and pair list. Messages are parsed, coerced to numbers, and passed to the same onTick handler the poller will use. Heartbeats and notices that lack bid or ask are ignored.
function connectFxStream(config, onTick, onStatus) {
const socket = new WebSocket(config.streamUrl);
socket.addEventListener("open", function () {
onStatus("live");
socket.send(JSON.stringify({
type: "subscribe",
pairs: config.pairs,
apiKey: config.apiKey
}));
});
socket.addEventListener("message", function (event) {
const msg = JSON.parse(event.data);
if (msg.bid == null || msg.ask == null) return;
onTick({
pair: msg.pair || msg.symbol,
bid: Number(msg.bid),
ask: Number(msg.ask),
ts: msg.ts || Date.now()
});
});
return socket;
}
Keep subscribe logic in one function so tests and the REST fallback can inject ticks without opening a socket. A status of live in a small header tells operators the stream is up. The exact subscribe frame is provider-specific; the tick shape above is what the rest of the page depends on.
Render bid and ask with movement flashes
A compact HTML table is enough. Each row carries a data-pair attribute; each quote cell carries data-side. Pair labels can link to the public rate pages so finance users can check the board against all live rates.
On each tick, write the new prices, then compare bid and ask to the previous tick separately. Flash only the side that changed. A 400 ms up or down class is long enough to notice and short enough not to stack. Force a reflow before re-adding the class so consecutive ticks retrigger the animation.
const last = new Map();
function flash(el, direction) {
el.classList.remove("up", "down");
void el.offsetWidth;
el.classList.add(direction);
window.setTimeout(function () {
el.classList.remove("up", "down");
}, 400);
}
function renderTick(tick) {
const row = document.querySelector("[data-pair='" + tick.pair + "']");
if (!row) return;
const bidEl = row.querySelector("[data-side=bid]");
const askEl = row.querySelector("[data-side=ask]");
const prev = last.get(tick.pair);
bidEl.textContent = tick.bid.toFixed(5);
askEl.textContent = tick.ask.toFixed(5);
if (prev) {
if (tick.bid !== prev.bid) flash(bidEl, tick.bid > prev.bid ? "up" : "down");
if (tick.ask !== prev.ask) flash(askEl, tick.ask > prev.ask ? "up" : "down");
}
last.set(tick.pair, tick);
}
JPY pairs are often quoted to three decimal places and majors to five. A small per-pair precision map avoids showing 150.12300 on USD/JPY. Spread is ask minus bid and does not need its own stream field.
Handle reconnects without hammering the API
Sockets drop when laptops sleep, proxies idle out, or mobile networks hand off. Treat close and error as normal. Exponential backoff from 500 ms, capped at 30 seconds, plus a little jitter, prevents a reconnect stampede. After five failed attempts, start one-second polling so the board stays current, then stop the poller once the socket is healthy.
Backoff, then a 1-second polling fallback
function createDashboard(config, onTick, onStatus) {
let socket = null, attempt = 0, pollTimer = null, polling = false;
function startPoll() {
if (pollTimer) return;
polling = true;
onStatus("poll");
pollTimer = window.setInterval(async function () {
const res = await fetch(config.restUrl, {
headers: { Authorization: "Bearer " + config.apiKey }
});
const body = await res.json();
const quotes = Array.isArray(body) ? body : body.rates || [];
quotes.forEach(onTick);
}, config.pollMs || 1000);
}
function stopPoll() {
window.clearInterval(pollTimer);
pollTimer = null;
polling = false;
}
function scheduleReconnect() {
const delay = Math.min(30000, 500 * Math.pow(2, attempt));
attempt += 1;
if (attempt >= 5) startPoll();
window.setTimeout(connect, delay + Math.random() * 250);
}
function connect() {
socket = connectFxStream(config, function (tick) {
attempt = 0;
if (polling) stopPoll();
onTick(tick);
}, onStatus);
socket.addEventListener("close", scheduleReconnect);
socket.addEventListener("error", function () { socket.close(); });
}
connect();
window.setTimeout(function () {
if (!socket || socket.readyState !== WebSocket.OPEN) startPoll();
}, 2000);
}
A two-second grace period before the first poll covers a slow handshake without opening both transports on every load. Stop the interval when the document is hidden if background polling is not required, and resume on visibility change so a parked tab does not consume quota overnight.
FAQ
When should a forex dashboard use real-time data instead of an hourly feed?
Use a stream or a one-second snapshot when someone will act on the quote while it is on screen: dealing, converting a payment, or watching exposure. Hourly and daily fixes are the better source for invoices, accounting, and any process that needs a stable official print.
What happens if the FX rates WebSocket is unavailable?
The same tick handler should accept REST snapshots on a 1,000 ms interval. After a handful of failed socket attempts the client starts polling, then stops the timer once the WebSocket is live again so the two transports do not double-update the board.
How should bid and ask movement flashes work?
Store the previous tick per pair and compare each side on its own. Apply a short-lived up or down class only to the cell that changed, retriggering the CSS animation via a reflow. Flashing the whole row hides whether the bid, the ask, or both moved.
How aggressive should reconnect logic be?
Back off exponentially from a few hundred milliseconds to a cap around 30 seconds, add jitter, and fall back to polling instead of retrying forever at full speed. A tight reconnect loop looks like an outage to the API and can trip rate limits for every other client sharing the key.
Ready to feed a live board from production-grade quotes? Review the Live-Rates plans page and wire the dashboard to a subscription that matches the pair list and update rate the UI actually needs.
Real-time forex rates for your app
Live bid/ask for the pairs you need, updated every second, with a simple JSON & XML API. Try it free for 7 days.