@siebly/kraken-api

中文文档
1.1.9发布于 2026/11/02MITTypeScriptESM + CJS构建来源已验证

Complete & robust Node.js SDK for Kraken's REST APIs and WebSockets, with TypeScript & strong end to end tests.

原始使用文档
文档目录26 节
  1. Table of Contents
  2. Installation
  3. Examples
  4. Issues & Discussion
  5. Related Projects
  6. Documentation
  7. API Documentation Links
  8. Structure
  9. REST API
  10. Spot Trading
  11. Derivatives (Futures) Trading
  12. WebSockets
  13. WebSocket Subscriptions (WebsocketClient)
  14. Why not raw ws?
  15. Spot orderbook over WebSocket
  16. Public WebSocket Streams
  17. Private WebSocket Streams
  18. WebSocket API (WebsocketAPIClient)
  19. Customise Logging
  20. Browser/Frontend Usage
  21. Webpack
  22. Use with LLMs & AI
  23. Used By
  24. Contributions & Thanks
  25. Contributions & Pull Requests
  26. Star History

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:

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

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

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

Documentation

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.

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

Webpack

Build a bundle using webpack:

  • npm install
  • npm run build
  • npm run pack

The bundle can be found in dist/. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.

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

版本与发布记录

@siebly/kraken-api 共发布 17 个版本,首次发布于 2025/12/01;过去 12 个月发布了 17 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.9latest2026/11/021 天前
1.1.82026/10/2014 天前
1.1.72026/10/1618 天前
1.1.62026/10/0627 天前
1.1.52026/09/241 个月前
1.1.42026/09/012 个月前

关于 @siebly/kraken-api 的常见问题

@siebly/kraken-api 是什么?

完整和强大的Node.js SDK,用于Kraken的REST api和WebSockets,带有TypeScript和强大的端到端测试。

如何安装 @siebly/kraken-api?

在项目目录运行 npm install @siebly/kraken-api,或使用 pnpm add / yarn add / bun add。

@siebly/kraken-api 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@siebly/kraken-api 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@siebly/kraken-api 可以商用吗?

@siebly/kraken-api 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@siebly/kraken-api 还在维护吗?

最新版本 1.1.9 发布于 2026/11/02(1 天前);至今共发布 17 个版本,其中过去 12 个月发布了 17 个;首次发布于 2025/12/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。