Skip to content

Repository files navigation

Node.js & JavaScript SDK for Kraken REST APIs & WebSockets

Build & Test npm version npm size npm downloads last commit Telegram Ask DeepWiki

SDK Logo

Complete & robust JavaScript & Node.js SDK for the Kraken REST APIs and WebSockets.

Take a look at our dedicated Kraken API quickstart guides for major frameworks and JavaScript runtimes.

  • Professional, robust & performant Kraken SDK with extensive production use in live trading environments.
  • Complete integration with all Kraken REST APIs and WebSockets.
    • Dedicated REST clients for Spot, Derivatives (Futures), Institutional, and Partner operations
    • Unified WebSocket client for all markets
  • Complete TypeScript support (with type declarations for most API requests & responses).
    • Strongly typed requests and responses.
    • Automated end-to-end tests ensuring reliability.
  • Actively maintained with a modern, promise-driven interface.
  • Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
    • Event driven messaging.
    • Smart WebSocket persistence with automatic reconnection handling.
    • Emit reconnected event when dropped connection is restored.
    • Support for both public and private WebSocket streams.
  • Browser-friendly HMAC signature mechanism.
  • Automatically supports both ESM and CJS projects.
  • Heavy automated end-to-end testing with real API calls.
  • Proxy support via axios integration.
  • Active community support & collaboration in telegram: Node.js Algo Traders.
  • QuickStart Guide: Kraken JavaScript QuickStart Guide
  • Kraken JavaScript Tutorial: Kraken JavaScript REST API and WebSocket Tutorial

Table of Contents

Installation

Install the scoped package @siebly/kraken-api:

npm install --save @siebly/kraken-api

The unscoped npm package kraken-api is a different package. It is not this SDK.

Frameworks & Quickstart Guides

Our complete Kraken SDK supports all the major JavaScript runtimes. For maximum convenience, we've included guides to quickly get you started with the most popular runtimes. If you're not sure how to use this SDK with a runtime or framework not listed here, feel free to open an issue on GitHub.

Runtime Details
Backend (trading bots) Using Node.js and JavaScript, Node.js and TypeScript, Bun, or Deno. This is the recommendation for algorithmic trading systems.
Frontend / Web Development Using React with Vite or Vite with plain JavaScript. Display REST and WebSocket prices in the browser.
Next.js App Router Using the Next.js App Router to serve the price from a Route Handler running on Node.js.
Mobile (iOS & Android) Using React Native with Expo for iOS and Android. The example guides you to display the current BTC/USD price from Kraken and stream updates over WebSockets.
Cloudflare Workers Cloudflare Workers. Return a public price from a Worker, with a separate example for authenticated orders.

Refer to runtime compatibility for a complete list of runtimes that we've actively tested, including setup guides.

Examples

Refer to the examples folder for implementation demos, including:

  • Spot Trading Examples: market data, account management, order placement
  • Derivatives Trading Examples: futures market data, account management, order placement
  • WebSocket Examples: public market data streams, private account data

Issues & Discussion

  • Issues? Check the issues tab.
  • Discuss & collaborate with other node devs? Join our Node.js Algo Traders engineering community on telegram.
  • Follow our announcement channel for real-time updates on X/Twitter

Related Projects

Check out our JavaScript/TypeScript/Node.js SDKs & Projects:

Documentation

The Kraken SDK documentation covers installation, client setup, public market data, authenticated trading, and WebSocket subscriptions.

Most methods accept JS objects. These can be populated using parameters specified by Kraken's API documentation, or check the type definition in each class within this repository.

API Documentation Links

Structure

This project uses typescript. Resources are stored in 2 key structures:

  • src - the whole connector written in typescript
  • examples - some implementation examples & demonstrations. Contributions are welcome!

Usage

Create API credentials on Kraken's website:

REST API

The SDK provides dedicated REST clients for different trading products:

  • SpotClient - for spot trading, staking, and account operations
  • DerivativesClient - for futures trading operations
  • InstitutionalClient - for institutional trading and custody
  • PartnerClient - for partner and affiliate operations

Spot Trading

To use Kraken's Spot APIs, import (or require) the SpotClient:

import { SpotClient } from '@siebly/kraken-api';
// or if you prefer require:
// const { SpotClient } = require('@siebly/kraken-api');

// For public endpoints, API credentials are optional
const publicClient = new SpotClient();

// For private endpoints, provide API credentials
const client = new SpotClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-base64-encoded-private-key',
});

// Public API Examples

// Get ticker information
const ticker = await publicClient.getTicker({
  pair: 'XBTUSD',
});
console.log('Ticker: ', ticker);

// Get order book
const orderBook = await publicClient.getOrderBook({
  pair: 'XBTUSD',
  count: 10,
});
console.log('Order Book: ', orderBook);

// Private API Examples (requires authentication)

// Submit a market order
client
  .submitOrder({
    ordertype: 'market',
    type: 'buy',
    volume: '0.01',
    pair: 'XBTUSD',
    cl_ord_id: client.generateNewOrderID(),
  })
  .then((result) => {
    console.log('Market Order Result: ', result);
  })
  .catch((err) => {
    console.error('Error: ', err);
  });

// Submit a limit order
client
  .submitOrder({
    ordertype: 'limit',
    type: 'buy',
    volume: '0.0001',
    pair: 'XBTUSD',
    price: '10000',
    cl_ord_id: client.generateNewOrderID(),
  })
  .then((result) => {
    console.log('Limit Order Result: ', result);
  })
  .catch((err) => {
    console.error('Error: ', err);
  });

// Submit batch of orders (minimum 2, maximum 15)
client
  .submitBatchOrders({
    pair: 'XBTUSD',
    orders: [
      {
        ordertype: 'limit',
        type: 'buy',
        volume: '0.0001',
        price: '10000.00',
        timeinforce: 'GTC',
        cl_ord_id: client.generateNewOrderID(),
      },
      {
        ordertype: 'limit',
        type: 'buy',
        volume: '0.0001',
        price: '11111.00',
        timeinforce: 'GTC',
        cl_ord_id: client.generateNewOrderID(),
      },
      {
        ordertype: 'limit',
        type: 'sell',
        volume: '0.0001',
        price: '13000.00',
        timeinforce: 'GTC',
        cl_ord_id: client.generateNewOrderID(),
      },
    ],
  })
  .then((result) => {
    console.log('Batch Order Result: ', JSON.stringify(result, null, 2));
  })
  .catch((err) => {
    console.error('Error: ', err);
  });

// Get account balances
client
  .getAccountBalance()
  .then((balance) => {
    console.log('Account Balance: ', balance);
  })
  .catch((err) => {
    console.error('Error: ', err);
  });

See SpotClient for further information, or the examples for lots of usage examples.

Derivatives (Futures) Trading

Use the DerivativesClient for futures trading operations:

import { DerivativesClient } from '@siebly/kraken-api';
// or if you prefer require:
// const { DerivativesClient } = require('@siebly/kraken-api');

// For public endpoints, API credentials are optional
const publicClient = new DerivativesClient();

// For private endpoints, provide API credentials
const client = new DerivativesClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
});

// Public API Examples

// Get order book for a specific instrument
const orderBook = await publicClient.getOrderBook({
  symbol: 'PF_XBTUSD',
});
console.log('Futures Order Book: ', orderBook);

// Get ticker information
const ticker = await publicClient.getTickers({
  symbol: 'PF_XBTUSD',
});
console.log('Futures Ticker: ', ticker);

// Private API Examples (requires authentication)

// Get account balances
client
  .getAccountsDetails()
  .then((accounts) => {
    console.log('Accounts Details: ', accounts);
  })
  .catch((err) => {
    console.error('Error: ', err);
  });

// Submit a limit order
client
  .submitOrder({
    orderType: 'lmt',
    symbol: 'PF_ETHUSD', // Perpetual ETH/USD
    side: 'buy',
    size: 0.01, // Contract size
    limitPrice: 1000,
    cliOrdId: client.generateNewOrderID(),
  })
  .then((result) => {
    console.log('Limit Order Result: ', JSON.stringify(result, null, 2));
  })
  .catch((err) => {
    console.error('Error: ', err);
  });

Kraken retired the Futures demo (testnet) environment on 14 July 2026. There is no replacement demo host, and Spot never had a testnet. Setting testnet: true on DerivativesClient or WebsocketClient throws. See the announcement.

See DerivativesClient for further information.

WebSockets

Kraken supports two types of WebSocket connections:

  1. WebSocket Subscriptions - Real-time market data and account updates via the WebsocketClient
  2. WebSocket API - REST-like request/response trading via the WebsocketAPIClient

WebSocket Subscriptions (WebsocketClient)

The unified WebsocketClient handles all Kraken WebSocket streams with automatic connection management and reconnection.

Key WebSocket features:

  • Event driven messaging
  • Smart WebSocket persistence with automatic reconnection
  • Heartbeat mechanisms to detect disconnections
  • Automatic resubscription after reconnection
  • Support for both Spot and Futures markets
  • Support for both public and private WebSocket streams

Why not raw ws?

A raw ws socket leaves reconnect, liveness, resubscribe, and auth to you. WebsocketClient does that work:

  • Reconnects a dropped socket, then resubscribes to the topics already requested.
  • Heartbeats (native ping/pong, plus Kraken heartbeat / pong frames) so a silent socket is treated as dead and reconnected.
  • Private auth: Spot WebSocket tokens are fetched from REST, cached, and refreshed before they expire. Futures private streams use the signed challenge flow, and a reconnect re-authenticates.

Kraken book payloads include a checksum. This SDK does not validate it. Spot orderbook over WebSocket keeps a local book and checks that checksum.

import { WebsocketClient } from '@siebly/kraken-api';
const ws = new WebsocketClient();
ws.on('message', (data) => console.log(data));
ws.subscribe(
  { topic: 'ticker', payload: { symbol: ['BTC/USD'] } },
  'spotPublicV2',
);

Spot orderbook over WebSocket

Use WebsocketClient to maintain a Spot orderbook over WebSocket with checksum validation, as shown in the runnable local orderbook example. The example applies snapshots and updates, restores pair precision for CRC32 validation, resubscribes on checksum mismatch, and logs the best bid and ask. The SDK handles reconnects, heartbeats, and resubscription after reconnect; the example supplies the local book and checksum resync logic that a raw ws socket leaves to you.

Public WebSocket Streams

For public market data, API credentials are not required:

import { WebsocketClient } from '@siebly/kraken-api';
// or if you prefer require:
// const { WebsocketClient } = require('@siebly/kraken-api');
// Create WebSocket client for public streams
const wsClient = new WebsocketClient();

// Set up event handlers
wsClient.on('open', (data) => {
  console.log('WebSocket connected: ', data?.wsKey);
});

wsClient.on('message', (data) => {
  console.log('Data received: ', JSON.stringify(data, null, 2));
});

wsClient.on('reconnected', (data) => {
  console.log('WebSocket reconnected: ', data);
});

wsClient.on('exception', (data) => {
  console.error('WebSocket error: ', data);
});

// Spot - Subscribe to public data streams
wsClient.subscribe(
  {
    topic: 'ticker',
    payload: {
      symbol: ['BTC/USD', 'ETH/USD'],
    },
  },
  'spotPublicV2',
);

wsClient.subscribe(
  {
    topic: 'book',
    payload: {
      symbol: ['BTC/USD'],
      depth: 10,
    },
  },
  'spotPublicV2',
);

// Derivatives - Subscribe to public data streams
wsClient.subscribe(
  {
    topic: 'ticker',
    payload: {
      product_ids: ['PI_XBTUSD', 'PI_ETHUSD'],
    },
  },
  'derivativesPublicV1',
);

wsClient.subscribe(
  {
    topic: 'book',
    payload: {
      product_ids: ['PI_XBTUSD'],
    },
  },
  'derivativesPublicV1',
);

Private WebSocket Streams

For private account data streams, API credentials are required:

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

// Create WebSocket client with API credentials for private streams
const wsClient = new WebsocketClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
});

// Set up event handlers
wsClient.on('open', (data) => {
  console.log('Private WebSocket connected: ', data?.wsKey);
});

wsClient.on('message', (data) => {
  console.log('Private data received: ', JSON.stringify(data, null, 2));
});

wsClient.on('authenticated', (data) => {
  console.log('WebSocket authenticated: ', data);
});

wsClient.on('response', (data) => {
  console.log('WebSocket response: ', data);
});

wsClient.on('exception', (data) => {
  console.error('WebSocket error: ', data);
});

// Spot - Subscribe to private data streams
wsClient.subscribe(
  {
    topic: 'executions',
    payload: {
      snap_trades: true,
      snap_orders: true,
      order_status: true,
    },
  },
  'spotPrivateV2',
);

wsClient.subscribe(
  {
    topic: 'balances',
    payload: {
      snapshot: true,
    },
  },
  'spotPrivateV2',
);

// Derivatives - Subscribe to private data streams
// Note: SDK automatically handles authentication and challenge tokens
wsClient.subscribe('open_orders', 'derivativesPrivateV1');

wsClient.subscribe(
  {
    topic: 'fills',
    payload: {
      product_ids: ['PF_XBTUSD'],
    },
  },
  'derivativesPrivateV1',
);

wsClient.subscribe('balances', 'derivativesPrivateV1');

wsClient.subscribe('open_positions', 'derivativesPrivateV1');

For more comprehensive examples, including custom logging and error handling, check the examples folder.

WebSocket API (WebsocketAPIClient)

