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

kucoin-api

v1.0.20

Published

Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.

Downloads

327

Readme

Node.js & JavaScript SDK for Kucoin REST APIs & Websockets

npm version npm size npm downloads Build & Test last commit Telegram

Updated & performant JavaScript & Node.js SDK for the Kucoin REST APIs and WebSockets:

  • Complete integration with all Kucoin REST APIs and WebSockets.
  • TypeScript support (with type declarations for most API requests & responses)
  • Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
  • Browser-friendly HMAC signature mechanism.
  • Automatically supports both ESM and CJS projects.
  • Proxy support via axios integration.
  • Active community support & collaboration in telegram: Node.js Algo Traders.

Installation

npm install --save kucoin-api

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:

Documentation

Most methods accept JS objects. These can be populated using parameters specified by Kucoin's API documentation.

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

REST API

To use any of Kucoin's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the SpotClient (for spot and margin APIs) or FuturesClient (for futures APIs):

const { SpotClient, FuturesClient } = require('kucoin-api');

const client = new SpotClient({
  apiKey: 'apiKeyHere',
  apiSecret: 'apiSecretHere',
  apiPassphrase: 'apiPassPhraseHere',
});

try {
  const spotBuyResult = await client.submitOrder({
    clientOid: client.generateNewOrderID(),
    side: 'buy',
    type: 'market',
    symbol: 'BTC-USDT',
    size: '0.00001',
  });
  console.log('spotBuy ', JSON.stringify(spotBuyResult, null, 2));

  const spotSellResult = await client.submitOrder({
    clientOid: client.generateNewOrderID(),
    side: 'sell',
    type: 'market',
    symbol: 'BTC-USDT',
    size: '0.00001',
  });
  console.log('spotSellResult ', JSON.stringify(spotSellResult, null, 2));
} catch (e) {
  console.error(`Req error: `, e);
}

See SpotClient and FuturesClient for further information, or the examples for lots of usage examples.

WebSockets

All available WebSockets can be used via a shared WebsocketClient. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - see WS_KEY_MAP for a list of supported values).

Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the examples folder on GitHub.

Data events are emitted from the WebsocketClient via the update event, see example below:

const { WebsocketClient } = require('kucoin-api');

const client = new WebsocketClient();

client.on('open', (data) => {
  console.log('open: ', data?.wsKey);
});

// Data received
client.on('update', (data) => {
  console.info('data received: ', JSON.stringify(data));
});

// Something happened, attempting to reconenct
client.on('reconnect', (data) => {
  console.log('reconnect: ', data);
});

// Reconnect successful
client.on('reconnected', (data) => {
  console.log('reconnected: ', data);
});

// Connection closed. If unexpected, expect reconnect -> reconnected.
client.on('close', (data) => {
  console.error('close: ', data);
});

// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
client.on('response', (data) => {
  console.info('response: ', data);
  // throw new Error('res?');
});

client.on('exception', (data) => {
  console.error('exception: ', {
    msg: data.msg,
    errno: data.errno,
    code: data.code,
    syscall: data.syscall,
    hostname: data.hostname,
  });
});

try {
  // Optional: await a connection to be ready before subscribing (this is not necessary)
  // await client.connect('futuresPublicV1');

  /**
   * Examples for public futures websocket topics (that don't require authentication).
   *
   * These should all subscribe via the "futuresPublicV1" wsKey. For detailed usage, refer to the ws-spot-public.ts example.
   */
  client.subscribe(
    [
      '/contractMarket/tickerV2:XBTUSDM',
      '/contractMarket/ticker:XBTUSDM',
      '/contractMarket/level2:XBTUSDM',
      '/contractMarket/execution:XBTUSDM',
      '/contractMarket/level2Depth5:XBTUSDM',
      '/contractMarket/level2Depth50:XBTUSDM',
      '/contractMarket/limitCandle:XBTUSDTM_1hour',
      '/contract/instrument:XBTUSDM',
      '/contract/announcement',
      '/contractMarket/snapshot:XBTUSDM',
    ],
    'futuresPublicV1',
  );
} catch (e) {
  console.error(`Subscribe exception: `, e);
}

See WebsocketClient for further information and make sure to check the examples folder for much more detail, especially ws-spot-public.ts, which explains a lot of detail.


Customise Logging

Pass a custom logger which supports the log methods trace, info and error, or override methods from the default logger as desired.

const { WebsocketClient, DefaultLogger } = require('kucoin-api');

// E.g. customise logging for only the trace level:
const logger = {
  // Inherit existing logger methods, using an object spread
  ...DefaultLogger,
  // Define a custom trace function to override only that function
  trace: (...params) => {
    if (
      [
        'Sending ping',
        // 'Sending upstream ws message: ',
        'Received pong',
      ].includes(params[0])
    ) {
      return;
    }
    console.log('trace', JSON.stringify(params, null, 2));
  },
};

const ws = new WebsocketClient(
  {
    apiKey: 'apiKeyHere',
    apiSecret: 'apiSecretHere',
    apiPassphrase: 'apiPassPhraseHere',
  },
  logger,
);

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

Contributions & Pull Requests

Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.

Star History

Star History Chart