Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/sieblyio/kraken-api/llms.txt

Use this file to discover all available pages before exploring further.

The WebsocketAPIClient provides a REST-like interface for sending trading commands over persistent WebSocket connections. Rather than managing raw WebSocket frames yourself, each method returns a Promise that resolves when the exchange acknowledges your request — giving you the ergonomics of async/await while benefiting from the low-latency of a long-lived WebSocket connection. Internally, the client wraps the lower-level WebsocketClient and handles authentication token retrieval, caching, and injection automatically.
All methods return Promises and can be awaited. The underlying connection is established lazily — the first call will trigger authentication and connection to wss://ws-auth.kraken.com/v2.

Constructor

WSAPIClientConfigurableOptions

OptionTypeDefaultDescription
attachEventListenersbooleantrueAttaches default console.log handlers for open, reconnecting, reconnected, authenticated, and exception events. Set to false and add your own listeners via getWSClient().on(...).

Instantiation

import { WebsocketAPIClient } from '@siebly/kraken-api';

const client = new WebsocketAPIClient(
  {
    apiKey: process.env.API_SPOT_KEY,
    apiSecret: process.env.API_SPOT_SECRET,
    // Optionally disable default event listeners:
    attachEventListeners: true,
  },
  // Optional custom logger:
  // customLogger
);

getWSClient()

Returns the underlying WebsocketClient instance, giving you direct access to the event emitter, connection management, and raw subscription APIs.
const wsClient = client.getWSClient();

wsClient.on('open', (data) => console.log('connected', data.wsKey));
wsClient.on('reconnecting', ({ wsKey }) => console.log('reconnecting', wsKey));
wsClient.on('reconnected', (data) => console.log('reconnected', data.wsKey));
wsClient.on('authenticated', (data) => console.log('authenticated', data.wsKey));
wsClient.on('exception', (data) => console.error('exception', data));

Methods

submitSpotOrder

Place a new Spot order over WebSocket. Supports all Kraken order types including limit, market, stop-loss, take-profit, trailing-stop, iceberg, and conditional (bracket) orders.
submitSpotOrder(
  params: Omit<WSAPIAddSpotOrderParams, 'token' | 'req_id'>,
  wsKey?: WSAPIWsKey,
): Promise<WSAPISpotResponse<WSAPIAddSpotOrderResult, 'add_order'>>
Returns: WSAPIAddSpotOrderResult{ order_id, cl_ord_id?, order_userref?, warnings? }
order_type
string
required
Order type. One of: limit, market, iceberg, stop-loss, stop-loss-limit, take-profit, take-profit-limit, trailing-stop, trailing-stop-limit, settle-position.
side
string
required
Order direction: buy or sell.
symbol
string
required
Trading pair symbol, e.g. BTC/USD.
order_qty
number
required
Order quantity in base asset units.
limit_price
number
Limit price (required for limit, stop-loss-limit, take-profit-limit, trailing-stop-limit).
limit_price_type
string
How limit_price is interpreted: static (default), pct (percentage from trigger), or quote.
triggers
object
Trigger configuration for stop/take-profit orders. Fields: reference (index | last), price (number), price_type (static | pct | quote).
time_in_force
string
Time in force: gtc (good till cancelled), gtd (good till date), or ioc (immediate or cancel).
cl_ord_id
string
Client-assigned order ID (UUID recommended). Must be unique per account.
stp_type
string
Self-trade prevention: cancel_newest, cancel_oldest, or cancel_both.
fee_preference
string
Whether fees are paid in base or quote asset.
margin
boolean
If true, place the order on margin.
post_only
boolean
Reject the order if it would execute immediately (maker-only).
reduce_only
boolean
Only reduce an existing position.
deadline
string
ISO 8601 datetime after which the order will be rejected (RFC 3339).
validate
boolean
If true, validate the order parameters without submitting. Useful for dry-run testing.
conditional
object
Conditional (bracket) order attached to this order. Fields: order_type, limit_price, limit_price_type, trigger_price, trigger_price_type, stop_price.
display_qty
number
Visible quantity for iceberg orders.
cash_order_qty
number
Order quantity expressed in quote asset (cash) instead of base asset.
order_userref
number
User-defined integer reference for the order.
Set validate: true to perform a full dry-run of your order parameters. The exchange validates the request and returns what the order would look like without actually placing it — ideal for testing new strategies.
import { WebsocketAPIClient } from '@siebly/kraken-api';

