1.2.0 • Published 3 years ago

kalamar v1.2.0

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

Kalamar

npm version

A set of HTTP REST methods and WebSocket subscribers and clients for the API of the cryptocurrency trading platform kraken.com.

Summary

  1. Installation
  2. How to access the kraken API
  3. Kraken API Documentation
  4. Package Documentation
  5. Testing
  6. Rest methods
    1. Nonce
    2. Headers
    3. Rate limits
    4. Errors
    5. Rest Config
    6. Public methods examples
      1. assetPairs
      2. assets
      3. depth
      4. spread
      5. systemStatus
      6. ticker
      7. time
      8. trades
    7. Private methods examples
      1. addExport
      2. balance
      3. closedOrders
      4. exportStatus
      5. getWebSocketsToken
      6. ledgers
      7. openOrders
      8. openPositions
      9. queryLedgers
      10. queryOrders
      11. queryTrades
      12. retrieveExport
      13. tradeBalance
      14. tradesHistory
      15. tradeVolume
    8. Trading methods
      1. addOrder
      2. cancelAll
      3. cancelAllOrdersAfter
      4. cancelOrder
    9. Withdraw methods
      1. withdraw
      2. withdrawCancel
      3. withdrawInfo
      4. withdrawStatus
  7. WebSocket Subscribers examples
    1. TickerSubscriber
    2. OHLCSubscriber
    3. TradeSubscriber
    4. SpreadSubscriber
    5. BookSubscriber
  8. WebSocket Clients examples
    1. AddOrderClient
    2. CancelOrderClient
    3. CancelAllClient
    4. CancelAllOrdersAfterClient

Installation

