Classes
KiteConnect

Class: 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 (opens in a new tab) for the complete list of APIs, supported parameters and values, and response formats.

Example

Getting started

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

Example

API promises

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

kiteConnectApiCall()
	.then(function(v) {
	    // On success
	})
	.catch(function(e) {
		// On rejected
	});
 
try {
   const response = await kiteConnectAPiCall();
   // Do something with response
} catch(error) {
   // Handle error
}

Constructors

constructor

new KiteConnect(params): KiteConnect

Parameters

NameType
paramsKiteConnectParams

Returns

KiteConnect

Properties

EXCHANGE_BCD

Readonly EXCHANGE_BCD: "BCD"


EXCHANGE_BFO

Readonly EXCHANGE_BFO: "BFO"


EXCHANGE_BSE

Readonly EXCHANGE_BSE: "BSE"


EXCHANGE_CDS

Readonly EXCHANGE_CDS: "CDS"


EXCHANGE_MCX

Readonly EXCHANGE_MCX: "MCX"


EXCHANGE_NFO

Readonly EXCHANGE_NFO: "NFO"


EXCHANGE_NSE

Readonly EXCHANGE_NSE: "NSE"


GTT_STATUS_ACTIVE

Readonly GTT_STATUS_ACTIVE: "active"


GTT_STATUS_CANCELLED

Readonly GTT_STATUS_CANCELLED: "cancelled"


GTT_STATUS_DELETED

Readonly GTT_STATUS_DELETED: "deleted"


GTT_STATUS_DISABLED

Readonly GTT_STATUS_DISABLED: "disabled"


GTT_STATUS_EXPIRED

Readonly GTT_STATUS_EXPIRED: "expired"


GTT_STATUS_REJECTED

Readonly GTT_STATUS_REJECTED: "rejected"


GTT_STATUS_TRIGGERED

Readonly GTT_STATUS_TRIGGERED: "triggered"


GTT_TYPE_OCO

Readonly GTT_TYPE_OCO: "two-leg"


GTT_TYPE_SINGLE

Readonly GTT_TYPE_SINGLE: "single"


MARGIN_COMMODITY

Readonly MARGIN_COMMODITY: "commodity"


MARGIN_EQUITY

Readonly MARGIN_EQUITY: "equity"


ORDER_TYPE_LIMIT

Readonly ORDER_TYPE_LIMIT: "LIMIT"


ORDER_TYPE_MARKET

Readonly ORDER_TYPE_MARKET: "MARKET"


ORDER_TYPE_SL

Readonly ORDER_TYPE_SL: "SL"


ORDER_TYPE_SLM

Readonly ORDER_TYPE_SLM: "SL-M"


POSITION_TYPE_DAY

Readonly POSITION_TYPE_DAY: "day"


POSITION_TYPE_OVERNIGHT

Readonly POSITION_TYPE_OVERNIGHT: "overnight"


PRODUCT_BO

Readonly PRODUCT_BO: "BO"


PRODUCT_CNC

Readonly PRODUCT_CNC: "CNC"


PRODUCT_CO

Readonly PRODUCT_CO: "CO"


PRODUCT_MIS

Readonly PRODUCT_MIS: "MIS"


PRODUCT_NRML

Readonly PRODUCT_NRML: "NRML"


STATUS_CANCELLED

Readonly STATUS_CANCELLED: "CANCELLED"


STATUS_COMPLETE

Readonly STATUS_COMPLETE: "COMPLETE"


STATUS_REJECTED

Readonly STATUS_REJECTED: "REJECTED"


TRANSACTION_TYPE_BUY

Readonly TRANSACTION_TYPE_BUY: "BUY"


TRANSACTION_TYPE_SELL

Readonly TRANSACTION_TYPE_SELL: "SELL"


VALIDITY_DAY

Readonly VALIDITY_DAY: "DAY"


VALIDITY_IOC

Readonly VALIDITY_IOC: "IOC"


VALIDITY_TTL

Readonly VALIDITY_TTL: "TTL"


VARIETY_AMO

Readonly VARIETY_AMO: "amo"


VARIETY_AUCTION

Readonly VARIETY_AUCTION: "auction"


VARIETY_BO

Readonly VARIETY_BO: "bo"


VARIETY_CO

Readonly VARIETY_CO: "co"


VARIETY_ICEBERG

Readonly VARIETY_ICEBERG: "iceberg"


VARIETY_REGULAR

Readonly VARIETY_REGULAR: "regular"

Methods

cancelMFOrder

cancelMFOrder(order_id): Promise<{ order_id: string }>

Cancel a mutual fund order.

Parameters

NameTypeDescription
order_idstringID of the order.

Returns

Promise<{ order_id: string }>


cancelMFSIP

cancelMFSIP(sip_id): Promise<{ sip_id: string }>

Cancel a mutual fund SIP.

Parameters

NameTypeDescription
sip_idstringID of the SIP.

Returns

Promise<{ sip_id: string }>


cancelOrder

cancelOrder(variety, order_id, params?): Promise<{ order_id: string }>

Cancel an order

Parameters

NameTypeDescription
variety"amo" | "auction" | "bo" | "co" | "iceberg" | "regular"Order variety (ex. bo, co, amo)
order_idstringID of the order.
params?ObjectOrder params. regular).
params.parent_order_id?stringParent order id incase of multilegged orders.

Returns

Promise<{ order_id: string }>


convertPosition

convertPosition(params): Promise<boolean>

Modify an open position's product type.

Parameters

NameTypeDescription
paramsConvertPositionParamsparams.

Returns

Promise<boolean>


deleteGTT

deleteGTT(trigger_id): Promise<{ trigger_id: number }>

Get list of order history.

Parameters

NameTypeDescription
trigger_idstringGTT ID

Returns

Promise<{ trigger_id: number }>


exitOrder

exitOrder(variety, order_id, params?): Promise<{ order_id: string }>

Exit an order

Parameters

NameTypeDescription
variety"amo" | "auction" | "bo" | "co" | "iceberg" | "regular"Order variety (ex. bo, co, amo)
order_idstringID of the order.
params?ObjectOrder params.
params.parent_order_id?stringParent order id incase of multilegged orders.

Returns

Promise<{ order_id: string }>


generateSession

generateSession(request_token, api_secret): Promise<SessionData>

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.

Parameters

NameTypeDescription
request_tokenstringToken obtained from the GET parameters after a successful login redirect.
api_secretstringAPI secret issued with the API key.

Returns

Promise<SessionData>


getAuctionInstruments

getAuctionInstruments(): Promise<any>

Returns

Promise<any>


getGTT

getGTT(trigger_id): Promise<Trigger>

Get list of order history.

Parameters

NameTypeDescription
trigger_idstringGTT trigger ID

Returns

Promise<Trigger>


getGTTs

getGTTs(): Promise<Trigger[]>

Get GTTs list

Returns

Promise<Trigger[]>


getHistoricalData

getHistoricalData(instrument_token, interval, from_date, to_date, continuous?, oi?): Promise<{ close: number ; date: Date ; high: number ; low: number ; oi?: number ; open: number ; volume: number }>

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.

Parameters

NameTypeDescription
instrument_tokenstringInstrument identifier (retrieved from the instruments()) call.
interval"day" | "minute" | "3minute" | "5minute" | "10minute" | "15minute" | "30minute" | "60minute"candle interval (minute, day, 5 minute etc.)
from_datestring | DateFrom date (String in format of 'yyyy-mm-dd HH:MM:SS' or Date object).
to_datestring | DateTo date (String in format of 'yyyy-mm-dd HH:MM:SS' or Date object).
continuous?booleanis a bool flag to get continuous data for futures and options instruments. Defaults to false.
oi?booleanis a bool flag to include OI data for futures and options instruments. Defaults to false.

Returns

Promise<{ close: number ; date: Date ; high: number ; low: number ; oi?: number ; open: number ; volume: number }>

Example

[{
	date: '2015-02-10T00:00:00+0530',
	open: 277.5,
	high: 290.8,
	low: 275.7,
	close: 287.3,
	volume: 22589681
}, ....]

getHoldings

getHoldings(): Promise<PortfolioHolding[]>

Retrieve the list of equity holdings.

Returns

Promise<PortfolioHolding[]>


getInstruments

getInstruments(exchange?): Promise<Instrument[]>

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.

Parameters

NameTypeDescription
exchange?("NSE" | "BSE" | "NFO" | "CDS" | "BCD" | "BFO" | "MCX")[]Filter instruments based on exchange (NSE, BSE, NFO, BFO, CDS, MCX). If no segment is specified, all instruments are returned.

Returns

Promise<Instrument[]>

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' }, ...]

getLTP

getLTP(instruments): Promise<Record<string, { instrument_token: number ; last_price: number }>>

Retrieve LTP for list of instruments.

Parameters

NameTypeDescription
instrumentsstring | string[]is a single instrument or 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", ..]

Returns

Promise<Record<string, { instrument_token: number ; last_price: number }>>


getLoginURL

getLoginURL(): string

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

Returns

string


getMFHoldings

getMFHoldings(): Promise<MFHolding[]>

Get list of mutual fund holdings.

Returns

Promise<MFHolding[]>


getMFInstruments

