@siebly/kraken-api
v1.0.1
Published
Complete & robust Node.js SDK for Kraken's REST APIs and WebSockets, with TypeScript & strong end to end tests.
Maintainers
Readme
Node.js & JavaScript SDK for Kraken REST APIs & WebSockets
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
reconnectedevent 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.
Table of Contents
- Installation
- Examples
- Issues & Discussion
- Related Projects
- Documentation
- Structure
- Usage
- Customise Logging
- LLMs & AI
- Used By
- Contributions & Thanks
Installation
npm install --save @siebly/kraken-api
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 my related JavaScript/TypeScript/Node.js projects:
- Try my REST API & WebSocket SDKs:
- Try my misc utilities:
- Check out my examples:
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.
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);
});See DerivativesClient for further information.
WebSockets
Kraken supports two types of WebSocket connections:
- WebSocket Subscriptions - Real-time market data and account updates via the
WebsocketClient - 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
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,
);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
Contributions & Thanks
Have my projects helped you? Share the love, there are many ways you can show your thanks:
- Star & share my projects.
- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler
- Have an interesting project? Get in touch & invite me to it.
- Or buy me all the coffee:
- ETH(ERC20):
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
- ETH(ERC20):
Contributions & Pull Requests
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
