Node-Kraken-API: A Complete Guide for Developers

·

The Node-Kraken-API is a powerful, fully typed REST and WebSocket client designed specifically for interacting with the Kraken cryptocurrency exchange. Built for Node.js, this unofficial library provides developers with a robust toolkit for accessing market data, executing trades, and managing accounts programmatically.

This guide covers its core features, setup process, and practical usage examples to help you integrate Kraken's capabilities into your applications seamlessly.

Core Features and Benefits

The library offers a comprehensive set of tools for both public and private endpoints.

Getting Started with Node-Kraken-API

Installation and Integration

Integrating the library into your project is straightforward using npm.

npm i --save node-kraken-api

Once installed, you can import and initialize the client in your code.

import { Kraken } from "node-kraken-api";

Initial Configuration and Settings

The API client is configured with an options object during instantiation. For public data, no credentials are needed. For private endpoints, your API key and secret are required.

const kraken = new Kraken({
  /** REST API key. */
  key: "your_api_key",
  /** REST API secret. */
  secret: "your_api_secret",
  /** REST API OTP generator. */
  genotp: () => "your_otp", // Required if two-factor authentication is enabled
  /**
   * Custom nonce generator. The default uses milliseconds with a guarantee against duplication.
   * Note: If you are using an API key from another library that spoofs microsecond time,
   * you may need a custom generator (e.g., `() => Date.now() * 1000`).
   */
  gennonce: yourCustomNonceFunction,
  /** Connection timeout in milliseconds (default is 1000). */
  timeout: 5000,
});

Utilizing the REST API

Accessing Public Market Data

You can easily fetch common market information without authentication.

// Initialize without credentials for public data
const kraken = new Kraken();

// Get server time
const { unixtime } = await kraken.time();

// Fetch asset information
const { XXBT } = await kraken.assets();

// Retrieve ticker data for a trading pair
const ticker = await kraken.ticker({ pair: "XXBTZUSD" });

Managing Private User Data and Orders

Authenticated calls allow you to interact with your account, query balances, and execute trades.

// Initialize with your credentials
const kraken = new Kraken({ key: "...", secret: "..." });

// Place a new limit order
const { txid } = await kraken.addOrder({
  pair: "XXBTZUSD",
  type: "buy",
  ordertype: "limit",
  price: "65432.1",
  volume: "1",
});

The RetrieveExport endpoint is unique as it returns a binary buffer, useful for downloading account reports.

const buf = await kraken.retrieveExport({ id: "REPORT_ID" });
// Save the buffer to a file
fs.writeFileSync("report.zip", buf);

👉 Explore more advanced API strategies

Working with the WebSocket API

The WebSocket interface, located under .ws, provides real-time data streams for public and private data. Connections are managed automatically when subscriptions are made.

Subscribing to Public Feeds

Public WebSocket feeds include trade, order book, and ticker data.

const kraken = new Kraken();

// Subscribe to trade updates
const tradeSub = await kraken.ws.trade()
  .on('update', (update, pair) => console.log("New trade:", update, pair))
  .on('status', (status) => console.log("Subscription status:", status))
  .on('error', (error, pair) => console.error("Error:", error, pair))
  .subscribe('XBT/USD'); // Subscribe to a single pair

// Subscribe to a depth-100 order book with mirroring
const bookSub = await kraken.ws.book({ depth: 100 })
  .on("mirror", (mirror, pair) => console.log("Orderbook snapshot:", mirror, pair))
  .on("error", (error, pair) => console.error("Error:", error, pair))
  .subscribe("XBT/USD", "ETH/USD"); // Subscribe to multiple pairs

// Unsubscribe from specific pairs later
await bookSub.unsubscribe('XBT/USD');

Accessing Private WebSocket Data

Private feeds require an authenticated token and provide access to user-specific data like open orders.

const kraken = new Kraken({ key: "...", secret: "..." });

// First, obtain a WebSocket token
const { token } = await kraken.getWebSocketsToken();

// Then, subscribe to open orders feed
const ordersSub = kraken.ws.openOrders({ token: token })
  .on("update", (update, sequence) => console.log("Order update:", update, sequence))
  .subscribe();

// Unsubscribe when done
await ordersSub.unsubscribe();

Testing and Development Practices

The project uses a custom testing framework (@jpcx/testts). To run the test suite:

  1. Create an auth.json file in the root directory with your readonly API key and secret: { "key": "your_key", "secret": "your_secret" }.
  2. Run the command npm test to execute the tests.

Contributions to the project are encouraged. Given the complexity of maintaining accurate typings for a large API, community input is valuable. The author is also seeking contributors with access to Kraken's Futures API to help expand support.

Frequently Asked Questions

Is this the official Kraken API library?
No, this is an unofficial community-developed library. Always refer to the official Kraken API documentation for the most accurate and up-to-date information on endpoint behavior and parameters.

How do I handle two-factor authentication (2FA) with this library?
If your API key requires a two-factor authentication code, you must provide a genotp function in the settings when initializing the Kraken client. This function should return the current code as a string.

What is the purpose of the custom nonce generator?
Kraken requires a unique, incrementing number (a nonce) for each private API request. The default generator is robust, but if you are migrating from another library that used a different nonce strategy (like microsecond spoofing), you may need to provide a custom gennonce function to avoid conflicts.

How does the WebSocket orderbook mirroring work?
The library manages the complex process of building and maintaining a real-time order book from WebSocket streams. It starts with a snapshot and then applies subsequent 'bid' and 'ask' update events. It also performs automatic checksum validation to ensure data integrity and will resubscribe if a discrepancy is found.

Can I subscribe to multiple currency pairs on a single WebSocket connection?
Yes, the WebSocket client is efficient and allows you to subscribe to multiple trading pairs (e.g., .subscribe("XBT/USD", "ETH/USD")) on a single connection, reducing overhead.

Where can I report issues or contribute to the project?
The project is hosted on GitHub. You can report issues or submit pull requests through the repository. Contributions, especially those improving type definitions or adding new features, are welcome.