getMFInstruments(): Promise<MFInstrument[]>

Get list of mutual fund instruments.

Returns

Promise<MFInstrument[]>


getMFOrders

getMFOrders(order_id?): Promise<MFOrder | MFOrder[]>

Get list of mutual fund orders.

Parameters

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

Returns

Promise<MFOrder | MFOrder[]>


getMFSIPS

getMFSIPS(sip_id?): Promise<MFSIP | MFSIP[]>

Get list of mutual fund SIPS. If no sip_id is specified, all active and paused SIPs are returned.

Parameters

NameTypeDescription
sip_id?stringID of the SIP (optional) whose details are to be retrieved.

Returns

Promise<MFSIP | MFSIP[]>


getMargins

getMargins(segment?): Promise<{ commodity?: UserMargin ; equity?: UserMargin }>

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

Parameters

NameTypeDescription
segment?"equity" | "commodity"trading segment (eg: equity or commodity).

Returns

Promise<{ commodity?: UserMargin ; equity?: UserMargin }>


getOHLC

getOHLC(instruments): Promise<Record<string, { instrument_token: number ; last_price: number ; ohlc: { close: number ; high: number ; low: number ; open: number } }>>

Retrieve OHLC for list of instruments.

Parameters

NameTypeDescription
instrumentsstring | string[]is a single instrument or 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", ..]

Returns

Promise<Record<string, { instrument_token: number ; last_price: number ; ohlc: { close: number ; high: number ; low: number ; open: number } }>>


getOrderHistory

getOrderHistory(order_id): Promise<Order[]>

Get list of order history.

Parameters

NameTypeDescription
order_idstringID of the order whose order details to be retrieved.

Returns

Promise<Order[]>


getOrderTrades

getOrderTrades(order_id): Promise<Trade[]>

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.

Parameters

NameTypeDescription
order_idstringID of the order whose trades are to be retrieved.

Returns

Promise<Trade[]>


getOrders

getOrders(): Promise<Order[]>

Get list of orders.

Returns

Promise<Order[]>


getPositions

getPositions(): Promise<{ day: Position[] ; net: Position[] }>

Retrieve positions.

Returns

Promise<{ day: Position[] ; net: Position[] }>


getProfile

getProfile(): Promise<UserProfile>

Get user profile details.

Returns

Promise<UserProfile>


getQuote

getQuote(instruments): Promise<Record<string, Quote>>

Retrieve quote and market depth for list of instruments.

Parameters

NameTypeDescription
instrumentsstring | string[]is a single instrument or 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", ..]

Returns

Promise<Record<string, Quote>>


getTrades

getTrades(): Promise<Trade[]>

Retrieve the list of trades executed.

Returns

Promise<Trade[]>


invalidateAccessToken

invalidateAccessToken(access_token?): Promise<boolean>

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.

Parameters

NameTypeDescription
access_token?stringToken to invalidate. Default is the active access_token.

Returns

Promise<boolean>


invalidateRefreshToken

invalidateRefreshToken(refresh_token): Promise<boolean>

Invalidate the refresh token.

Parameters

NameTypeDescription
refresh_tokenstringToken to invalidate.

Returns

Promise<boolean>


modifyGTT

modifyGTT(trigger_id, params): Promise<{ trigger_id: number }>

Modify GTT.

Parameters

NameTypeDescription
trigger_idstringGTT trigger ID.
paramsGTTParamsModify params

Returns

Promise<{ trigger_id: number }>


modifyMFSIP

modifyMFSIP(sip_id, params): Promise<{ sip_id: number }>

Modify a mutual fund SIP.

Parameters

NameTypeDescription
sip_idstringID of the SIP.
paramsObjectModify params.
params.frequency?"weekly" | "monthly" | "quarterly"Order frequency. weekly, monthly, or quarterly.
params.instalment_day?stringIf frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on.
params.instalments?numberNumber of instalments to trigger. If set to -1, instalments are triggered at fixed intervals until the SIP is cancelled
params.status?"active" | "paused"Pause or unpause an SIP (active or paused).

Returns

Promise<{ sip_id: number }>


modifyOrder

modifyOrder(variety, order_id, params): Promise<{ order_id: string }>

Modify an order

Parameters

NameTypeDescription
variety"amo" | "auction" | "bo" | "co" | "iceberg" | "regular"Order variety (ex. bo, co, amo, regular).
order_idstringID of the order.
paramsObjectOrder modify params.
params.disclosed_quantity?numberDisclosed quantity
params.order_type?"LIMIT" | "MARKET" | "SL" | "SL-M"Order type (NRML, SL, SL-M, MARKET).
params.parent_order_id?stringParent order id incase of multilegged orders.
params.price?numberOrder Price
params.quantity?numberOrder quantity
params.trigger_price?numberTrigger price
params.validity?"DAY" | "IOC" | "TTL"Order validity (DAY, IOC).