You must install [NodeJS](https://nodejs.org/en/) and use your favorite package manager.

npm i kalamar
#or
yarn add kalamar

How to access the kraken API

Public methods (ticker,trades, spread...) won't require public and private API keys but private methods (account informations, trade orders, withdrawal...) will.

You need to create an account on [kraken](https://www.kraken.com/) then go to the security settings and create an API key. Copy the keys as the private key will no longer be available after its creation.

Best practice will be to register those keys in your environment variables on your server. The use of this package as part of a client-side application is not recommended when using private methods since it lets the API keys appear in clear.

It is recommended to use a proxy server in order to bridge the gap between your client and the kraken servers, the url property of the RestConfig is here for that purpose.

I have written a [proxy server](https://github.com/vivienld/kraken-proxy-server) in typescript with the expressJS framework.

Kraken API Documentation

Every REST method, Websocket client and payload is based on the Kraken official documentation.

[REST API documentation](https://docs.kraken.com/rest/)

[WebSocket API documentation](https://docs.kraken.com/websockets/)

Package Documentation

A [package documentation](https://vivienld.github.io/kalamar/) with every methods, classes, interfaces and types has been generated thanks to [Typedoc](https://typedoc.org/).

Testing

Tests are available in the tests folder. Thoses tests are carried out by Jest. Add your keys in you env vars or in a .env file.

KRAKEN_API = public_key
KRAKEN_SECRET = private_key

Don't run all tests at once! You don't know which request will be treated first and this can result in a invalid nonce error or in a too many concurrent error.

Some tests require specific transaction id, withdraw methods require wallet informations... so you may have to customize them.

Rest methods

Rest methods return a Promise. The promise will resolve if the server returns a response, either there is a result or an error.

Best way to know if the server returned errors is to verify that the length of the response.error is superior to 0. It will mean that server returned no result.

Nonce

When you make a REST request, Kraken servers ask for a nonce. It is a number that must be incremented at the next request and it cannot be reset. Nonce is automatically added to any request by getting the current timestamp * 1000. Be careful not to make requests that are too close to each other, or else the B request could arrive before the A request and produce an "invalid nonce" error. Too many nonce errors cause a 15-minute ban on the servers. The nonce is used to produce the API-Sign header.

Headers

4 headers are automatically added to the requests.

The User-Agent header is required by the API and is added with the value Kraken Javascript API Client to every request.

The Content-Type header is required by the API and is added with the value application/x-www-form-urlencoded to every request.

The API-Key header is added to every private request.

The API-Sign header is added to every private request and its value is calculated with the nonce and the public and private API keys provided in the RestConfig of every private method.

Rate limits

Every kraken user has a counter starting at 0 and going from 15 to 20 according to their verification tier. Every request inscreases this counter by less or more points depending on the method. Reaching your counter or making too many concurrent requests will provoke a temporary ban. See [documentation](https://docs.kraken.com/rest/#section/Rate-Limits/REST-API-Rate-Limits).

Errors

The kraken servers will always return a response. This response is a JSON object with a error field and a result field. The error field is a string array containing the reasons of the request failure. See [documentation](https://docs.kraken.com/rest/#section/General-Usage/Requests-Responses-and-Errors).

RestConfig

Rest configuration is the last argument of public and private methods.

In public methods, it is optional, in private methods, the minimal properties to fill are apiKey and secret since they are retrieving personal data.

If you protected your API key with a two-factor authentication, you will have to set doubleAuthentication to true and define the one time password defined by your two-factor authentication app.

interface RestConfig {
    /** API public Key */
    apiKey?: string
    /** API secret key */
    secret?: string
    /** The REST API URL. Default: 'https://api.kraken.com' */
    url?: string
    /** API version. Default: 0 */
    version?: number
    /** Axios request timeout: Default: 5000ms */
    timeout?: number
    /** whether two-factor authentication is enabled on the API key. Default: false */
    doubleAuthentication?: boolean
    /** One Time Password for double authentification */
    otp?: any
}

Public methods examples

[assetPairs](https://docs.kraken.com/rest/#operation/getTradableAssetPairs)

Get tradable asset pairs

import Rest from 'kalamar'
//or
import {assetPairs} from 'kalamar/dist/rest'

Rest.assetPairs({ pair: "DOGEEUR" },optionalRestConfig)
.then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[assets](https://docs.kraken.com/rest/#operation/getAssetInfo)

Get information about the assets that are available for deposit, withdrawal, trading and staking.

import Rest from 'kalamar'
//or
import {assets} from 'kalamar/dist/rest'

Rest.assets({ asset: "BTC" },optionalRestConfig)
.then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[depth](https://docs.kraken.com/rest/#operation/getOrderBook)

Get Order Book

import Rest from 'kalamar'
//or
import {depth} from 'kalamar/dist/rest'

Rest.depth({ pair: "BTCUSD" },optionalRestConfig)
.then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[spread](https://docs.kraken.com/rest/#operation/getRecentSpreads)

Get Recent Spreads

import Rest from 'kalamar'
//or
import {spread} from 'kalamar/dist/rest'

Rest.spread({ pair: "BTCUSD" },optionalRestConfig)
.then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[systemStatus](https://docs.kraken.com/rest/#operation/getSystemStatus)

Get the current system status or trading mode.

import Rest from 'kalamar'
//or
import {systemStatus} from 'kalamar/dist/rest'

Rest.systemStatus(optionalRestConfig)
.then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[ticker](https://docs.kraken.com/rest/#operation/getTickerInformation)

Get Ticker Information

import Rest from 'kalamar'
//or
import {ticker} from 'kalamar/dist/rest'

Rest.ticker({pair:"BTCUSD"},optionalRestConfig)
.then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[time](https://docs.kraken.com/rest/#operation/getServerTime)

Get the server's time.

import Rest from 'kalamar'
//or
import {time} from 'kalamar/dist/rest'

Rest.time(optionalRestConfig)
.then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[trades](https://docs.kraken.com/rest/#operation/getRecentTrades)

Get Recent Trades. Returns the last 1000 trades by default

import Rest from 'kalamar'
//or
import {trades} from 'kalamar/dist/rest'

Rest.trades({pair:"BTCUSD"},optionalRestConfig)
.then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

Private method example

Most private methods have a request payload as first argument and the request configuration as second argument. Configuration is where you define the API key and the secret key, axios timeout or the server base url to communicate with (see [how to access kraken API](#how-to-access-the-kraken-API) and no-cors issues for in-browser implementation)

[addExport](https://docs.kraken.com/rest/#operation/addExport)

Request export of trades or ledgers.

import Rest from 'kalamar'
//or
import {addExport} from 'kalamar/dist/rest'

Rest.addExport({ 
    description: "my-desc", 
    report: "ledgers" },
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[balance](https://docs.kraken.com/rest/#operation/getAccountBalance)

Retrieve all cash balances, net of pending withdrawals.

import Rest from 'kalamar'
//or
import {balance} from 'kalamar/dist/rest'

Rest.balance({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[closedOrders](https://docs.kraken.com/rest/#operation/getClosedOrders)

Retrieve information about orders that have been closed (filled or cancelled).

import Rest from 'kalamar'
//or
import {closedOrders} from 'kalamar/dist/rest'

Rest.closedOrders(undefined,{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[exportStatus](https://docs.kraken.com/rest/#operation/exportStatus)

Get status of requested data exports.

import Rest from 'kalamar'
//or
import {exportStatus} from 'kalamar/dist/rest'

Rest.exportStatus({ report: 'trades' },{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[getWebSocketsToken](https://docs.kraken.com/rest/#operation/getWebsocketsToken)

Get Websockets Token

@see —

import Rest from 'kalamar'
//or
import {getWebSocketsToken} from 'kalamar/dist/rest'

Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[ledgers](https://docs.kraken.com/rest/#operation/getLedgers)

Retrieve information about ledger entries. 50 results are returned at a time, the most recent by default.

import Rest from 'kalamar'
//or
import {ledgers} from 'kalamar/dist/rest'

Rest.ledgers(undefined,{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[openOrders](https://docs.kraken.com/rest/#operation/getOpenOrders)

Retrieve information about currently open orders.

import Rest from 'kalamar'
//or
import {openOrders} from 'kalamar/dist/rest'

Rest.openOrders(undefined,{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[openPositions](https://docs.kraken.com/rest/#operation/getOpenPositions)

Get information about open margin positions.

import Rest from 'kalamar'
//or
import {openPositions} from 'kalamar/dist/rest'

Rest.openPositions(undefined,{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[queryLedgers](https://docs.kraken.com/rest/#operation/getLedgersInfo)

Retrieve information about specific ledger entries.

import Rest from 'kalamar'
//or
import {queryLedgers} from 'kalamar/dist/rest'

Rest.queryLedgers({ id: "ledger-entry-id" },{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[queryOrders](https://docs.kraken.com/rest/#operation/getOrdersInfo)

Retrieve information about specific orders.

import Rest from 'kalamar'
//or
import {queryOrders} from 'kalamar/dist/rest'

Rest.queryOrders({ txid: "transaction-id,another,another,..." },{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[queryTrades](https://docs.kraken.com/rest/#operation/getTradesInfo)

Retrieve information about specific trades/fills.

import Rest from 'kalamar'
//or
import {queryTrades} from 'kalamar/dist/rest'

Rest.queryTrades({ txid: "transaction-id,another,another,..." },{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[retrieveExport](https://docs.kraken.com/rest/#operation/retrieveExport)

Retrieve a processed data export

import Rest from 'kalamar'
//or
import {retrieveExport} from 'kalamar/dist/rest'

Rest.retrieveExport({ id: "export-id,another,another,..." },{
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[tradeBalance](https://docs.kraken.com/rest/#operation/getTradeBalance)

Retrieve a summary of collateral balances, margin position valuations, equity and margin level.

import Rest from 'kalamar'
//or
import {tradeBalance} from 'kalamar/dist/rest'

Rest.tradeBalance({asset: "ZUSD"},
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[tradesHistory](https://docs.kraken.com/rest/#operation/getTradeHistory)

Retrieve information about trades/fills.

import Rest from 'kalamar'
//or
import {tradesHistory} from 'kalamar/dist/rest'

Rest.tradesHistory(undefined,
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[tradeVolume](https://docs.kraken.com/rest/#operation/getTradeVolume)

Get trade volume

import Rest from 'kalamar'
//or
import {tradeVolume} from 'kalamar/dist/rest'

Rest.tradeVolume(undefined,
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

Trading methods

[addOrder](https://docs.kraken.com/rest/#operation/addOrder)

Place a new order.

import Rest from 'kalamar'
//or
import {addOrder} from 'kalamar/dist/rest'

Rest.addOrder({
        ordertype: 'market',
        pair: "DOGEEUR",
        type: "buy",
        volume: "50",
        price: "0.1"
    },
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[cancelAll](https://docs.kraken.com/rest/#operation/cancelAllOrders)

Cancel all open orders

import Rest from 'kalamar'
//or
import {cancelAll} from 'kalamar/dist/rest'

Rest.cancelAll({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[cancelAllOrdersAfter](https://docs.kraken.com/rest/#operation/cancelAllOrdersAfter)

Cancel All Orders After X seconds

import Rest from 'kalamar'
//or
import {cancelAllOrdersAfter} from 'kalamar/dist/rest'

Rest.cancelAllOrdersAfter({ timeout: 30 },
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[cancelOrder](https://docs.kraken.com/rest/#operation/cancelOrder)

Cancel a particular open order (or set of open orders) by txid or userref

import Rest from 'kalamar'
//or
import {cancelOrder} from 'kalamar/dist/rest'

Rest.cancelOrder(txid: "transaction-id,another,..." },
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

Withdraw methods

[withdraw](https://docs.kraken.com/rest/#operation/withdrawFunds)

Make a withdrawal request.

import Rest from 'kalamar'
//or
import {withdraw} from 'kalamar/dist/rest'

Rest.withdraw({
    amount: "1",
    asset: "BTW",
    key:"withdrawal-key"
}, 
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[withdrawCancel](https://docs.kraken.com/rest/#operation/cancelWithdrawal)

Cancel a recently requested withdrawal, if it has not already been successfully processed.

import Rest from 'kalamar'
//or
import {withdrawCancel} from 'kalamar/dist/rest'

Rest.withdrawCancel({
    refid:"withdrawal-ref-id",
    asset: "BTC"
}, 
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[withdrawInfo](https://docs.kraken.com/rest/#operation/getWithdrawalInformation)

Retrieve fee information about potential withdrawals for a particular asset, key and amount.

import Rest from 'kalamar'
//or
import {withdrawInfo} from 'kalamar/dist/rest'

Rest.withdrawInfo({
    amount: "1",
    key:"withdrawal-key-name",
    asset: "BTC"
}, 
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

[withdrawStatus](https://docs.kraken.com/rest/#operation/getStatusRecentWithdrawals)

Retrieve information about recently requests withdrawals.

import Rest from 'kalamar'
//or
import {withdrawStatus} from 'kalamar/dist/rest'

Rest.withdrawStatus({
    method:"Bitcoin",
    asset: "BTC"
}, 
  {
    apiKey: "your api key",
    secret: " your secret key"
  }).then(payload =>{
    const {result,error} = payload
}).catch(error=>{
    ...
})

WebSocket subscribers Examples

A subscriber will connect to the webSocket API server, subscribe to an endpoint and listen to messages.

The first thing will be to retrieve a token with the REST method getWebSocketsToken, then instantiate the subscriber with the retrieved token. Every subscriber has event handlers according to the message type sent by the server.

Shared handlers are:

  • onOpen : called when subscriber is connected to the server (readyState 1). The subscriber connects to the server with the connect method. connect is not subscribe, subscribe is a method sending a subscribe message to an endpoint so the subscriber can start listening to that endpoint if subscription is accepted. subscribe must be called inside the onOpen handler.

  • onError : called when the subscription has failed

  • onPayload : called when the server sends data that is not an error message or a subscription message

  • onSubscribed : called when the subscriber has subscribed to the given endpoint with the subscribe method

  • onUnsubscribed : called when the subscriber has unsubscribed from the given endpoint with the unsubscribe method

  • onSystemStatus : after subscription, the server will return its status. Call when receiving this message.

[TickerSubscriber](https://docs.kraken.com/websockets/#message-ticker)

Ticker information on currency pair.

import Rest,{TickerSubscriber} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {
        const subscriber = new TickerSubscriber({
            token: res.result.token
        })

        //handle tickerPayload messages
        subscriber.onPayload = (tickerPayload) => {
            console.log(tickerPayload)
        }

        // handle errorPayload message
        subscriber.onError = (errorPayload) => {
            console.log(errorPayload)
        }

        //subscriber is subscribed to endpoint
        subscriber.onSubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //subscriber is unsubscribed from endpoint
        subscriber.onUnsubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //system status received when subscribed
        subscriber.onSystemStatus = (systemStatusPayload) => {
            console.log(errorPayload)
        }

        //handle opened connection 
        subscriber.onOpen = (event) => {
            //subscribe to the implicit "ticker" endpoint and listen to the BTC-USD  asset pair ticks
            subscriber.subscribe({
                pair: ["BTC/USD"]
            })
        }

        //connect to the server
        subscriber.connect();
}).catch(e => {
    console.log(e)
})

[BookSubscriber](https://docs.kraken.com/websockets/#message-book)

Order book levels. On subscription, a snapshot will be published at the specified depth, following the snapshot, level updates will be published

import Rest,{BookSubscriber} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {
        const subscriber = new BookSubscriber({
            token: res.result.token
        })

        //handle snapshotPayload messages
        subscriber.onFirstPayload = (snapshotPayload) => {
            console.log(snapshotPayload)
        }

        //handle updatePayload messages
        subscriber.onPayload = (updatePayload) => {
            console.log(updatePayload)
        }
    
        // handle errorPayload message
        subscriber.onError = (errorPayload) => {
            console.log(errorPayload)
        }

        //subscriber is subscribed to endpoint
        subscriber.onSubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //subscriber is unsubscribed from endpoint
        subscriber.onUnsubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //system status received when subscribed
        subscriber.onSystemStatus = (systemStatusPayload) => {
            console.log(errorPayload)
        }

        //handle opened connection 
        subscriber.onOpen = (event) => {
            //subscribe to the implicit "book" endpoint and listen to the BTC-USD asset pair ticks
            subscriber.subscribe({
                pair: ["BTC/USD"]
            })
        }

        //connect to the server
        subscriber.connect();
}).catch(e => {
    console.log(e)
})

[OHLCSubscriber](https://docs.kraken.com/websockets/#message-ohlc)

Open High Low Close (Candle) feed for a currency pair and interval period.

import Rest,{OHLCSubscriber} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {
        const subscriber = new OHLCSubscriber({
        token: res.result.token
    })

        //handle ohlcPayload messages
        subscriber.onPayload = (ohlcPayload) => {
            console.log(ohlcPayload)
        }

        // handle errorPayload message
        subscriber.onError = (errorPayload) => {
            console.log(errorPayload)
        }

        //subscriber is subscribed to endpoint
        subscriber.onSubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //subscriber is unsubscribed from endpoint
        subscriber.onUnsubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //system status received when subscribed
        subscriber.onSystemStatus = (systemStatusPayload) => {
            console.log(errorPayload)
        }
        //handle opened connection 
        subscriber.onOpen = (event) => {
            //subscribe to the implicit "ohlc" endpoint and listen to the BTC-USD asset pair ticks
            subscriber.subscribe({
                pair: ["BTC/USD"]
            })
        }

        //connect to the server
        subscriber.connect();
}).catch(e => {
    console.log(e)
})

[TradeSubscriber](https://docs.kraken.com/websockets/#message-trade)

Trade feed for a currency pair.

import Rest,{TradeSubscriber} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {
        const subscriber = new TradeSubscriber({
        token: res.result.token
    })

        //handle tradePayload messages
        subscriber.onPayload = (tradePayload) => {
            console.log(tradePayload)
        }

        // handle errorPayload message
        subscriber.onError = (errorPayload) => {
            console.log(errorPayload)
        }

        //subscriber is subscribed to endpoint
        subscriber.onSubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //subscriber is unsubscribed from endpoint
        subscriber.onUnsubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //system status received when subscribed
        subscriber.onSystemStatus = (systemStatusPayload) => {
            console.log(errorPayload)
        }


        //handle opened connection 
        subscriber.onOpen = (event) => {
            //subscribe to the implicit "trade" endpoint and listen to the BTC-USD asset pair ticks
            subscriber.subscribe({
                pair: ["BTC/USD"]
            })
        }

        //connect to the server
        subscriber.connect();
}).catch(e => {
    console.log(e)
})

[SpreadSubscriber](https://docs.kraken.com/websockets/#message-spread)

Spread feed for a currency pair.

import Rest,{SpreadSubscriber} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {
        const subscriber = new SpreadSubscriber({
        token: res.result.token
    })

        //handle spreadPayload messages
        subscriber.onPayload = (spreadPayload) => {
            console.log(spreadPayload)
        }

        // handle errorPayload message
        subscriber.onError = (errorPayload) => {
            console.log(errorPayload)
        }

        //subscriber is subscribed to endpoint
        subscriber.onSubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //subscriber is unsubscribed from endpoint
        subscriber.onUnsubscribed = (subscriptionPayload) => {
            console.log(errorPayload)
        }

        //system status received when subscribed
        subscriber.onSystemStatus = (systemStatusPayload) => {
            console.log(errorPayload)
        }

        //handle opened connection 
        subscriber.onOpen = (event) => {
            //subscribe to the implicit "spread" endpoint and listen to the BTC-USD asset pair ticks
            subscriber.subscribe({
                pair: ["BTC/USD"]
            })
        }

        //connect to the server
        subscriber.connect();
}).catch(e => {
    console.log(e)
})

WebSocket clients Examples

The role of the clients is to execute an order. The server will respond to this order with a single message. So there is no subscribe method but an execute method. Client don't have onSubscribed and onUnsubscribed handlers.

[AddOrderClient](https://docs.kraken.com/websockets/#message-addOrder)

Add new order.

import Rest,{AddOrderClient} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {
    //client instantiation with given token
    const client = new AddOrderClient({
        token: res.result.token
    })

    //on order response
    client.onPayload = (payload) => {
        console.log(payload)
    }

    //when client is connected, we can execute an order
    client.onOpen = (event) => {
        client.execute({
            ordertype: "limit",
            pair: "BTC/EUR",
            type: "buy",
            volume: "1",
            price: "1"
        })
    }

    //When client receives an error message
    client.onError = payload => {
        console.log(payload)
    }

    //system status received when subscribed
    client.onSystemStatus = payload => {
        console.log(payload)
    }

    //we connect the client to the server
    client.connect()
}).catch(e => {
    console.log(e)
})

[CancelOrderClient](https://docs.kraken.com/websockets/#message-cancelOrder)

Cancel order or list of orders.

import Rest,{CancelOrderClient} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {

    //client instantiation with given token
    const client = new CancelOrderClient({
        token: res.result.token
    })

    //on order response
    client.onPayload = (payload) => {
        console.log(payload)
    }

    //when client is connected, we can cancel specific orders
    client.onOpen = (event) => {
        client.execute({
            txid: ["transaction id","other transaction id"]
        })
    }

    //When client receives an error message
    client.onError = payload => {
        console.log(payload)
    }

    //system status received when subscribed
    client.onSystemStatus = payload => {
        console.log(payload)
    }

    //we connect the client to the server
    client.connect()
}).catch(e => {
    console.log(e)
})

[CancelAllClient](https://docs.kraken.com/websockets/#message-cancelAll)

Cancel all open orders. Includes partially-filled orders.

import Rest,{CancelAllClient} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {

    //client instantiation with given token
    const client = new CancelAllClient({
        token: res.result.token
    })

    //on order response
    client.onPayload = (payload) => {
        console.log(payload)
    }

    //when client is connected, we can cancel all orders
    client.onOpen = (event) => {
        client.execute()
    }

    //When client receives an error message
    client.onError = payload => {
        console.log(payload)
    }

    //system status received when subscribed
    client.onSystemStatus = payload => {
        console.log(payload)
    }

    //we connect the client to the server
    client.connect()
}).catch(e => {
    console.log(e)
})

[CancelAllOrdersAfterClient](https://docs.kraken.com/websockets/#message-cancelAllOrdersAfter)

Cancel all open orders after X seconds. Includes partially-filled orders.

import Rest,{CancelAllOrdersAfterClient} from 'kalamar'

//retrieve an authorization token for the WebSocket transactions
Rest.getWebSocketsToken({
    apiKey: "your api key",
    secret: " your secret key"
  }).then(res => {

    //client instantiation with given token
    const client = new CancelAllOrdersAfterClient({
        token: res.result.token
    })

    //on order response
    client.onPayload = (payload) => {
        console.log(payload)
    }

    //when client is connected, we can cancel all orders after 10 seconds
    client.onOpen = (event) => {
        client.execute({
            timeout:10
        })
    }

    //When client receives an error message
    client.onError = payload => {
        console.log(payload)
    }

    //system status received when subscribed
    client.onSystemStatus = payload => {
        console.log(payload)
    }

    //we connect the client to the server
    client.connect()
}).catch(e => {
    console.log(e)
})

About this documentation

English is not my native language. If you think parts of this documentation deserve improvement, you can submit a pull request.

1.2.0

3 years ago

1.0.2

3 years ago

1.1.0

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago