node-kraken-api

·

Introduction

The node-kraken-api is a fully typed Node.js client designed for seamless integration with the Kraken cryptocurrency exchange via both REST and WebSocket APIs. Built with TypeScript, this powerful library enables developers to interact efficiently with Kraken’s trading, asset, and orderbook data—ideal for algorithmic trading bots, portfolio trackers, or real-time market analysis tools.

As an unofficial yet highly reliable API wrapper, node-kraken-api pulls method definitions and documentation directly from Kraken’s official OpenAPI specifications and WebSocket documentation (version 1.8.3), ensuring accuracy and up-to-date functionality.

Whether you're retrieving real-time ticker data or managing private orders through secure WebSocket subscriptions, this package delivers robust performance with strong typing for safer development.

👉 Discover how to integrate advanced crypto trading tools into your projects effortlessly.


Key Features

Fully Typed API Responses

One of the standout advantages of node-kraken-api is its comprehensive TypeScript support. All REST and WebSocket responses are strictly typed, reducing runtime errors and improving code maintainability.

This strict typing ensures your application handles edge cases gracefully while benefiting from IDE autocomplete and compile-time error detection.

Binary Export Support

The retrieveExport method uniquely returns a binary buffer, enabling direct handling of downloadable reports such as trade history exports:

const buf = await kraken.retrieveExport({ id: "FOOB" });
fs.writeFileSync("report.zip", buf);

This feature is essential for users automating compliance or tax reporting workflows.

Real-Time Orderbook Mirroring with Checksum Validation

For high-frequency traders, maintaining an accurate local copy of the orderbook is crucial. The library supports full orderbook mirroring over WebSockets, including automatic checksum validation.

If a discrepancy is detected, the client automatically resubscribes and emits status updates—ensuring data integrity without manual intervention.

const book = await kraken.ws.book({ depth: 100 })
  .on("mirror", (mirror, pair) => console.log(mirror, pair))
  .on("status", (status) => console.log(status))
  .subscribe("XBT/USD");

Getting Started

Installation

Install the package using npm:

npm i --save node-kraken-api

Then import it into your project:

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

Configuration Options

When initializing the Kraken client, you can customize several parameters:

new Kraken({
  key?: string;         // API key (for private endpoints)
  secret?: string;      // API secret
  genotp?: () => string; // OTP generator if two-factor authentication is enabled
  gennonce?: () => number; // Custom nonce generator (default uses millisecond timestamp)
  timeout?: number;     // Request timeout in ms (default: 1000)
});
Note: If you're using an API key shared with another service that spoofs microsecond timestamps, use a custom gennonce function like () => Date.now() * 1000.

Using the REST API

Public Endpoints

Access market data without authentication:

const kraken = new Kraken();
const { unixtime } = await kraken.time();
const assets = await kraken.assets();
const ticker = await kraken.ticker({ pair: "XXBTZUSD" });

These methods are perfect for building dashboards or price alert systems.

Private Endpoints

To place trades or access account data, provide your API credentials:

const kraken = new Kraken({ key: "your-key", secret: "your-secret" });
const { txid } = await kraken.addOrder({
  pair: "XXBTZUSD",
  type: "buy",
  ordertype: "limit",
  price: "65432.1",
  volume: "1",
});

If two-factor authentication (2FA) is enabled on your account, include an OTP generator:

const kraken = new Kraken({
  key: "...",
  secret: "...",
  genotp: () => totp(key), // e.g., using 'speakeasy' or similar library
});

👉 Explore powerful tools to enhance your crypto development workflow today.


WebSocket Integration

Connection Management

WebSocket interactions are available under the .ws namespace:

Connections open automatically when data is requested. For manual control:

await kraken.ws.open();
await kraken.ws.close();

Public Subscriptions

Subscribe to real-time trade and orderbook events:

const trade = await kraken.ws.trade()
  .on('update', (update, pair) => console.log(update, pair))
  .subscribe('XBT/USD');

const book = await kraken.ws.book({ depth: 100 })
  .on("mirror", (mirror, pair) => console.log(mirror, pair))
  .subscribe("XBT/USD", "ETH/USD");

Multiple pairs can be subscribed to simultaneously.

Private Subscriptions

To receive live updates on open orders:

const { token } = await kraken.getWebSocketsToken();
const orders = kraken.ws.openOrders({ token })
  .on("update", (update, sequence) => console.log(update, sequence))
  .subscribe();
The authentication token remains valid during active subscriptions but may need refreshing after reconnection.

Migration Notes

From Version 0.4.1

The entire codebase was rewritten in TypeScript starting at v1.0.0. Major changes include:

Review the CHANGELOG before upgrading.

From Version 1.0.0

Minor breaking changes affect the Emitter class—mainly internal updates with limited impact on most implementations.


Testing & Development

To run tests locally:

  1. Create an auth.json file with read-only API credentials:

    { "key": "your-key", "secret": "your-secret" }
  2. Run npm test in the project root.

Contributions are welcome! Given the extensive use of TypeScript typings, any discrepancies should be reported via GitHub issues or pull requests.

Note: The author does not have access to Kraken’s futures API (due to regional restrictions). Developers with access are encouraged to contribute.

Frequently Asked Questions

Q: Is node-kraken-api officially supported by Kraken?
A: No, it is an unofficial library. Always refer to Kraken's official API documentation for authoritative information.

Q: Can I use this in production applications?
A: Yes—many developers use it in live trading bots and monitoring tools. Its strong typing and error handling make it suitable for production use.

Q: How do I handle WebSocket reconnections?
A: The client automatically manages reconnection and resubscription upon network loss or checksum failure.

Q: Why does retrieveExport return a buffer?
A: Because it downloads compressed binary files (e.g., ZIP archives of trade reports), which must be written directly to disk.

Q: Does the library support futures trading?
A: Not currently. The maintainer lacks access to Kraken’s futures API, but contributions are open.

Q: What should I do if I encounter a typing error?
A: Open a GitHub issue with reproduction steps. Pull requests are also appreciated.


License

This project is licensed under the MIT License—see the LICENSE file for details.

👉 Maximize your crypto development potential with cutting-edge resources now.