Returns

Promise<{ order_id: string }>


orderBasketMargins

orderBasketMargins(orders): Promise<{ final: Margin ; initial: Margin ; orders: Margin[] }>

Fetch basket margin for list of orders

Parameters

NameTypeDescription
ordersMarginOrder[]Margin fetch orders.

Returns

Promise<{ final: Margin ; initial: Margin ; orders: Margin[] }>

orderBasketMargins(orders, consider_positions): Promise<{ final: Margin ; initial: Margin ; orders: Margin[] }>

Parameters

NameType
ordersMarginOrder[]
consider_positionsboolean

Returns

Promise<{ final: Margin ; initial: Margin ; orders: Margin[] }>

orderBasketMargins(orders, consider_positions, mode): Promise<{ final: CompactMargin ; initial: CompactMargin ; orders: CompactMargin[] }>

Parameters

NameType
ordersMarginOrder[]
consider_positionsboolean
mode"compact"

Returns

Promise<{ final: CompactMargin ; initial: CompactMargin ; orders: CompactMargin[] }>


orderMargins

orderMargins(orders): Promise<Margin[]>

Fetch required margin for order/list of orders

Parameters

NameTypeDescription
ordersMarginOrder[]Margin fetch orders.

Returns

Promise<Margin[]>

orderMargins(orders, mode): Promise<CompactMargin[]>

Parameters

NameType
ordersMarginOrder[]
mode"compact"

Returns

Promise<CompactMargin[]>


placeGTT

placeGTT(params): Promise<{ trigger_id: number }>

Place GTT.

Parameters

NameTypeDescription
paramsGTTParamsPlace GTT params

Returns

Promise<{ trigger_id: number }>


placeMFOrder

placeMFOrder(params): Promise<{ order_id: number }>

Place a mutual fund order.

Parameters

NameTypeDescription
paramsObjectMF Order params.
params.amount?numberAmount worth of units to purchase. Not applicable on SELLs
params.quantity?numberQuantity to SELL. Not applicable on BUYs.
params.tag?stringAn optional tag to apply to an order to identify it (alphanumeric, max 20 chars)
params.tradingsymbolstringTradingsymbol (ISIN) of the fund.
params.transaction_type"BUY" | "SELL"Transaction type (BUY or SELL).

Returns

Promise<{ order_id: number }>


placeMFSIP

placeMFSIP(params): Promise<{ sip_id: number }>

Place a mutual fund SIP.

Parameters

NameTypeDescription
paramsObjectSIP params.
params.amountnumberAmount worth of units to purchase.
params.frequency"weekly" | "monthly" | "quarterly"Order frequency. weekly, monthly, or quarterly.
params.initial_amount?numberAmount worth of units to purchase before the SIP starts.
params.instalment_day?stringIf frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on.
params.instalmentsnumberNumber of instalments to trigger. If set to -1, instalments are triggered at fixed intervals until the SIP is cancelled
params.tag?stringAn optional tag to apply to an order to identify it (alphanumeric, max 20 chars)
params.tradingsymbolstringTradingsymbol (ISIN) of the fund.

Returns

Promise<{ sip_id: number }>


placeOrder

placeOrder(variety, params): Promise<{ order_id: string }>

Place an order.

Parameters

NameTypeDescription
variety"amo" | "auction" | "bo" | "co" | "iceberg" | "regular"Order variety (ex. bo, co, amo, regular).
paramsPlaceOrderParamsOrder params.

Returns

Promise<{ order_id: string }>


renewAccessToken

renewAccessToken(refresh_token, api_secret): Promise<SessionData>

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

Parameters

NameTypeDescription
refresh_tokenstringToken obtained from previous successful login.
api_secretstringAPI secret issued with the API key.

Returns

Promise<SessionData>


setAccessToken

setAccessToken(access_token): void

Set access_token received after a successful authentication.

Parameters

NameTypeDescription
access_tokenstringToken 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.

Returns

void


setSessionExpiryHook

setSessionExpiryHook(cb): void

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.

Parameters

NameTypeDescription
cbFunctionCallback

Returns

void


validatePostback

validatePostback(postback_data, api_secret): boolean

Validate postback data checksum

Parameters

NameTypeDescription
postback_dataObjectPostback data received. Must be an json object with required keys order_id, checksum and order_timestamp
postback_data.checksumstring-
postback_data.order_idstring-
postback_data.order_timestampstring-
api_secretstringApi secret of the app

Returns

boolean