
Security News
npm Introduces minimumReleaseAge and Bulk OIDC Configuration
npm rolls out a package release cooldown and scalable trusted publishing updates as ecosystem adoption of install safeguards grows.
@siebly/kraken-api
Advanced tools
Complete & robust Node.js SDK for Kraken's REST APIs and WebSockets, with TypeScript & strong end to end tests.
Complete & robust JavaScript & Node.js SDK for the Kraken REST APIs and WebSockets:
reconnected event when dropped connection is restored.npm install --save @siebly/kraken-api
Refer to the examples folder for implementation demos, including:
Check out my related JavaScript/TypeScript/Node.js projects:
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.
This project uses typescript. Resources are stored in 2 key structures:
Create API credentials on Kraken's website:
The SDK provides dedicated REST clients for different trading products:
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.
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);
});
See DerivativesClient for further information.
Kraken supports two types of WebSocket connections:
WebsocketClientWebsocketAPIClientThe unified WebsocketClient handles all Kraken WebSocket streams with automatic connection management and reconnection.
Key WebSocket features:
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',
);
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.
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:
See the WebSocket API examples for more detailed usage.
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,
);
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.
Have my projects helped you? Share the love, there are many ways you can show your thanks:
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
FAQs
Complete & robust Node.js SDK for Kraken's REST APIs and WebSockets, with TypeScript & strong end to end tests.
The npm package @siebly/kraken-api receives a total of 10 weekly downloads. As such, @siebly/kraken-api popularity was classified as not popular.
We found that @siebly/kraken-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
npm rolls out a package release cooldown and scalable trusted publishing updates as ecosystem adoption of install safeguards grows.

Security News
AI agents are writing more code than ever, and that's creating new supply chain risks. Feross joins the Risky Business Podcast to break down what that means for open source security.

Research
/Security News
Socket uncovered four malicious NuGet packages targeting ASP.NET apps, using a typosquatted dropper and localhost proxy to steal Identity data and backdoor apps.