npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

kalamar

v1.2.0

Published

HTTP REST methods and WebSocket subscribers for the Kraken.com cryptocurrency platform API

Downloads

10

Readme

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

WebSocket API documentation

Package Documentation

A package documentation with every methods, classes, interfaces and types has been generated thanks to Typedoc.

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.

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.

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

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

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

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

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

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

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

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

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 and no-cors issues for in-browser implementation)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.