DEV Community

kalos
kalos

Posted on

How to Calculate Crypto 24h Price Change Using API & Python


Hello developers! In this guide, I'll walk you through how to pull real-time cryptocurrency market data and calculate the 24-hour price change with Python and WebSocket API. This tutorial is suitable for beginners and developers building market trackers, quantitative analysis tools, or personal trading assistants.


1. Background & Why We Choose WebSocket

When tracking crypto markets, the 24-hour price change is one of the most important indicators. Manually refreshing exchange pages is inefficient, especially for multi-asset monitoring.

Traditional REST polling works but brings extra network requests and noticeable latency. Since crypto prices fluctuate rapidly, WebSocket persistent connection is the better choice: it delivers low-latency real-time data, reduces request overhead, and supports monitoring multiple trading pairs at the same time.

We will use AllTick, a multi-asset market API covering crypto, forex, stocks and commodities.


2. Correct Formula for 24h Price Change

A common misconception is calculating change using the previous day's closing price. Most mainstream market APIs use the 24h opening price as the benchmark instead.

Calculation Formula

[
\text{24h Price Change (\%)} = \frac{\text{Latest Price} - \text{24h Opening Price}}{\text{24h Opening Price}} \times 100\%
]

Core Data Fields

Field Description Usage
symbol Crypto trading pair (e.g. BTCUSDT, ETHUSDT) Identify different assets
price Latest transaction price Main value for calculation
open_24h Opening price in the last 24 hours Base value for calculation

3. API Introduction & Updated Endpoint

The original AllTick WebSocket domain is no longer available. Please use the latest valid endpoint below for crypto market data:

wss://quote.tradeswitcher.com/quote-b-ws-api?token=YOUR_TOKEN
Enter fullscreen mode Exit fullscreen mode

Connection rules:

  • After connecting, send a subscription frame with fixed cmd_id=22004
  • Use the code field to specify the trading pairs you want to monitor

4. Full Python Code Implementation

This production-ready code includes heartbeat detection, auto-reconnection, exception handling, data filtering and throttling. Just replace the token with your own credential to run directly.

# AllTick official documentation reference
# Latest WebSocket endpoint: wss://quote.tradeswitcher.com/quote-b-ws-api
import websocket
import json
import time
import random

# Replace with your personal valid Token
ACCESS_TOKEN = "Your_Access_Token"
# Official WebSocket URL for cryptocurrency market
WS_URL = f"wss://quote.tradeswitcher.com/quote-b-ws-api?token={ACCESS_TOKEN}"
# Local cache for data throttling, avoid redundant calculation
tick_cache = {}

def on_open(ws):
    """Triggered when WebSocket connection is established"""
    print("WebSocket connected, start subscribing crypto tick data")
    # Official subscription frame format
    sub_frame = {
        "cmd_id": 22004,
        "seq_id": random.randint(1000, 9999),
        "trace": "crypto_tick_subscribe",
        "data": {
            "symbol_list": [
                {"code": "BTCUSDT"},
                {"code": "ETHUSDT"}
            ]
        }
    }
    ws.send(json.dumps(sub_frame))

def on_message(ws, message):
    """Receive market data and calculate 24h price change"""
    global tick_cache
    try:
        data = json.loads(message)
        symbol = data.get("symbol")
        price = data.get("price")
        open_24h = data.get("open_24h")

        # Filter empty, null and zero values
        if not all([symbol, price, open_24h]) or float(open_24h) == 0:
            return

        current_ts = time.time()
        # Throttle: update result only once per second
        if symbol in tick_cache and current_ts - tick_cache[symbol]["ts"] < 1:
            return

        # Refresh local cache
        tick_cache[symbol] = {
            "price": price,
            "open_24h": open_24h,
            "ts": current_ts
        }

        # Compute 24h price change
        price_float = float(price)
        open_float = float(open_24h)
        change_rate = (price_float - open_float) / open_float * 100
        print(f"Pair: {symbol} | Latest Price: {price_float:.4f} | 24h Change: {change_rate:.2f}%")

    except Exception as e:
        print(f"Data parse error: {str(e)}")

def on_error(ws, error):
    """Catch runtime exceptions"""
    print(f"WebSocket error: {str(error)}")

def on_close(ws, close_status_code, close_msg):
    """Triggered when connection is closed"""
    print(f"Connection closed | Code: {close_status_code} | Message: {close_msg}")

if __name__ == "__main__":
    # Initialize WebSocket client
    ws_app = websocket.WebSocketApp(
        WS_URL,
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )

    # Heartbeat: 10s ping interval, 30s timeout
    # Auto reconnect after 3 seconds when disconnected
    while True:
        ws_app.run_forever(ping_interval=10, ping_timeout=30)
        print("Connection lost, reconnecting in 3 seconds...")
        time.sleep(3)
Enter fullscreen mode Exit fullscreen mode

5. Common Issues & Fixes

Here are the most frequent bugs I encountered during development, with practical solutions:

  1. Problem: API returns empty, None or 0 for price / open_24h

    • Check: Add non-null and division-by-zero validation
    • Fix: Skip abnormal data and only keep error logs
  2. Problem: Frequent disconnection due to network fluctuation or API limits

    • Check: Monitor on_close and on_error callbacks
    • Fix: Enable heartbeat, implement 3-second delayed auto-reconnect
  3. Problem: Floating-point calculation deviation for low-price crypto assets

    • Check: Verify results with multiple groups of continuous data
    • Fix: Unify float type, limit output to 2 decimal places
  4. Problem: High-frequency data causes redundant computation & resource waste

    • Check: Count data update frequency per second
    • Fix: Add timestamp-based throttling logic

6. Feature Limitations

  • ✅ Supported: Real-time data acquisition & 24h price calculation for single/multiple crypto pairs
  • ❌ Not supported: Place trading orders, fetch full historical tick data
  • Note: Service stability depends on your local network and the third-party API status

7. Wrap-up

Compared with REST polling, WebSocket is definitely a better choice for real-time crypto market scenarios. This project combines WebSocket programming, JSON parsing and basic financial data logic, which is a great hands-on practice for Python developers.

You can extend this code to build a visual dashboard, alert system or simple quantitative tools according to your own needs.

Top comments (0)