The WebsocketAPIClient provides a REST-like interface for trading operations over WebSocket, offering lower latency than REST APIs. Currently, only Spot trading is supported.

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

// Create WebSocket API client with credentials
const wsApiClient = new WebsocketAPIClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
});

// The client handles event listeners automatically, but you can customize them
wsApiClient
  .getWSClient()
  .on('open', (data) => {
    console.log('WebSocket API connected:', data.wsKey);
  })
  .on('response', (data) => {
    console.log('Response:', data);
  })
  .on('exception', (data) => {
    console.error('Error:', data);
  });

// Trading operations return promises

// Submit a spot order
const orderResponse = await wsApiClient.submitSpotOrder({
  order_type: 'limit',
  side: 'buy',
  limit_price: 26500.4,
  order_qty: 1.2,
  symbol: 'BTC/USD',
});
console.log('Order placed:', orderResponse);

// Amend an existing order
const amendResponse = await wsApiClient.amendSpotOrder({
  order_id: 'OAIYAU-LGI3M-PFM5VW',
  order_qty: 1.5,
  limit_price: 27000,
});

// Cancel specific orders
const cancelResponse = await wsApiClient.cancelSpotOrder({
  order_id: ['OM5CRX-N2HAL-GFGWE9', 'OLUMT4-UTEGU-ZYM7E9'],
});

// Cancel all open orders
const cancelAllResponse = await wsApiClient.cancelAllSpotOrders();

The WebSocket API provides several advantages:

  • Lower Latency - Faster than REST API for high-frequency trading
  • Connection Reuse - Single persistent connection for multiple requests
  • Better Performance - Batch operations for submitting/canceling multiple orders
  • Type Safety - Full TypeScript support with typed requests and responses

See the WebSocket API examples for more detailed usage.


Customise Logging

Pass a custom logger which supports the log methods trace, info and error, or override methods from the default logger as desired.

import { WebsocketClient, DefaultLogger } from '@siebly/kraken-api';

// E.g. customise logging for only the trace level:
const customLogger: DefaultLogger = {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  trace: (...params: LogParams): void => {
    // console.log('trace', ...params);
  },
  info: (...params: LogParams): void => {
    console.log('info', ...params);
  },
  error: (...params: LogParams): void => {
    console.error('error', ...params);
  },
};

const ws = new WebsocketClient(
  {
    apiKey: 'apiKeyHere',
    apiSecret: 'apiSecretHere',
  },
  customLogger,
);

Browser/Frontend Usage

The npm package includes ES module and CommonJS builds. You do not need to build the SDK's standalone Webpack bundle to use it in a frontend project. Choose the setup for your application below.

Vite and React

Use the Vite guide or React guide for a complete public market-data project that imports @siebly/kraken-api from npm.

Keep the supplied bundler configuration with the example: it provides EventEmitter through the events alias. These browser examples use public Kraken Spot data. Keep private keys and API credentials in a secure server-side environment and make authenticated calls there.

Browser REST requests also depend on Kraken's CORS policy. Keep the guides' public GET client configuration, which removes the SDK's UserAgent and locale headers to avoid a failing CORS preflight. This setup is limited to public GET requests. If a request is blocked, call the SDK through your application's server route instead. A development proxy does not solve CORS for a deployed application.

Next.js and server-side requests

The Next.js guide runs the SDK in a Node.js Route Handler and returns the result to the frontend. Use this pattern when requests need credentials or cannot be made directly from the browser.

React Native and Expo

Follow the Expo guide for its Metro configuration and required polyfill dependencies, including its HTTP, HTTPS and URL aliases. Browser bundler configuration is not interchangeable with Metro configuration. The example uses public Kraken Spot data; keep authenticated operations on your server.

Standalone Webpack bundle

If you need a standalone UMD bundle rather than npm imports in your application, the SDK repository includes a Webpack configuration. From a checkout of this repository:

npm install
npm run build
npm run pack

The configuration writes dist/krakenapi.js with the krakenapi global name. It disables Node.js http and https imports; the REST client's Node-only https.Agent is unavailable in browsers. This is a separate packaging option, not a required step for the framework guides above. Browser-specific configuration and API access restrictions still apply.

Use with LLMs & AI

This SDK includes a bundled llms.txt file in the root of the repository. If you're developing with LLMs, use the included llms.txt with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK.

This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence.


Used By

Repository Users Preview Image


Contributions & Thanks

Have my projects helped you? Share the love, there are many ways you can show your thanks:

Contributions & Pull Requests

Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.

Star History

Star History Chart

Releases

Sponsor this project

Used by

Contributors

Languages