Logo

dev-resources.site

for different kinds of informations.

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

Published at
1/1/2025
Categories
webdev
react
typescript
websocket
Author
abhivyaktii
Categories
4 categories in total
webdev
open
react
open
typescript
open
websocket
open
Author
11 person written this
abhivyaktii
open
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!


websocket Article's
30 articles in total
Favicon
Unchain Proxy Svr By Golang
Favicon
Getting Started with Web Sockets in Node.js
Favicon
Implementing a Scalable Forex WebSocket Using a Python Proxy
Favicon
Building SyncBridge: When "Copy Here, Paste There" Gets an Upgrade 🚀
Favicon
Socket.IO vs. WebSocket: Pros and Cons for Beginners
Favicon
Building Real-Time Dashboards with WebSockets: A Crypto Live Trades Example
Favicon
WebSocket Load Testing: A Comprehensive Guide to Seamless API Performance
Favicon
Real-Time Web Application demo with WebSocket - Backend
Favicon
Real-Time Web Application demo with WebSocket - Frontend
Favicon
Real-Time Web Application demo with WebSocket - Overview
Favicon
WebSocket Integration in React for Real-Time Communication
Favicon
How to disconnect WebSocket from Chrome Developer tool
Favicon
Guarantee message deliveries for real-time WebSocket APIs with Serverless on AWS
Favicon
WebSockets: The Secret to Seamless Real-Time Communication
Favicon
WebSocket broadcasting with JavaScript and Bun
Favicon
WebSocket Client with JavaScript
Favicon
A Strategy Template Allows You to Use WebSocket Market Seamlessly
Favicon
WebSocket with JavaScript and Bun
Favicon
Top 10 WebSocket Testing Tools for Real-Time Apps (Updated 2024)
Favicon
AWS AppSync Events — Serverless WebSockets Done Right or Just Different?
Favicon
How to Get Free Market Data: Mastering The Market Data Feed Via Free API Key
Favicon
SimplySocket: A Lightweight WebSocket Wrapper for Go
Favicon
Building Simple Real-Time System Monitor using Go, HTMX, and Web Socket
Favicon
Synchronizing Collaborative Text Editing with Yjs and WebSockets
Favicon
Scaling Kafka with WebSockets
Favicon
Building Tetris using WebSocket and Svelte Stores
Favicon
Mastering WebSocket Load Balancing: Unlocking Resilience with Sticky IPs and Session Routing
Favicon
What is WebRTC and How Does It Work?
Favicon
6 Ways Handle WebSocket Load Balancing Without Losing the Connection Thread
Favicon
6 Ways Handle WebSocket Load Balancing Without Losing the Connection Thread

Featured ones: