KiteConnect

KiteConnect

API client class. In production, you may initialise a single instance of this class per api_key. This module provides an easy to use abstraction over the HTTP APIs. The HTTP calls have been converted to methods and their JSON responses. See the Kite Connect API documentation for the complete list of APIs, supported parameters and values, and response formats.

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
    });

Constructor

new KiteConnect(params)

Source:
Parameters:
Name Type Description
params Object

Init params.

Name Type Attributes Default Description
api_key string

API key issued to you.

access_token string <optional>
null

Token obtained after the login flow in exchange for the request_token. Pre-login, this will default to null, but once you have obtained it, you should persist it in a database or session to pass to the Kite Connect class initialisation for subsequent requests.

root string <optional>
"https://api.kite.trade"

API end point root. Unless you explicitly want to send API requests to a non-default endpoint, this can be ignored.

login_uri string <optional>
"https://kite.trade/connect/login"

Kite connect login url

debug bool <optional>
false

If set to true, will console log requests and responses.

timeout number <optional>
7000

Time (milliseconds) for which the API client will wait for a request to complete before it fails.

Example

Initialize KiteConnect object

var kc = KiteConnect("my_api_key", {timeout: 10, debug: false})

Members

(static) self.EXCHANGE_BCD

Source:

(static) self.EXCHANGE_BFO

Source:

(static) self.EXCHANGE_BSE

Source:

(static) self.EXCHANGE_CDS

Source:

(static) self.EXCHANGE_MCX

Source:

(static) self.EXCHANGE_NFO

Source:

(static) self.EXCHANGE_NSE

Source:

(static) self.GTT_STATUS_ACTIVE

Source:

(static) self.GTT_STATUS_CANCELLED

Source:

(static) self.GTT_STATUS_DELETED

Source:

(static) self.GTT_STATUS_DISABLED

Source:

(static) self.GTT_STATUS_EXPIRED

Source:

(static) self.GTT_STATUS_REJECTED

Source:

(static) self.GTT_STATUS_TRIGGERED

Source:

(static) self.GTT_TYPE_OCO

Source:

(static) self.GTT_TYPE_SINGLE

Source:

(static) self.MARGIN_COMMODITY

Source:

(static) self.MARGIN_EQUITY

Source:

(static) self.ORDER_TYPE_LIMIT

Source:

(static) self.ORDER_TYPE_MARKET

Source:

(static) self.ORDER_TYPE_SL

Source:

(static) self.ORDER_TYPE_SLM

Source:

(static) self.POSITION_TYPE_DAY

Source:

(static) self.POSITION_TYPE_OVERNIGHT

Source:

(static) self.PRODUCT_BO

Source:

(static) self.PRODUCT_CNC

Source:

(static) self.PRODUCT_CO

Source:

(static) self.PRODUCT_MIS

Source:

(static) self.PRODUCT_NRML

Source:

(static) self.STATUS_CANCELLED

Source:

(static) self.STATUS_COMPLETE

Source:

(static) self.STATUS_REJECTED

Source:

(static) self.TRANSACTION_TYPE_BUY

Source:

(static) self.TRANSACTION_TYPE_SELL

Source:

(static) self.VALIDITY_DAY

Source:

(static) self.VALIDITY_IOC

Source:

(static) self.VARIETY_AMO

Source:

(static) self.VARIETY_BO

Source:

(static) self.VARIETY_CO

Source:

(static) self.VARIETY_REGULAR

Source:

Methods

cancelMFOrder(order_id)

Cancel a mutual fund order.

Source:
Parameters:
Name Type Description
order_id string

ID of the order.

cancelMFSIP(sip_id)

Cancel a mutual fund SIP.

Source:
Parameters:
Name Type Description
sip_id string

ID of the SIP.

cancelOrder(variety, order_id, paramsopt)

Cancel an order

Source:
Parameters:
Name Type Attributes Description
variety string

Order variety (ex. bo, co, amo)

order_id string

ID of the order.

params Object <optional>

Order params. regular).

Name Type Attributes Description
parent_order_id string <optional>

Parent order id incase of multilegged orders.

convertPosition(params)

Modify an open position's product type.

Source:
Parameters:
Name Type Description
params Object

params.

Name Type Description
exchange string

Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX).

tradingsymbol string

Tradingsymbol of the instrument (ex. RELIANCE, INFY).

transaction_type string

Transaction type (BUY or SELL).

position_type string

Position type (overnight, day).

quantity string

Position quantity

old_product string

Current product code (NRML, MIS, CNC).

new_product string

New Product code (NRML, MIS, CNC).

deleteGTT(trigger_id)

Get list of order history.

Source:
Parameters:
Name Type Description
trigger_id string

GTT ID

exitOrder(variety, order_id, paramsopt)

Exit an order

Source:
Parameters:
Name Type Attributes Description
variety string

Order variety (ex. bo, co, amo)

order_id string

ID of the order.

params Object <optional>

Order params.

Name Type Attributes Description
parent_order_id string <optional>

Parent order id incase of multilegged orders.

generateSession(request_token, api_secret)

Do the token exchange with the request_token obtained after the login flow, and retrieve the access_token required for all subsequent requests. The response contains not just the access_token, but metadata for the user who has authenticated.

Source:
Parameters:
Name Type Description
request_token string

Token obtained from the GET parameters after a successful login redirect.

api_secret string

API secret issued with the API key.

getGTT(trigger_id)

Get list of order history.

Source:
Parameters:
Name Type Description
trigger_id string

GTT trigger ID

getGTTs()

Get GTTs list

Source:

getHistoricalData(instrument_token, interval, from_date, to_date, continuousopt)

Retrieve historical data (candles) for an instrument. Although the actual response JSON from the API does not have field names such has 'open', 'high' etc., this functin call structures the data into an array of objects with field names. For example:

[{
    date: '2015-02-10T00:00:00+0530',
    open: 277.5,
    high: 290.8,
    low: 275.7,
    close: 287.3,
    volume: 22589681
}, ....]
Source:
Parameters:
Name Type Attributes Default Description
instrument_token string

Instrument identifier (retrieved from the instruments()) call.

interval string

candle interval (minute, day, 5 minute etc.)

from_date string | Date

From date (String in format of 'yyyy-mm-dd HH:MM:SS' or Date object).

to_date string | Date

To date (String in format of 'yyyy-mm-dd HH:MM:SS' or Date object).

continuous bool <optional>
false

is a bool flag to get continuous data for futures and options instruments. Defaults to false.

getHoldings()

Retrieve the list of equity holdings.

Source:

getInstruments(segmentopt)

Retrieve the list of market instruments available to trade. Note that the results could be large, several hundred KBs in size, with tens of thousands of entries in the list. Response is array for objects. For example

    {
        instrument_token: '131098372',
        exchange_token: '512103',
        tradingsymbol: 'NIDHGRN',
        name: 'NIDHI GRANITES',
        last_price: '0.0',
        expiry: '',
        strike: '0.0',
        tick_size: '0.05',
        lot_size: '1',
        instrument_type: 'EQ',
        segment: 'BSE',
        exchange: 'BSE' }, ...]
Source:
Parameters:
Name Type Attributes Description
segment Array <optional>

Filter instruments based on exchange (NSE, BSE, NFO, BFO, CDS, MCX). If no segment is specified, all instruments are returned.

getLoginURL()

Get the remote login url to which a user should be redirected to initiate the login flow.

Source:

getLTP(instruments)

Retrieve LTP for list of instruments.

Source:
Parameters:
Name Type Description
instruments Array

is a list of instruments, Instrument are in the format of exchange:tradingsymbol. For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..]

getMargins(segmentopt)

Get account balance and cash margin details for a particular segment.

Source:
Parameters:
Name Type Attributes Description
segment string <optional>

trading segment (eg: equity or commodity).

getMFHoldings()

Get list of mutual fund holdings.

Source:

getMFInstruments()

Get list of mutual fund instruments.

Source:

getMFOrders(order_idopt)

Get list of mutual fund orders.

Source:
Parameters:
Name Type Attributes Description
order_id string <optional>

ID of the order (optional) whose order details are to be retrieved. If no order_id is specified, all orders for the day are returned.

getMFSIPS(sip_id)

Get list of mutual fund SIPS.

Source:
Parameters:
Name Type Description
sip_id string

ID of the SIP.

getOHLC(instruments)

Retrieve OHLC for list of instruments.

Source:
Parameters:
Name Type Description
instruments Array

is a list of instruments, Instrument are in the format of exchange:tradingsymbol. For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..]

getOrderHistory(order_id)

Get list of order history.

Source:
Parameters:
Name Type Description
order_id string

ID of the order whose order details to be retrieved.

getOrders()

Get list of orders.

Source:

getOrderTrades(order_id)

Retrieve the list of trades a particular order). An order can be executed in tranches based on market conditions. These trades are individually recorded under an order.

Source:
Parameters:
Name Type Description
order_id string

ID of the order whose trades are to be retrieved.

getPositions()

Retrieve positions.

Source:

getProfile()

Get user profile details.

