Your First Crypto Stream in 5 Minutes

Want to start streaming real-time crypto data right now? This guide will get you connected to the CoinPaprika Streaming API and receiving live price updates in less than 5 minutes. We’ll walk you through a simple copy-paste Node.js script. No complex setup, just instant data.

What You’ll Need

Step 1: Set Up Your Project (1 Minute)

First, let’s create a new project directory and install the necessary ws library for handling WebSockets in Node.js.
1

Create a Project Folder
2

Open your terminal and run these commands to create a project folder and navigate into it:
3

mkdir coinpaprika-5min-stream
cd coinpaprika-5min-stream
4

Initialize a Node.js Project
5

Next, run this command to create a package.json file for your project.
6

npm init -y
7

Install the WebSocket Library
8

Finally, install the ws library to handle the WebSocket connection.
9

npm install ws
10

Enable ES6 Modules (Important!)
11

To avoid warnings and ensure smooth operation, edit your package.json file and add "type": "module":
12

{
  "name": "coinpaprika-5min-stream",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "ws": "^8.14.0"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

Step 2: Create and Run the Client (4 Minutes)

Now, create a new file named index.js in your project folder. This file will contain all the code for our streaming client. Open index.js and paste the following code into it. Be sure to replace "YOUR_API_KEY" with your actual CoinPaprika API key.
// Import the WebSocket library
import WebSocket from "ws";

// --- Configuration ---
// Replace with your actual CoinPaprika API key
const API_KEY = "YOUR_API_KEY"; 
const WS_URL = "wss://streaming.coinpaprika.com/ticks";

console.log("--- CoinPaprika 5-Minute Ticker ---");
console.log("Starting connection to streaming API...");

// --- WebSocket Connection ---
try {
  // Initialize the WebSocket connection with your API key in the headers
  const ws = new WebSocket(WS_URL, {
    headers: {
      Authorization: API_KEY,
    },
  });

  let pingTimeout;

  // This function is a safeguard that terminates the connection if the server stops sending pings.
  function heartbeat() {
    clearTimeout(pingTimeout);
    console.log("Heartbeat timeout. Terminating connection.");
    ws.terminate();
  }

  // --- Event Handlers ---

  // 1. When the connection opens, subscribe to tickers.
  ws.on("open", () => {
    console.log("✅ Connection established. Subscribing to tickers...");
    pingTimeout = setTimeout(heartbeat, 130 * 1000); // Expect a ping within 130 seconds

    const subscribePayload = {
      event: "subscribe",
      ids: ["btc-bitcoin", "eth-ethereum"],
      quotes: ["USD"],
    };

    ws.send(JSON.stringify(subscribePayload));
    console.log("Subscribed to Bitcoin and Ethereum tickers");
    console.log("Waiting for live price updates...\n");
  });

  // 2. When the server sends a ping, reset the heartbeat timeout.
  ws.on("ping", () => {
    console.log("Received server ping. Connection is healthy.");
    clearTimeout(pingTimeout);
    pingTimeout = setTimeout(heartbeat, 130 * 1000);
  });

  // 3. When a message is received, log it to the console.
  ws.on("message", (data) => {
    try {
      const message = JSON.parse(data.toString());
      
      // Format the output to be more readable
      const price = message.quotes?.USD?.p;
      const volume = message.quotes?.USD?.v24h;
      const marketCap = message.quotes?.USD?.m;
      
      console.log(`📊 ${message.sym} (${message.id}):`);
      console.log(`   💲 Price: $${price?.toLocaleString() || 'N/A'}`);
      console.log(`   📈 24h Volume: $${volume?.toLocaleString() || 'N/A'}`);
      console.log(`   🏦 Market Cap: $${marketCap?.toLocaleString() || 'N/A'}`);
      console.log(`   🕐 Timestamp: ${new Date(message.ts * 1000).toLocaleString()}\n`);
      
    } catch (error) {
      console.error("Failed to parse message:", error);
    }
  });

  // 4. When the connection closes, clean up the timeout.
  ws.on("close", (code, reason) => {
    console.log(`🔌 Connection closed with code ${code}: ${reason || 'No reason provided'}`);
    clearTimeout(pingTimeout);
  });

  // 5. Handle any errors that occur.
  ws.on("error", (err) => {
    console.error("A WebSocket error occurred:", err.message);
  });

  // 6. Graceful shutdown on Ctrl+C
  process.on('SIGINT', () => {
    console.log('\nGracefully shutting down...');
    ws.close();
    process.exit(0);
  });

} catch (e) {
  console.error("Failed to create WebSocket connection:", e.message);
  process.exit(1);
}

Run the Application

You are now ready to go! Save the index.js file, and in your terminal, run the following command:
node index.js
You should immediately see output as the connection is made and data starts streaming in:
--- CoinPaprika 5-Minute Ticker ---
🚀 Starting connection to streaming API...
✅ Connection established. Subscribing to tickers...
📡 Subscribed to Bitcoin and Ethereum tickers
💰 Waiting for live price updates...

📊 BTC (btc-bitcoin):
   💲 Price: $118,625
   📈 24h Volume: $42,480,897,345
   🏦 Market Cap: $2,359,846,639,027
   🕐 Timestamp: 7/16/2025, 4:09:40 PM

📊 ETH (eth-ethereum):
   💲 Price: $3,191
   📈 24h Volume: $28,987,190,950
   🏦 Market Cap: $384,299,955,255
   🕐 Timestamp: 7/16/2025, 4:09:40 PM
To stop the stream, simply press Ctrl+C in your terminal.

What Just Happened?

Congratulations! 🎉 You’ve successfully:
  1. Connected to the CoinPaprika Streaming API
  2. Authenticated using your API key
  3. Subscribed to Bitcoin and Ethereum price feeds
  4. Received real-time market data
The stream will continue indefinitely, updating you whenever there are price changes on these cryptocurrencies.

Understanding the Code

Let’s break down the key parts:
  • WebSocket Connection: Creates a persistent connection to receive real-time data
  • Heartbeat: Monitors connection health and reconnects if needed
  • Event Handlers: Respond to different connection states (open, message, close, error)
  • Data Parsing: Safely parses incoming JSON messages with error handling
  • Graceful Shutdown: Properly closes the connection when you stop the program

Next Steps

This tutorial provides a solid foundation. Here are a few ideas for expanding your application:
  • Store the Data: Save the incoming ticker data to a database for historical analysis.
  • Build a UI: Create a web-based dashboard to visualize the price changes in real time.
  • Add More Currencies: Modify the subscribePayload to include other cryptocurrencies you’re interested in.
  • Implement Reconnection Logic: Enhance the script to automatically reconnect if the connection is lost.
  • Add Alerts: Set up price alerts when certain thresholds are met.
  • Calculate Changes: Track price changes and display percentage movements.

Troubleshooting

Common Issues:
  • Module Error: Make sure you added "type": "module" to your package.json
  • Connection Failed: Check your API key and internet connection
  • No Data: Verify the currency IDs are correct (e.g., "btc-bitcoin", "eth-ethereum")
Happy coding!