const client = new WebsocketAPIClient({
  apiKey: process.env.API_SPOT_KEY,
  apiSecret: process.env.API_SPOT_SECRET,
});

const response = await client.submitSpotOrder({
  order_type: 'limit',
  side: 'buy',
  symbol: 'BTC/USD',
  order_qty: 1.2,
  limit_price: 26500.4,
  order_userref: 100054,
});
console.log('order_id:', response.result.order_id);

amendSpotOrder

Amend the price, quantity, or post-only flag of an existing open order without cancelling and re-placing it. Prefer this over editSpotOrder for lower latency and to avoid losing queue priority where possible.
amendSpotOrder(
  params: WSAPIAmendSpotOrderParams,
  wsKey?: WSAPIWsKey,
): Promise<WSAPISpotResponse<WSAPIAmendSpotOrderResult, 'amend_order'>>
Returns: WSAPIAmendSpotOrderResult{ amend_id, order_id?, cl_ord_id?, warnings? }
order_id
string
Exchange-assigned order ID to amend. Provide either order_id or cl_ord_id.
cl_ord_id
string
Client-assigned order ID to amend. Provide either order_id or cl_ord_id.
order_qty
number
required
New order quantity in base asset units.
limit_price
number
New limit price for the order.
limit_price_type
string
How the new limit_price is interpreted: static, pct, or quote.
trigger_price
number
New trigger price (for stop/take-profit orders).
post_only
boolean
Update the post-only flag.
deadline
string
ISO 8601 datetime deadline for the amended order.
const response = await client.amendSpotOrder({
  cl_ord_id: '2c6be801-1f53-4f79-a0bb-4ea1c95dfae9',
  limit_price: 10000,
  order_qty: 1.2,
});
console.log('amend_id:', response.result.amend_id);

editSpotOrder

Edit an existing order by cancelling it and re-placing it with updated parameters. The new order receives a new order_id.
editSpotOrder is a legacy method that cancels and re-places the order, causing loss of queue position. Use amendSpotOrder instead for in-place modification wherever possible.
editSpotOrder(
  params: WSAPIEditSpotOrderParams,
  wsKey?: WSAPIWsKey,
): Promise<WSAPISpotResponse<WSAPIEditSpotOrderResult, 'edit_order'>>
Returns: WSAPIEditSpotOrderResult{ order_id, original_order_id, warnings? }
order_id
string
required
The exchange-assigned ID of the order to edit.
symbol
string
required
Trading pair symbol (must match the original order).
order_qty
number
New order quantity.
limit_price
number
New limit price.
triggers
object
New trigger settings: reference (index | last), price, price_type.
post_only
boolean
Update the post-only flag.
validate
boolean
Validate parameters without executing the edit.
const response = await client.editSpotOrder({
  order_id: 'OAIYAU-LGI3M-PFM5VW',
  symbol: 'BTC/USD',
  order_qty: 0.5,
  limit_price: 27000,
});
console.log('new order_id:', response.result.order_id);
console.log('replaced:', response.result.original_order_id);

cancelSpotOrder

Cancel one or more open Spot orders by exchange order ID or client order ID.
cancelSpotOrder(
  params: WSAPICancelSpotOrderParams,
  wsKey?: WSAPIWsKey,
): Promise<WSAPISpotResponse<WSAPICancelSpotOrderResult, 'cancel_order'>>
Returns: WSAPICancelSpotOrderResult{ order_id, cl_ord_id?, warnings? }
order_id
string[]
Array of exchange-assigned order IDs to cancel.
cl_ord_id
string[]
Array of client-assigned order IDs to cancel.
order_userref
number[]
Array of user reference integers to cancel.
const response = await client.cancelSpotOrder({
  order_id: ['OM5CRX-N2HAL-GFGWE9', 'OLUMT4-UTEGU-ZYM7E9'],
});
console.log('cancelled order_id:', response.result.order_id);