Source:

getQuote(instruments)

Retrieve quote and market depth for list of instruments.

Source:
Parameters:
Name Type Description
instruments Array

is a list of instruments, Instrument are in the format of exchange:tradingsymbol. For example NSE:INFY and for list of instruments ["NSE:RELIANCE", "NSE:SBIN", ..]

getTrades()

Retrieve the list of trades executed.

Source:

getTriggerRange(exchange, tradingsymbol, transaction_type)

Retrieve the buy/sell trigger range for Cover Orders.

Source:
Parameters:
Name Type Description
exchange string

Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX).

tradingsymbol string

Tranding symbol of the instrument (ex. RELIANCE, INFY).

transaction_type string

Transaction type (BUY or SELL).

invalidateAccessToken(access_tokenopt)

Kill the session by invalidating the access token. If access_token is passed then it will be set as current access token and get in validated.

Source:
Parameters:
Name Type Attributes Description
access_token string <optional>

Token to invalidate. Default is the active access_token.

invalidateRefreshToken(refresh_token)

Invalidate the refresh token.

Source:
Parameters:
Name Type Description
refresh_token string

Token to invalidate.

modifyGTT(trigger_id, params)

Place GTT.

Source:
Parameters:
Name Type Description
trigger_id string

GTT trigger ID.

params Object

Modify params

Name Type Description
trigger_type string

GTT type, its either self.GTT_TYPE_OCO or self.GTT_TYPE_SINGLE.

tradingsymbol string

Tradingsymbol of the instrument (ex. RELIANCE, INFY).

exchange string

Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX).

trigger_values Array.<number>

List of trigger values, number of items depends on trigger type.

last_price number

Price at which trigger is created. This is usually the last price of the instrument.

orders Array.<Object>

List of orders.

Name Type Description
transaction_type string

Transaction type (BUY or SELL).

quantity number

Order quantity

product string

Product code (NRML, MIS, CNC).

order_type string

Order type (NRML, SL, SL-M, MARKET).

price number

Order price.

modifyMFSIP(sip_id, params)

Modify a mutual fund SIP.

Source:
Parameters:
Name Type Description
sip_id string

ID of the SIP.

params string

Order params.

Name Type Attributes Description
instalments string <optional>

Number of instalments to trigger. If set to -1, instalments are triggered at fixed intervals until the SIP is cancelled

frequency string <optional>

Order frequency. weekly, monthly, or quarterly.

instalment_day string <optional>

If frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on.

status string <optional>

Pause or unpause an SIP (active or paused).

modifyOrder(variety, order_id, params)

Modify an order

Source:
Parameters:
Name Type Description
variety string

Order variety (ex. bo, co, amo, regular).

order_id string

ID of the order.

params Object

Order modify params.

Name Type Attributes Description
quantity number <optional>

Order quantity

price number <optional>

Order Price

order_type string <optional>

Order type (NRML, SL, SL-M, MARKET).

validity string <optional>

Order validity (DAY, IOC).

disclosed_quantity number <optional>

Disclosed quantity

trigger_price number <optional>

Trigger price

parent_order_id string <optional>

Parent order id incase of multilegged orders.

orderBasketMargins(orders, consider_positions, mode)

Fetch basket margin for list of orders

Source:
Parameters:
Name Type Description
orders Array.<Object>

Margin fetch orders.

Name Type Description
exchange string

Name of the exchange(eg. NSE, BSE, NFO, CDS, MCX)

tradingsymbol string

Trading symbol of the instrument

transaction_type string

eg. BUY, SELL

variety string

Order variety (regular, amo, bo, co etc.)

product string

Margin product to use for the order

order_type string

Order type (MARKET, LIMIT etc.)

quantity number

Quantity of the order

price number

Price at which the order is going to be placed (LIMIT orders)

trigger_price number

Trigger price (for SL, SL-M, CO orders)

consider_positions string

Boolean to consider users positions while calculating margins

mode string

(optional) Compact mode will only give the total margins

orderMargins(orders, mode)

Fetch required margin for order/list of orders

Source:
Parameters:
Name Type Description
orders Array.<Object>

Margin fetch orders.

Name Type Description
exchange string

Name of the exchange(eg. NSE, BSE, NFO, CDS, MCX)

tradingsymbol string

Trading symbol of the instrument

transaction_type string

eg. BUY, SELL

variety string

Order variety (regular, amo, bo, co etc.)

product string

Margin product to use for the order

order_type string

Order type (MARKET, LIMIT etc.)

quantity number

Quantity of the order

price number

Price at which the order is going to be placed (LIMIT orders)

trigger_price number

Trigger price (for SL, SL-M, CO orders)

mode string

(optional) Compact mode will only give the total margins

placeGTT()

Place GTT.

Source:
Parameters:
Name Type Description
params.trigger_type string

GTT type, its either self.GTT_TYPE_OCO or self.GTT_TYPE_SINGLE.

params.tradingsymbol string

Tradingsymbol of the instrument (ex. RELIANCE, INFY).

params.exchange string

Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX).

params.trigger_values Array.<number>

List of trigger values, number of items depends on trigger type.

params.last_price number

Price at which trigger is created. This is usually the last price of the instrument.

params.orders Array.<Object>

List of orders.

Name Type Description
transaction_type string

Transaction type (BUY or SELL).

quantity number

Order quantity

product string

Product code (NRML, MIS, CNC).

order_type string

Order type (NRML, SL, SL-M, MARKET).

price number

Order price.

placeMFOrder(params)

Place a mutual fund order.

Source:
Parameters:
Name Type Description
params string

Order params.

Name Type Attributes Description
tradingsymbol string

Tradingsymbol (ISIN) of the fund.

transaction_type string

Transaction type (BUY or SELL).

quantity string <optional>

Quantity to SELL. Not applicable on BUYs.

amount string <optional>

Amount worth of units to purchase. Not applicable on SELLs

tag string <optional>

An optional tag to apply to an order to identify it (alphanumeric, max 20 chars)

placeMFSIP(params)

Place a mutual fund SIP.

Source:
Parameters:
Name Type Description
params string

Order params.

Name Type Attributes Description
tradingsymbol string

Tradingsymbol (ISIN) of the fund.

amount string

Amount worth of units to purchase.

instalments string

Number of instalments to trigger. If set to -1, instalments are triggered at fixed intervals until the SIP is cancelled

frequency string

Order frequency. weekly, monthly, or quarterly.

initial_amount string <optional>

Amount worth of units to purchase before the SIP starts.

instalment_day string <optional>

If frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on.

tag string <optional>

An optional tag to apply to an order to identify it (alphanumeric, max 20 chars)

placeOrder(variety, params)

Place an order.

Source:
Parameters:
Name Type Description
variety string

Order variety (ex. bo, co, amo, regular).

params string

Order params.

Name Type Attributes Description
exchange string

Exchange in which instrument is listed (NSE, BSE, NFO, BFO, CDS, MCX).

tradingsymbol string

Tradingsymbol of the instrument (ex. RELIANCE, INFY).

transaction_type string

Transaction type (BUY or SELL).

quantity number

Order quantity

product string

Product code (NRML, MIS, CNC).

order_type string

Order type (NRML, SL, SL-M, MARKET).

validity string <optional>

Order validity (DAY, IOC).

price number <optional>

Order Price

disclosed_quantity number <optional>

Disclosed quantity

trigger_price number <optional>

Trigger price

squareoff number <optional>

Square off value (only for bracket orders)

stoploss number <optional>

Stoploss value (only for bracket orders)

trailing_stoploss number <optional>

Trailing stoploss value (only for bracket orders)

tag string <optional>

An optional tag to apply to an order to identify it (alphanumeric, max 20 chars)

renewAccessToken(refresh_token, api_secret)

Renew access token by active refresh token. Renewed access token is implicitly set.

Source:
Parameters:
Name Type Description
refresh_token string

Token obtained from previous successful login.

api_secret string

API secret issued with the API key.

setAccessToken(access_token)

Set access_token received after a successful authentication.

Source:
Parameters:
Name Type Description
access_token string

Token obtained in exchange for request_token. Once you have obtained access_token, you should persist it in a database or session to pass to the Kite Connect class initialisation for subsequent requests.

setSessionExpiryHook(cb)

Set a callback hook for session (TokenException -- timeout, expiry etc.) errors. access_token (login session) can become invalid for a number of reasons, but it doesn't make sense for the client to try and catch it during every API call.

A callback method that handles session errors can be set here and when the client encounters a token error at any point, it'll be called.

This callback, for instance, can log the user out of the UI, clear session cookies, or initiate a fresh login.

Source:
Parameters:
Name Type Description
cb function

Callback

validatePostback(postback_data, api_secret) → {bool}

Validate postback data checksum

Source:
Parameters:
Name Type Description
postback_data object

Postback data received. Must be an json object with required keys order_id, checksum and order_timestamp

api_secret string

Api secret of the app

Throws:

Throws an error if the @postback_data or @api_secret is invalid

Returns:
Type:
bool

Return true if checksum matches else false