DEV Community

Abhinav
Abhinav

Posted on

4

Building Real-Time Dashboards with WebSockets: A Crypto Live Trades Example

Real-time updates are a fundamental feature of modern applications. Whether it’s live stock prices, cryptocurrency trades, or collaborative tools, the need for instantaneous data has reshaped how we build software. At the heart of this revolution lies WebSockets, a protocol designed for real-time, bidirectional communication.

In this blog, we’ll explore WebSockets, their advantages, and how they can power a Crypto Live Trades Dashboard. By the end, you’ll understand how WebSockets make real-time applications efficient and scalable.

Live link: https://crypto-tracker-jet-one.vercel.app/
crypto-tracker-ws


What Are WebSockets?

WebSockets is a communication protocol that allows persistent, full-duplex communication between a client (e.g., a browser) and a server. Unlike HTTP, which requires a request-response cycle, WebSockets maintain an open connection, enabling both client and server to send and receive data simultaneously.

Why Use WebSockets?

  • Low Latency: Ideal for time-sensitive applications like live dashboards or games.
  • Efficient: Eliminates the need to repeatedly establish connections, reducing overhead.
  • Bidirectional Communication: Both server and client can initiate messages.

Common Use Cases

  • Live Feeds: Cryptocurrency prices, stock market updates, sports scores.
  • Messaging Apps: Instant chat and notification systems.
  • Gaming: Multiplayer gaming requiring real-time synchronization.
  • IoT: Communication between devices and a central hub.

Building a Crypto Live Trades Dashboard

Let’s dive into an example: a Crypto Live Trades Dashboard powered by the Binance WebSocket API. This application uses React, TypeScript, and TailwindCSS for the frontend, providing a clean and responsive user experience.

Step 1: Setting Up WebSocket Communication

The Binance API offers WebSocket streams for live cryptocurrency trade data. Here’s a custom React hook for managing WebSocket connections:

import { useEffect, useState } from 'react';

interface Trade {
  price: string;
  quantity: string;
  symbol: string;
  time: number;
}

export const useCryptoTrades = (symbol: string) => {
  const [trades, setTrades] = useState<Trade[]>([]);

  useEffect(() => {
    const ws = new WebSocket(`wss://stream.binance.com:9443/ws/${symbol.toLowerCase()}@trade`);

    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      const trade: Trade = {
        price: data.p,
        quantity: data.q,
        symbol: data.s,
        time: data.T,
      };
      setTrades((prevTrades) => [...prevTrades.slice(-9), trade]); // Keep the last 10 trades
    };

    return () => ws.close(); // Cleanup on component unmount
  }, [symbol]);

  return trades;
};
Enter fullscreen mode Exit fullscreen mode

Step 2: Creating the Dashboard

Here’s how you can use the useCryptoTrades hook in a React component to render a grid of live trades:

import React from 'react';
import { useCryptoTrades } from './hooks/useCryptoTrades';

const CryptoTradeCard = ({ symbol }: { symbol: string }) => {
  const trades = useCryptoTrades(symbol);

  return (
    <div className="trade-card">
      <h3>{symbol}</h3>
      <ul>
        {trades.map((trade, index) => (
          <li key={index}>
            {new Date(trade.time).toLocaleTimeString()} - Price: {trade.price}, Quantity: {trade.quantity}
          </li>
        ))}
      </ul>
    </div>
  );
};

const App = () => {
  const symbols = ['BTCUSDT', 'ETHUSDT', 'ADAUSDT', 'XRPUSDT', 'SOLUSDT'];

  return (
    <div className="dashboard">
      <h1>Crypto Live Trades</h1>
      <div className="grid">
        {symbols.map((symbol) => (
          <CryptoTradeCard key={symbol} symbol={symbol} />
        ))}
      </div>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 3: Styling with TailwindCSS

Here’s a basic setup for styling the dashboard:

/* Tailwind example */
.trade-card {
  @apply bg-white shadow-md rounded-lg p-4 text-center;
}

.grid {
  @apply grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4;
}

.dashboard {
  @apply max-w-7xl mx-auto p-6;
}
Enter fullscreen mode Exit fullscreen mode

Debugging WebSockets

Web browsers make it easy to debug WebSocket connections:

  1. Open Developer Tools (F12).
  2. Go to the Network tab and filter by WS.
  3. Observe the handshake, data frames, and any errors.

In our example, the WebSocket handshake with Binance is confirmed by the 101 Switching Protocols status, allowing seamless live trade data streaming.


Best Practices for WebSocket Applications

  1. Reconnect Logic: Handle connection drops with retries and exponential backoff.
  2. Heartbeat Messages: Send periodic ping/pong messages to keep the connection alive.
  3. Optimize Data Handling: Only send or store necessary data to reduce memory usage.
  4. Secure Connections: Always use wss:// for encrypted communication.

Conclusion

WebSockets are an essential tool for building real-time applications, offering low latency and bidirectional communication. Whether you’re working on a cryptocurrency dashboard or multiplayer games, WebSockets provide the foundation for dynamic and engaging user experiences.

Start experimenting with WebSockets today and bring real-time interactivity to your applications. The future is live, and now you have the tools to build it!


Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay