> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coinpaprika.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Your First Crypto Stream in 5 Minutes

> A step-by-step guide to connecting to the CoinPaprika Streaming API and receiving live ticker data in less than 5 minutes.

# 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

* **A CoinPaprika API Key**: If you don't have one, get it from the [CoinPaprika API page](https://coinpaprika.com/api/panel/).
* **Node.js**: If you don't have it installed, download it from the [official Node.js website](https://nodejs.org/).

## 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.

<Steps>
  ### Create a Project Folder

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

  ```bash theme={"dark"}
  mkdir coinpaprika-5min-stream
  cd coinpaprika-5min-stream
  ```

  ### Initialize a Node.js Project

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

  ```bash theme={"dark"}
  npm init -y
  ```

  ### Install the WebSocket Library

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

  ```bash theme={"dark"}
  npm install ws
  ```

  ### Enable ES6 Modules (Important!)

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

  ```json theme={"dark"}
  {
    "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": ""
  }
  ```
</Steps>

## 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.

```javascript theme={"dark"}
// 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:

```bash theme={"dark"}
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!

### FAQs

<AccordionGroup>
  <Accordion title="What is the quickest way to test the crypto streaming API?">
    Use the Node.js snippet in this guide. Replace `YOUR_API_KEY` and run `node index.js`.
  </Accordion>

  <Accordion title="Where do I find coin IDs for subscriptions?">
    Use the REST API `GET /coins` or the [Coverage Checker](/tools/coverage) to look up canonical IDs (e.g., `btc-bitcoin`).
  </Accordion>

  <Accordion title="How do I switch quote currencies?">
    Change the `quotes` array in the subscribe payload (e.g., \`\['USD', 'BTC']).
  </Accordion>

  <Accordion title="How should I handle reconnections?">
    Implement a heartbeat and reconnect with exponential backoff. See the sample code’s heartbeat logic.
  </Accordion>

  <Accordion title="Is streaming data included in paid plans?">
    WebSockets are available on Enterprise; contact us if you need real-time streaming in production.
  </Accordion>
</AccordionGroup>
