Blog
Public dashboardsNode.js

A Local Crypto Price Dashboard with Node.js

Build a local public-data dashboard with one upstream WebSocket, bounded browser connections, server-sent updates, visible data age, and reconnect invalidation.

Siebly.io2 min readMarkdown

Run One Upstream Consumer

A price display can keep showing its last value after the upstream feed disconnects. If the browser receives only a price string, it cannot distinguish a recent observation from a cached value left behind by an outage.

This small dashboard sends both the price and its local age. One Node.js process consumes a public Bybit ticker and serves the browser on loopback. It does not need account credentials.

Save ticker-state.mjs from the public Bybit feed example beside the files below. That module applies ticker snapshots and partial updates.

Install bybit-api, save this as dashboard.mjs, and run node dashboard.mjs:

dashboard.mjs

JavaScript
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { performance } from 'node:perf_hooks';
import { WebsocketClient } from 'bybit-api';
import { applyTicker } from './ticker-state.mjs';

const html = await readFile(new URL('./dashboard.html', import.meta.url));
const browsers = new Set();
const feed = new WebsocketClient();
let ticker;
let stopping = false;
feed.on('update', (message) => {
  if (message.topic === 'tickers.BTCUSDT' && message.data?.symbol === 'BTCUSDT') {
    ticker = applyTicker(ticker, message, performance.now());
  }
});
feed.on('reconnect', () => {
  ticker = undefined;
});
feed.on('close', () => {
  ticker = undefined;
});
feed.on('exception', () => {
  ticker = undefined;
  console.error('Ticker connection exception');
});
const server = createServer((request, response) => {
  if (request.url === '/') {
    response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    response.end(html);
  } else if (request.url === '/events' && browsers.size < 20) {
    response.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
    });
    response.flushHeaders();
    browsers.add(response);
    response.on('close', () => browsers.delete(response));
  } else {
    response.writeHead(404);
    response.end();
  }
});
const timer = setInterval(() => {
  const payload = ticker
    ? {
        price: ticker.lastPrice,
        ageMs: Math.round(performance.now() - ticker.receivedAt),
      }
    : { price: null, ageMs: null };
  for (const browser of browsers) {
    if (!browser.write(`data: ${JSON.stringify(payload)}\n\n`)) browser.end();
  }
}, 250);
function stop() {
  if (stopping) return;
  stopping = true;
  clearInterval(timer);
  for (const browser of browsers) browser.end();
  feed.closeAll();
  server.close();
}
server.on('error', (error) => {
  console.error(error.message);
  process.exitCode = 1;
  stop();
});
process.once('SIGINT', stop);
server.listen(8087, '127.0.0.1');
try {
  await Promise.all(feed.subscribeV5('tickers.BTCUSDT', 'linear'));
} catch (error) {
  console.error(error.message);
  process.exitCode = 1;
  stop();
}

The connection limit and write check prevent an unbounded per-browser backlog. A slow browser is disconnected and can reconnect; it is not a trade recorder that requires every intermediate update.

Show Age in the Browser

Save this as dashboard.html, then open 127.0.0.1:8087 in a browser:

dashboard.html

html
<!doctype html>
<html lang="en">
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>BTCUSDT public ticker</title>
  <h1>BTCUSDT linear ticker</h1>
  <p id="price">Waiting for a snapshot</p>
  <p id="status" role="status">Connecting</p>
  <script>
    const price = document.querySelector('#price');
    const status = document.querySelector('#status');
    const stream = new EventSource('/events');
    let latest;
    let frame;
    stream.onmessage = ({ data }) => {
      latest = JSON.parse(data);
      if (frame) return;
      frame = requestAnimationFrame(() => {
        frame = undefined;
        price.textContent = latest.price ?? 'Waiting for a snapshot';
        status.textContent =
          latest.ageMs === null
            ? 'Upstream state unavailable'
            : `${latest.ageMs > 5000 ? 'Old' : 'Recent'} observation: ${latest.ageMs} ms`;
      });
    };
    stream.onerror = () => {
      cancelAnimationFrame(frame);
      frame = undefined;
      price.textContent = 'Unavailable';
      status.textContent = 'Browser connection interrupted';
    };
  </script>
</html>

The five-second label is a demonstration policy for arrival age, not proof of a fresh trade. The state function preserves an unchanged last price in a valid ticker delta. A reconnect clears the retained state until a new snapshot arrives.

Check Both Connections

Interrupt the upstream feed and confirm the browser shows unavailable state. Stop the server and confirm the browser clears its price. A browser connection and an exchange connection are separate failure boundaries.

The UI batching article measures rendering work at higher message rates. This dashboard receives four browser updates per second while its upstream handler processes ticker events independently. Persistence, public deployment, authentication, and account data are outside this loopback demonstration.

Related articles

Continue from here

Related Siebly resources

All articles

Subscribe on Substack

Complete the Substack form below to join our newsletter. Substack handles all subscriber data directly.