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

kiteconnect-ts

v1.1.0

Published

Unofficial library for the Kite Connect trading APIs, written in TypeScript.

Downloads

190

Readme

kiteconnect-ts

Unofficial library for the Kite Connect trading APIs, written in TypeScript.

All classes and APIs are one-to-one with Zerodha's official kiteconnectjs library, so your existing code should work as is but with the added benefit of types! You will notice TypeScript's type safety as soon as you initialize a new KiteConnect or KiteTicker class. A bunch of extra types/interfaces are also available and can be used where the type cannot be inferred by TypeScript. See the docs section for more information.

If you notice a bug, please open an issue or consider contributing.

Documentation

Docs are auto-generated from TsDoc comments using TypeDoc, typedoc-plugin-markdown and Nextra.

Browse the full docs here or go to a specific part:

kiteconnect-ts

Other

Requirements

  • Node.js v14+

Please note: Browser environments are not supported. See Browser Support for more details.

Installation

npm

npm install kiteconnect-ts

yarn

yarn add kiteconnect-ts

pnpm

pnpm add kiteconnect-ts

KiteConnect

import { KiteConnect } from 'kiteconnect-ts';

const kc = new KiteConnect({
  api_key: 'YOUR_API_KEY',
});

// Get access token
try {
  const { access_token } = await kc.generateSession(
    'request_token',
    'YOUR_API_SECRET'
  );
  console.log('Access token:', access_token);
} catch (error) {
  console.error('Error while generating session', error);
  process.exit(1);
}

// Get equity margins
try {
  const margins = await kc.getMargins('equity');
  console.log('Equity margins', margins.equity);
} catch (error) {
  console.error('Error while fetching equity margins', error);
}

KiteTicker

import { KiteTicker, Tick } from 'kiteconnect-ts';

const ticker: KiteTicker = new KiteTicker({
  api_key: 'YOUR_API_KEY',
  access_token: 'YOUR_ACCESS_TOKEN',
});

ticker.on('ticks', (ticks: Tick[]) => {
  console.log('Ticks', ticks);
});

ticker.on('connect', () => {
  const items = [738561];
  ticker.subscribe(items);
});

ticker.connect();

Using provided enums

This library does not export Typescript enums, but rather JavaScript const objects. This was a design decision taken consciously to allow using the value from the object as well as a string literal, which has a better dx in my opinion. Constants are also present in the classes as readonly members, mainly for backwards compatibility with kiteconnectjs. So in total there are 3 ways you can these, pick one that works for you!

Option 1: As a string

All params which accept specific values provide type validation and autocomplete. So a simple string literal works as follows:

import { KiteConnect } from 'kiteconnect-ts';
import env from './env.json';

const kc = new KiteConnect({
  api_key: env.API_KEY,
});

const instruments = await kc.getInstruments(['NSE']);

Option 2: As an enum

You could also import the enum and use as follows:

import { Exchange, KiteConnect } from 'kiteconnect-ts';
import env from './env.json';

const kc = new KiteConnect({
  api_key: env.API_KEY,
});

const instruments = await kc.getInstruments([Exchange.NSE]);

Option 3: As a class member

This is mainly for backwards compatibility if you are migrating kiteconnectjs code to kiteconnect-ts.

import { KiteConnect } from 'kiteconnect-ts';
import env from './env.json';

const kc = new KiteConnect({
  api_key: env.API_KEY,
});

const instruments = await kc.getInstruments([kc.EXCHANGE_NSE]);

Browser Support

Unfortunately this library does not work on the browser, so you cannot use it on your Angular, React, Vue, etc front-ends. However, if you use a meta/full-stack framework (Next.js, Nuxt, etc) with SSR, you can definitely install and use it on the server side.

This is not a limitation of this library per say, rather a limitation from Zerodha as they do not want you to use Kite APIs directly from the browser. This is also evident once you try to access any Kite API endpoint from your browser and you are greeted with a CORS error.

However, you can connect to Kite Websocket from your browser using WebSocket. You'd need to write your own parser or adapt the code from here.

Here's an extremely simple full tick parser that just gets the token, firstBid and firstAsk.

// Tick structure reference: https://kite.trade/docs/connect/v3/websocket/#message-structure
const parseBinary = (dataView: DataView) => {
  const numberOfPackets = dataView.getInt16(0);
  let index = 4;
  const ticks: { token: number; firstBid: number; firstAsk: number }[] = [];

  for (let i = 0; i < numberOfPackets; i++) {
    const size = dataView.getInt16(index - 2);

    // Parse whatever you need
    ticks.push({
      token: dataView.getInt32(index),
      firstBid: dataView.getInt32(index + 68) / 100,
      firstAsk: dataView.getInt32(index + 128) / 100,
    });

    index = index + 2 + size;
  }

  return ticks;
};

const API_KEY = 'INSERT_API_KEY_HERE';
const ACCESS_TOKEN = 'INSERT_ACCESS_TOKEN_HERE';

const ws = new WebSocket(
  `wss://ws.kite.trade?api_key=${API_KEY}&access_token=${ACCESS_TOKEN}`
);

ws.onopen = (_event) => {
  console.log('Connected to Zerodha Kite Socket!');

  const setModeMessage = { a: 'mode', v: ['full', [61512711]] };
  ws.send(JSON.stringify(setModeMessage));
};

ws.onerror = (error) => {
  console.log('Some error occurred', error);
};

ws.onmessage = async (message) => {
  if (message.data instanceof Blob && message.data.size > 2) {
    const arrayBuffer = await message.data.arrayBuffer();
    const dataView = new DataView(arrayBuffer);
    const ticks = parseBinary(dataView);
    console.log(ticks);
  }
};

Todos

  • Add more examples
  • Add tests

Changelog

Check the changelog.

Contributing

See the Contribution Guide.

License

MIT © Anurag Roy

Credits

Code was adapted from kiteconnectjs, MIT License, Copyright 2018 Zerodha Technology