Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

kiteconnect-public

zerodhatech17MIT4.0.1

The official JS client library for the Kite Connect trading APIs

kiteconnect, kite, zerodha, rainmatter, trading, api, stock, market

readme

The Kite Connect API Javascript client - v4

The official Javascript node client for communicating with the Kite Connect API.

Kite Connect is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (WebSockets), and more, with the simple HTTP API collection.

Zerodha Technology (c) 2018. Licensed under the MIT License.

Documentation

Requirements

  • NodeJS v8.0.0+

Installation

Install via npm

npm install kiteconnect@latest

Or via Yarn

yarn add kiteconnect

Breaking changes - v4

v4 is a breaking major release with multiple internal modification to improve user experience.

Below are the breaking changes:

  • Upgrade deps and set minimum nodejs version to 8.0.0+
  • Return promise instead of throwing error on generateSession and renewAccessToken
  • Handle gtt payload validation and throw proper error
  • Change ticker response attributes naming as per kite connect doc

Getting started with API

var KiteConnect = require("kiteconnect").KiteConnect;

var kc = new KiteConnect({
  api_key: "your_api_key",
});

kc.generateSession("request_token", "api_secret")
  .then(function (response) {
    init();
  })
  .catch(function (err) {
    console.log(err);
  });

function init() {
  // Fetch equity margins.
  // You can have other api calls here.
  kc.getMargins()
    .then(function (response) {
      // You got user's margin details.
    })
    .catch(function (err) {
      // Something went wrong.
    });
}

API promises

All API calls returns a promise which you can use to call methods like .then(...) and .catch(...).

kiteConnectApiCall
  .then(function (v) {
    // On success
  })
  .catch(function (e) {
    // On rejected
  });

Getting started WebSocket client

var KiteTicker = require("kiteconnect").KiteTicker;
var ticker = new KiteTicker({
  api_key: "api_key",
  access_token: "access_token",
});

ticker.connect();
ticker.on("ticks", onTicks);
ticker.on("connect", subscribe);

function onTicks(ticks) {
  console.log("Ticks", ticks);
}

function subscribe() {
  var items = [738561];
  ticker.subscribe(items);
  ticker.setMode(ticker.modeFull, items);
}

Auto re-connect WebSocket client

Optionally you can enable client side auto re-connection to automatically reconnect if the connection is dropped. It is very useful at times when client side network is unreliable and patchy.

All you need to do is enable auto re-connection with preferred interval and time. For example

// Enable auto reconnect with 5 second interval and retry for maximum of 20 times.
ticker.autoReconnect(true, 20, 5);

// You can also set re-connection times to -1 for infinite re-connections
ticker.autoReconnect(true, -1, 5);
  • Event reconnecting is called when auto re-connection is triggered and event callback carries two additional params reconnection interval set and current re-connection count.

  • Event noreconnect is called when number of auto re-connections exceeds the maximum re-connection count set. For example if maximum re-connection count is set as 20 then after 20th re-connection this event will be triggered. Also note that the current process is exited when this event is triggered.

  • Event connect will be triggered again when re-connection succeeds.

Here is an example demonstrating auto reconnection.

var KiteTicker = require("kiteconnect").KiteTicker;
var ticker = new KiteTicker({
  api_key: "api_key",
  access_token: "access_token",
});

// set autoreconnect with 10 maximum reconnections and 5 second interval
ticker.autoReconnect(true, 10, 5);
ticker.connect();
ticker.on("ticks", onTicks);
ticker.on("connect", subscribe);

ticker.on("noreconnect", function () {
  console.log("noreconnect");
});

ticker.on("reconnecting", function (reconnect_interval, reconnections) {
  console.log(
    "Reconnecting: attempt - ",
    reconnections,
    " innterval - ",
    reconnect_interval
  );
});

function onTicks(ticks) {
  console.log("Ticks", ticks);
}

function subscribe() {
  var items = [738561];
  ticker.subscribe(items);
  ticker.setMode(ticker.modeFull, items);
}

Run unit tests

npm run test

Changelog

Check CHANGELOG.md