cancelAllSpotOrders

Cancel all open Spot orders for the authenticated account in a single request.
cancelAllSpotOrders(
  wsKey?: WSAPIWsKey,
): Promise<WSAPISpotResponse<WSAPICancelAllSpotOrdersResult, 'cancel_all'>>
Returns: WSAPICancelAllSpotOrdersResult{ count, warnings? }
const response = await client.cancelAllSpotOrders();
console.log(`Cancelled ${response.result.count} orders`);

cancelAllSpotOrdersAfter

Activate a Dead Man’s Switch that cancels all open orders after the specified timeout in seconds. Send timeout: 0 to deactivate. Re-send with a positive timeout before it fires to keep resetting the timer.
cancelAllSpotOrdersAfter(
  params: WSAPICancelAllSpotOrdersAfterParams,
  wsKey?: WSAPIWsKey,
): Promise<WSAPISpotResponse<WSAPICancelAllSpotOrdersAfterResult, 'cancel_all_orders_after'>>
Returns: WSAPICancelAllSpotOrdersAfterResult{ currentTime, triggerTime, warnings? }
timeout
number
required
Number of seconds after which all open orders will be cancelled. Set to 0 to cancel the timer.
// Set a 60-second dead man's switch
const response = await client.cancelAllSpotOrdersAfter({ timeout: 60 });
console.log('Will cancel all at:', response.result.triggerTime);

// Refresh the timer (call repeatedly while your system is healthy)
await client.cancelAllSpotOrdersAfter({ timeout: 60 });

// Deactivate the switch
await client.cancelAllSpotOrdersAfter({ timeout: 0 });

batchSubmitSpotOrders

Submit between 2 and 15 Spot orders in a single WebSocket request. All orders in the batch share the same symbol and optional deadline.
batchSubmitSpotOrders(
  params: WSAPIBatchAddSpotOrdersParams,
  wsKey?: WSAPIWsKey,
): Promise<WSAPISpotResponse<WSAPIBatchAddSpotOrdersResult[], 'batch_add'>>
Returns: Array of WSAPIBatchAddSpotOrdersResult{ order_id, cl_ord_id?, order_userref?, warnings? }[]
symbol
string
required
Trading pair symbol shared by all orders in the batch, e.g. BTC/USD.
orders
array
required
Array of 2–15 order objects. Each object takes the same fields as WSAPIAddSpotOrderParams minus symbol (which is set at the top level).
deadline
string
ISO 8601 deadline applied to all orders in the batch.
validate
boolean
If true, validate all orders without submitting any.
const response = await client.batchSubmitSpotOrders({
  symbol: 'BTC/USD',
  deadline: '2025-11-19T09:53:59.050Z',
  orders: [
    {
      order_type: 'limit',
      side: 'buy',
      order_qty: 1.2,
      limit_price: 1010.1,
      order_userref: 1,
    },
    {
      order_type: 'limit',
      side: 'sell',
      order_qty: 1.2,
      limit_price: 1100.3,
      order_userref: 2,
      stp_type: 'cancel_both',
    },
  ],
  validate: false,
});

response.result.forEach((order, i) => {
  console.log(`Order ${i + 1} order_id:`, order.order_id);
});

batchCancelSpotOrders

Cancel between 2 and 50 open orders in a single WebSocket request.
batchCancelSpotOrders(
  params: WSAPIBatchCancelSpotOrdersParams,
  wsKey?: WSAPIWsKey,
): Promise<WSAPISpotResponse<WSAPIBatchCancelSpotOrdersResult, 'batch_cancel'>>
Returns: WSAPIBatchCancelSpotOrdersResult{ count, warnings? }
orders
string[]
required
Array of exchange-assigned order IDs to cancel (2–50 entries).
cl_ord_id
string[]
Array of client-assigned order IDs to cancel.
const response = await client.batchCancelSpotOrders({
  orders: ['OM5CRX-N2HAL-GFGWE9', 'OLUMT4-UTEGU-ZYM7E9'],
});
console.log(`Batch cancelled ${response.result.count} orders`);

Using sendWSAPIRequest() Directly

If you prefer the lower-level WebsocketClient interface, you can call sendWSAPIRequest() directly on the underlying client. This approach gives you full control and is the foundation the WebsocketAPIClient methods are built on.
import { WebsocketClient, WS_KEY_MAP } from '@siebly/kraken-api';

const client = new WebsocketClient({
  apiKey: process.env.API_SPOT_KEY,
  apiSecret: process.env.API_SPOT_SECRET,
});

// Attach event listeners manually
client.on('open', (data) => console.log('connected', data?.wsKey));
client.on('message', (data) => console.info('data received:', JSON.stringify(data)));
client.on('reconnecting', (data) => console.log('reconnect:', data));
client.on('reconnected', (data) => console.log('reconnected:', data));
client.on('close', (data) => console.error('close:', data));
client.on('response', (data) => console.info('server reply:', JSON.stringify(data)));
client.on('exception', (data) => console.error('exception:', data));
client.on('authenticated', (data) => console.error('authenticated:', data));

// Submit an order using the raw API
const addOrderResponse = await client.sendWSAPIRequest(
  WS_KEY_MAP.spotPrivateV2,
  'add_order',
  {
    order_type: 'limit',
    side: 'buy',
    symbol: 'BTC/USD',
    order_qty: 1.2,
    limit_price: 26500.4,
    order_userref: 100054,
  },
);
console.log('addOrderResponse:', addOrderResponse);

// Cancel orders
const cancelResponse = await client.sendWSAPIRequest(
  WS_KEY_MAP.spotPrivateV2,
  'cancel_order',
  { order_id: ['OM5CRX-N2HAL-GFGWE9', 'OLUMT4-UTEGU-ZYM7E9'] },
);
console.log('cancelResponse:', cancelResponse);

// Dead man's switch
const cancelAfterResponse = await client.sendWSAPIRequest(
  WS_KEY_MAP.spotPrivateV2,
  'cancel_all_orders_after',
  { timeout: 100 },
);
console.log('cancelAfterResponse:', cancelAfterResponse);
The WS_KEY_MAP.spotBetaPrivateV2 key is also available if you want to route requests through the beta WebSocket endpoint. Pass it as the optional second wsKey argument to any WebsocketAPIClient method, or as the first argument to sendWSAPIRequest().

Full Example

The following example demonstrates the complete Spot trading lifecycle using WebsocketAPIClient:
import { WebsocketAPIClient } from '@siebly/kraken-api';

async function main() {
  const client = new WebsocketAPIClient({
    apiKey: process.env.API_SPOT_KEY,
    apiSecret: process.env.API_SPOT_SECRET,
  });

  try {
    // 1. Place a limit buy
    const order = await client.submitSpotOrder({
      order_type: 'limit',
      side: 'buy',
      symbol: 'BTC/USD',
      order_qty: 0.001,
      limit_price: 20000,
    });
    const orderId = order.result.order_id;
    console.log('Placed order:', orderId);

    // 2. Amend the price
    const amend = await client.amendSpotOrder({
      order_id: orderId,
      order_qty: 0.001,
      limit_price: 19500,
    });
    console.log('Amended:', amend.result.amend_id);

    // 3. Cancel it
    const cancel = await client.cancelSpotOrder({ order_id: [orderId] });
    console.log('Cancelled:', cancel.result.order_id);

    // 4. Batch submit two orders
    const batch = await client.batchSubmitSpotOrders({
      symbol: 'ETH/USD',
      orders: [
        { order_type: 'limit', side: 'buy', order_qty: 0.1, limit_price: 1500 },
        { order_type: 'limit', side: 'sell', order_qty: 0.1, limit_price: 2500 },
      ],
    });
    console.log('Batch orders:', batch.result.map((o) => o.order_id));

    // 5. Cancel all open orders
    const cancelAll = await client.cancelAllSpotOrders();
    console.log(`Cancelled ${cancelAll.result.count} open orders`);

  } catch (err) {
    console.error('Error:', err);
  }
}

main();

Build docs developers (and LLMs) love