Real-time Price Updates
On this page

Real-time Price Updates

Listen for real-time BTC/USDT price updates using WebSockets and update the dashboard card instantly.

Result

A real-time dashboard card that updates automatically as new price data arrives via WebSockets.

Bitcoin Price (BTC/USDT)

Used Technologies

  • HTML/CSS/JS: For the UI and logic.
  • WebSocket API: For real-time, bidirectional communication.
  • Bitcoin API: Specifically the getCurrentPrice WebSocket endpoint.

Implementation Steps

1. The HTML Structure

Create a card structure with a status dot and placeholders for the price.

html
<div class="price-card">
        <div class="price-card__header">
            <span class="price-card__label">Bitcoin Price (BTC/USDT)</span>
            <div id="status-dot" class="price-card__dot"></div>
        </div>
        <div class="price-card__body">
            <div id="loading-skeleton" class="price-card__loading">
                <div class="skeleton"></div>
            </div>
            <div id="error-message" class="price-card__error"></div>
            <div id="price-display" class="price-card__value" style="display: none;">
                <span class="price-card__currency">$</span>
                <span id="price-number" class="price-card__number">0.00</span>
            </div>
        </div>
        <div class="price-card__footer">
            <span id="connection-url" class="price-card__source">Live via WebSockets</span>
            <div class="price-card__badge">LIVE</div>
        </div>
    </div>

2. Styling for Connectivity

Add CSS styles to handle different connection states (online, offline, loading).

css
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f8fafc;
}

.price-card {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 1.5rem;
    width: 100%;
    max-width: 320px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.price-card__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.price-card__label {
    font-size: 0.75rem;
    font-weight: 600;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.price-card__dot {
    width: 8px;
    height: 8px;
    background: #10b981;
    border-radius: 50%;
    box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.1);
    transition: background-color 0.3s;
}

.price-card__dot.is-loading {
    background: #f59e0b;
    animation: pulse 2s infinite;
}

.price-card__dot.is-offline {
    background: #ef4444;
}

@keyframes pulse {
    0% { opacity: 1; }
    50% { opacity: 0.4; }
    100% { opacity: 1; }
}

.price-card__body {
    margin-bottom: 1rem;
}

.price-card__value {
    display: flex;
    align-items: baseline;
    color: #0f172a;
}

.price-card__currency {
    font-size: 1.5rem;
    font-weight: 500;
    margin-right: 0.25rem;
    color: #94a3b8;
}

.price-card__number {
    font-size: 2.5rem;
    font-weight: 800;
    letter-spacing: -0.02em;
}

.price-card__footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 1rem;
    border-top: 1px solid #f1f5f9;
}

.price-card__source {
    font-size: 0.75rem;
    color: #94a3b8;
}

.price-card__badge {
    background: #f1f5f9;
    color: #475569;
    font-size: 0.625rem;
    font-weight: 700;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    letter-spacing: 0.05em;
}

.skeleton {
    height: 3rem;
    background: #f1f5f9;
    border-radius: 8px;
    animation: skeleton-pulse 1.5s infinite;
}

@keyframes skeleton-pulse {
    0% { background-color: #f1f5f9; }
    50% { background-color: #e2e8f0; }
    100% { background-color: #f1f5f9; }
}

.price-card__error {
    color: #ef4444;
    font-size: 0.875rem;
    display: none;
}

3. WebSocket Logic

Implement the connection, message handling, and automatic reconnection logic.

javascript
const WS_URL = import.meta.env.VITE_WS_API_BROWSER_URL || 'wss://api.bitcoin-api.net/api';
const API_KEY = import.meta.env.VITE_BITCOIN_API_KEY;

console.log('Connecting to WebSocket:', WS_URL);

const priceNumber = document.getElementById('price-number');
const priceDisplay = document.getElementById('price-display');
const loadingSkeleton = document.getElementById('loading-skeleton');
const errorMessage = document.getElementById('error-message');
const statusDot = document.getElementById('status-dot');
const connectionUrlDisplay = document.getElementById('connection-url');

let socket;
let reconnectTimer;

function connect() {
    const url = new URL(`${WS_URL}/v1/prices/current`);
    url.searchParams.set('symbol', 'btcusdt');
    if (API_KEY) {
        url.searchParams.set('apiKey', API_KEY);
    }
    const fullUrl = url.toString();
    console.log('Opening connection to:', fullUrl);
    if (connectionUrlDisplay) connectionUrlDisplay.textContent = `Live: ${WS_URL.replace(/^wss?:\/\//, '')}`;

    // Reset UI state
    loadingSkeleton.style.display = 'block';
    priceDisplay.style.display = 'none';
    errorMessage.style.display = 'none';
    statusDot.classList.add('is-loading');
    statusDot.classList.remove('is-offline');

    socket = new WebSocket(fullUrl);

    socket.onopen = () => {
        console.log('Connected to Bitcoin API WebSocket');
        statusDot.classList.remove('is-loading');
        statusDot.classList.remove('is-offline');
        clearTimeout(reconnectTimer);
    };

    socket.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data);

            if (data.code || data.message) {
                errorMessage.textContent = data.message || data.code;
                errorMessage.style.display = 'block';
                loadingSkeleton.style.display = 'none';
                priceDisplay.style.display = 'none';
                return;
            }

            // Update UI with new price
            priceNumber.textContent = parseFloat(data.price).toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });

            loadingSkeleton.style.display = 'none';
            priceDisplay.style.display = 'flex';
            errorMessage.style.display = 'none';
        } catch (err) {
            console.error('Error parsing WebSocket message:', err);
        }
    };

    socket.onclose = (event) => {
        console.log('WebSocket connection closed:', event.code, event.reason);
        statusDot.classList.add('is-offline');
        statusDot.classList.remove('is-loading');

        // Show error message if we don't have a price yet OR if it was closed with a reason
        if (priceDisplay.style.display === 'none' || event.reason) {
            errorMessage.textContent = event.reason || 'Connection lost. Retrying...';
            loadingSkeleton.style.display = 'none';
            errorMessage.style.display = 'block';
            priceDisplay.style.display = 'none';
        }

        // Automatic reconnection
        reconnectTimer = setTimeout(connect, 5000);
    };

    socket.onerror = (err) => {
        console.error('WebSocket error:', err);
        socket.close();
    };
}

// Start connection
connect();

Resources

Used Endpoints