A typical web application

In a typical web application where a new instance of views, controllers etc. are created per incoming HTTP request, you will need to initialise a new instance of Kite client per request as well. This is because each individual instance represents a single user that's authenticated, unlike an admin API where you may use one instance to manage many users.

Hence, in your web application, typically:

  • You will initialise an instance of the Kite client
  • Redirect the user to the login_url()
  • At the redirect url endpoint, obtain the request_token from the query parameters
  • Initialise a new instance of Kite client, use request_access_token() to obtain the access_token along with authenticated user data
  • Store this response in a session and use the stored access_token and initialise instances of Kite client for subsequent API calls.

changelog

Kite v4

Breaking changes

  • Upgrade deps and set minimum nodejs version to 8.0.0+
  • Return promise instead of throwing error on generateSession and renewAccessToken
  • Handle gtt payload validation and throw proper error
  • Change ticker response attributes naming as per kite connect doc

New features

  • Order margin call : orderMargins
  • Basket order margin call : orderBasketMargins
  • Add OI param to getHistoricalData
  • Add global constant for postion types POSITION_TYPE_DAY, POSITION_TYPE_OVERNIGHT and EXCHANGE_BCD

Fixes

  • Remove order_id param from complete tradebook fetch getTrades
  • Fix cancelMF order_id param struct
  • Handle price conversion for BCD segment in ticker
  • Remove un-used headers param for parseHistorical
  • Update comment block for getQuote, getOHLC, getLTP, placeOrder and placeMFOrder

Kite v3

New features

  • method: getProfile
  • method: getOHLC
  • method: getLTP
  • method: getInstrumentsMargins
  • Added MF API calls
  • method: getMFOrders
  • method: getMFHoldings
  • method: placeMFOrder
  • method: cancelMFOrder
  • method: getMFSIPS
  • method: placeMFSIP
  • method: modifyMFSIP
  • method: cancelMFSIP
  • method: getMFInstruments
  • method: exitOrder
  • method: renewAccessToken
  • method: invalidateRefreshToken
  • constants for products, order type, transaction type, variety, validity, exchanges and margin segments

API method name changes

v2 v3
requestAccessToken generateSession
invalidateToken invalidateAccessToken
setSessionHook setSessionExpiryHook
loginUrl getLoginURL
margins getMargins
orderPlace placeOrder
orderModify modifyOrder
orderCancel cancelOrder
orders getOrders
orders(order_id) getOrderHistory
trades getTrades
trades(order_id) getOrderTrades
holdings getHoldings
positions getPositions
productModify convertPosition
instruments getInstruments
historical getHistoricalData
triggerRange getTriggerRange

Params and other changes

  • KiteConnect takes all the params as object including api_key
  • convertPosition method takes all the params as object
  • All success response returns only data field in response instead with envelope
  • All error thrown are in the format of {"message": "Unknown error", "error_type": "GeneralException", "data": null}
  • Changes in generateSession response structure
  • Changes in getPositions response structure
  • Changes in getQuote response structure
  • Changes in placeOrder params
  • Changes in getHistoricalData params
  • All datetime string fields has been converted to Date object.
    • getOrders, getOrderHistory, getTrades, getOrderTrades, getMFOrders responses fields order_timestamp, exchange_timestamp, fill_timestamp
    • getMFSIPS fields created, last_instalment
    • generateSession field login_time
    • getQuote fields timestamp, last_trade_time
    • getInstruments field expiry
    • getMFInstruments field last_price_date

KiteTicker changes

  • KiteTicker receives param access_token instead of public_token
  • New params addedd to KiteTicker initializer
    • reconnect - Toggle auto reconnect on/off
    • max_retry - Max retry count for auto reconnect
    • max_delay - Max delay between subsequent retries
    • Auto reconnect is enabled by default
  • Renamed callback reconnecting to reconnect
  • Added new callbacks
    • error - when socket connection is closed with error. Error is received as a first param
    • close - when socket connection is closed cleanly
    • order_update - When order update (postback) is received for the connected user (Data object is received as first argument)