Skip to content

Node.js / JavaScript quickstart ​

Read a public BTC/USD price with @siebly/kraken-api. No API key or TypeScript compiler is needed. Prices are BTC/USD last traded prices.

Use Node.js 24 and npm. If you prefer to start from a finished project, view the complete Kraken Node.js example on GitHub.

See Runtime compatibility for the checks that have been run and their results. Successful imports and builds alone do not verify live exchange access.

Create the project ​

sh
mkdir kraken-node-quickstart
cd kraken-node-quickstart
npm init -y
npm install @siebly/kraken-api

npm init creates package.json; npm install adds the current SDK release. You do not need to edit the package file for these examples.

Read a price ​

For a new project, create price.mjs with import. If your project uses require, choose price.cjs instead. Create one file; both request the price directly.

js
import { SpotClient } from '@siebly/kraken-api';

const client = new SpotClient();
const response = await client.getTicker({ pair: 'XBTUSD' });
const ticker = Object.values(response.result)[0];
const price = ticker?.c[0];

if (!price) {
  throw new Error('No BTC/USD price was returned.');
}

console.log('BTC/USD REST price:', price);
js
const { SpotClient } = require('@siebly/kraken-api');

async function main() {
  const client = new SpotClient();
  const response = await client.getTicker({ pair: 'XBTUSD' });
  const ticker = Object.values(response.result)[0];
  const price = ticker?.c[0];

  if (!price) {
    throw new Error('No BTC/USD price was returned.');
  }

  console.log('BTC/USD REST price:', price);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run the file you created:

sh
node price.mjs
sh
node price.cjs

The result is a price string, for example:

text
BTC/USD REST price: 65000.5

Stream a price (optional) ​

For a new project, create stream.mjs with import. If your project uses require, choose stream.cjs instead. Create one stream file; it closes the client after the first price or a failure.

js
import { WebsocketClient } from '@siebly/kraken-api';
import process from 'node:process';

async function main() {
  const ws = new WebsocketClient();
  let timeout;
  let stopped = false;

  try {
    const firstPrice = new Promise((resolve, reject) => {
      timeout = setTimeout(() => {
        reject(new Error('No BTC/USD update within 30 seconds.'));
      }, 30_000);

      ws.on('message', (message) => {
        if (message.channel !== 'ticker') {
          console.log('WebSocket message:', message);
          return;
        }

        const price = message.data?.[0]?.last;

        if (price) {
          resolve(String(price));
        }
      });
      ws.on('exception', reject);

      const subscription = Promise.resolve(ws.subscribe({ topic: 'ticker', payload: { symbol: ['BTC/USD'] } }, 'spotPublicV2'));
      subscription.catch(reject).finally(() => {
        if (stopped) {
          ws.closeAll();
        }
      });
    });

    console.log('BTC/USD WebSocket price:', await firstPrice);
  } finally {
    stopped = true;
    clearTimeout(timeout);
    ws.closeAll();
    console.log('WebSocket closed.');
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
js
const { WebsocketClient } = require('@siebly/kraken-api');
const process = require('node:process');

async function main() {
  const ws = new WebsocketClient();
  let timeout;
  let stopped = false;

  try {
    const firstPrice = new Promise((resolve, reject) => {
      timeout = setTimeout(() => {
        reject(new Error('No BTC/USD update within 30 seconds.'));
      }, 30_000);

      ws.on('message', (message) => {
        if (message.channel !== 'ticker') {
          console.log('WebSocket message:', message);
          return;
        }

        const price = message.data?.[0]?.last;

        if (price) {
          resolve(String(price));
        }
      });
      ws.on('exception', reject);

      const subscription = Promise.resolve(ws.subscribe({ topic: 'ticker', payload: { symbol: ['BTC/USD'] } }, 'spotPublicV2'));
      subscription.catch(reject).finally(() => {
        if (stopped) {
          ws.closeAll();
        }
      });
    });

    console.log('BTC/USD WebSocket price:', await firstPrice);
  } finally {
    stopped = true;
    clearTimeout(timeout);
    ws.closeAll();
    console.log('WebSocket closed.');
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run the matching file:

sh
node stream.mjs
sh
node stream.cjs

The script prints the first update, closes its WebSocket and exits. SDK connection logs may also appear:

text
BTC/USD WebSocket price: 65001.2
WebSocket closed.

Troubleshooting ​

  • Use .mjs for import and .cjs for require. These Node.js module rules let you choose either format without configuring "type" in package.json.
  • If the SDK cannot be resolved, run the install command from the directory containing your program and package.json.
  • If a request fails or no update arrives within 30 seconds, check HTTPS and WSS access to the exchange from your network and region.
  • See Runtime compatibility for tested versions and WebSocket subscriptions for continuous subscriptions.

Built by Siebly. Open source SDKs for exchange APIs.