Skip to Content
ClassesKiteConnect

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  for the complete list of APIs, supported parameters and values, and response formats.

Examples

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); } catch (error) { console.error('Error while fetching equity margins', error); }

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

params

KiteConnectParams

Returns

KiteConnect

Properties

EXCHANGE_BCD

readonly EXCHANGE_BCD: "BCD" = Exchange.BCD


EXCHANGE_BFO

readonly EXCHANGE_BFO: "BFO" = Exchange.BFO


EXCHANGE_BSE

readonly EXCHANGE_BSE: "BSE" = Exchange.BSE


EXCHANGE_CDS

readonly EXCHANGE_CDS: "CDS" = Exchange.CDS


EXCHANGE_MCX

readonly EXCHANGE_MCX: "MCX" = Exchange.MCX


EXCHANGE_NFO

readonly EXCHANGE_NFO: "NFO" = Exchange.NFO


EXCHANGE_NSE

readonly EXCHANGE_NSE: "NSE" = Exchange.NSE


GTT_STATUS_ACTIVE

readonly GTT_STATUS_ACTIVE: "active" = 'active'


GTT_STATUS_CANCELLED

readonly GTT_STATUS_CANCELLED: "cancelled" = 'cancelled'


GTT_STATUS_DELETED

readonly GTT_STATUS_DELETED: "deleted" = 'deleted'


GTT_STATUS_DISABLED

readonly GTT_STATUS_DISABLED: "disabled" = 'disabled'


GTT_STATUS_EXPIRED

readonly GTT_STATUS_EXPIRED: "expired" = 'expired'


GTT_STATUS_REJECTED

readonly GTT_STATUS_REJECTED: "rejected" = 'rejected'


GTT_STATUS_TRIGGERED

readonly GTT_STATUS_TRIGGERED: "triggered" = 'triggered'


GTT_TYPE_OCO

readonly GTT_TYPE_OCO: "two-leg"


GTT_TYPE_SINGLE

readonly GTT_TYPE_SINGLE: "single" = TriggerType.single


MARGIN_COMMODITY

readonly MARGIN_COMMODITY: "commodity" = 'commodity'


MARGIN_EQUITY

readonly MARGIN_EQUITY: "equity" = 'equity'


ORDER_TYPE_LIMIT

readonly ORDER_TYPE_LIMIT: "LIMIT" = OrderType.LIMIT


ORDER_TYPE_MARKET

readonly ORDER_TYPE_MARKET: "MARKET" = OrderType.MARKET


ORDER_TYPE_SL

readonly ORDER_TYPE_SL: "SL" = OrderType.SL


ORDER_TYPE_SLM

readonly ORDER_TYPE_SLM: "SL-M"


POSITION_TYPE_DAY

readonly POSITION_TYPE_DAY: "day" = 'day'


POSITION_TYPE_OVERNIGHT

readonly POSITION_TYPE_OVERNIGHT: "overnight" = 'overnight'


PRODUCT_BO

readonly PRODUCT_BO: "BO" = ProductType.BO


PRODUCT_CNC

readonly PRODUCT_CNC: "CNC" = ProductType.CNC


PRODUCT_CO

readonly PRODUCT_CO: "CO" = ProductType.CO


PRODUCT_MIS

readonly PRODUCT_MIS: "MIS" = ProductType.MIS


PRODUCT_NRML

readonly PRODUCT_NRML: "NRML" = ProductType.NRML


STATUS_CANCELLED

readonly STATUS_CANCELLED: "CANCELLED" = 'CANCELLED'


STATUS_COMPLETE

readonly STATUS_COMPLETE: "COMPLETE" = 'COMPLETE'


STATUS_REJECTED

readonly STATUS_REJECTED: "REJECTED" = 'REJECTED'


TRANSACTION_TYPE_BUY

readonly TRANSACTION_TYPE_BUY: "BUY" = TransactionType.BUY


TRANSACTION_TYPE_SELL

readonly TRANSACTION_TYPE_SELL: "SELL" = TransactionType.SELL


VALIDITY_DAY

readonly VALIDITY_DAY: "DAY" = Validity.DAY


VALIDITY_IOC

readonly VALIDITY_IOC: "IOC" = Validity.IOC


VALIDITY_TTL

readonly VALIDITY_TTL: "TTL" = Validity.TTL


VARIETY_AMO

readonly VARIETY_AMO: "amo" = Variety.amo


VARIETY_AUCTION

readonly VARIETY_AUCTION: "auction" = Variety.auction


VARIETY_BO

readonly VARIETY_BO: "bo" = Variety.bo


VARIETY_CO

readonly VARIETY_CO: "co" = Variety.co


VARIETY_ICEBERG

readonly VARIETY_ICEBERG: "iceberg" = Variety.iceberg


VARIETY_REGULAR

readonly VARIETY_REGULAR: "regular" = Variety.regular

Methods

cancelMFOrder()

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

Cancel a mutual fund order.

Parameters

order_id

string

ID of the order.

Returns

Promise<{ order_id: string; }>


cancelMFSIP()

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

Cancel a mutual fund SIP.

Parameters

sip_id

string

ID of the SIP.

Returns

Promise<{ sip_id: string; }>


cancelOrder()

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

Cancel an order

Parameters

variety

"amo" | "auction" | "bo" | "co" | "iceberg" | "regular"

Order variety (ex. bo, co, amo)

order_id

string

ID of the order.

params?

Order params. regular).

parent_order_id?

string

Parent order id incase of multilegged orders.

Returns

Promise<{ order_id: string; }>


convertPosition()

convertPosition(params): Promise<boolean>

Modify an open position’s product type.

Parameters

params

ConvertPositionParams

params.

Returns

Promise<boolean>


deleteGTT()

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

Get list of order history.

Parameters

trigger_id

string

GTT ID

Returns

Promise<{ trigger_id: number; }>


exitOrder()

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

Exit an order

Parameters

variety

"amo" | "auction" | "bo" | "co" | "iceberg" | "regular"

Order variety (ex. bo, co, amo)

order_id

string

ID of the order.

params?

Order params.

parent_order_id?

string

Parent 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

request_token

string

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

api_secret

string

API 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

trigger_id

string

GTT 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

instrument_token

string

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

interval

"day" | "minute" | "3minute" | "5minute" | "10minute" | "15minute" | "30minute" | "60minute"

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?

boolean

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

oi?

boolean

is 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

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

getLoginURL()

getLoginURL(): string

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

Returns

string


getLTP()

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

Retrieve LTP for list of instruments.

Parameters

instruments

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


getMargins()

Call Signature

getMargins(): Promise<UserMargins>

Get account balance and cash margin details for all segments.

Returns

Promise<UserMargins>

Call Signature

getMargins(segment): Promise<UserMargin>

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

Parameters
segment

"equity" | "commodity"

trading segment (eg: equity or commodity).

Returns

Promise<UserMargin>


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

order_id?

string

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.

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

sip_id?

string

ID of the SIP (optional) whose details are to be retrieved.

Returns

Promise<MFSIP | MFSIP[]>


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

instruments

string | 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

order_id

string

ID of the order whose order details to be retrieved.

Returns

Promise<Order[]>


getOrders()

getOrders(): Promise<Order[]>

Get list of orders.

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

order_id

string

ID of the order whose trades are to be retrieved.

Returns

Promise<Trade[]>


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

instruments

string | 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

access_token?

string

Token to invalidate. Default is the active access_token.

Returns

Promise<boolean>


invalidateRefreshToken()

invalidateRefreshToken(refresh_token): Promise<boolean>

Invalidate the refresh token.

Parameters

refresh_token

string

Token to invalidate.

Returns

Promise<boolean>


modifyGTT()

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

Modify GTT.

Parameters

trigger_id

string

GTT trigger ID.

params

GTTParams

Modify params

Returns

Promise<{ trigger_id: number; }>


modifyMFSIP()

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

Modify a mutual fund SIP.

Parameters

sip_id

string

ID of the SIP.

params

Modify params.

frequency?

"weekly" | "monthly" | "quarterly"

Order frequency. weekly, monthly, or quarterly.

instalment_day?

string

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

instalments?

number

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

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

variety

"amo" | "auction" | "bo" | "co" | "iceberg" | "regular"

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

order_id

string

ID of the order.

params

ModifyOrderParams

Order modify params.

Returns

Promise<{ order_id: string; }>


orderBasketMargins()

Call Signature

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

Fetch basket margin for list of orders

Parameters
orders

MarginOrder[]

Margin fetch orders.

Returns

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

Call Signature

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

Fetch basket margin for list of orders

Parameters
orders

MarginOrder[]

Margin fetch orders.

consider_positions

boolean

Boolean to consider users positions while calculating margins. Defauls to true

Returns

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

Call Signature

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

Fetch basket margin for list of orders

Parameters
orders

MarginOrder[]

Margin fetch orders.

consider_positions

boolean

Boolean to consider users positions while calculating margins. Defauls to true

mode

"compact"

(optional) Compact mode will only give the total margins

Returns

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


orderMargins()

Call Signature

orderMargins(orders): Promise<Margin[]>

Fetch required margin for order/list of orders

Parameters
orders

MarginOrder[]

Margin fetch orders.

Returns

Promise<Margin[]>

Call Signature

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

Fetch required margin for order/list of orders

Parameters
orders

MarginOrder[]

Margin fetch orders.

mode

"compact"

(optional) Compact mode will only give the total margins

Returns

Promise<CompactMargin[]>


placeGTT()

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

Place GTT.

Parameters

params

GTTParams

Place GTT params

Returns

Promise<{ trigger_id: number; }>


placeMFOrder()

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

Place a mutual fund order.

Parameters

params

MF Order params.

amount?

number

Amount worth of units to purchase. Not applicable on SELLs

quantity?

number

Quantity to SELL. Not applicable on BUYs.

tag?

string

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

tradingsymbol

string

Tradingsymbol (ISIN) of the fund.

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

params

SIP params.

amount

number

Amount worth of units to purchase.

frequency

"weekly" | "monthly" | "quarterly"

Order frequency. weekly, monthly, or quarterly.

initial_amount?

number

Amount worth of units to purchase before the SIP starts.

instalment_day?

string

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

instalments

number

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

tag?

string

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

tradingsymbol

string

Tradingsymbol (ISIN) of the fund.

Returns

Promise<{ sip_id: number; }>


placeOrder()

placeOrder(variety, params): Promise<AutosliceOrderResponse>

Place an order.

When params.autoslice is true, the backend may split the order into multiple child slices. In that case, the resolved response includes a children array, where each entry either carries an order_id or an error payload.

Parameters

variety

"amo" | "auction" | "bo" | "co" | "iceberg" | "regular"

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

params

PlaceOrderParams

Order params. Set autoslice: true to allow automatic order slicing.

Returns

Promise<AutosliceOrderResponse>


renewAccessToken()

renewAccessToken(refresh_token, api_secret): Promise<SessionData>

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

Parameters

refresh_token

string

Token obtained from previous successful login.

api_secret

string

API secret issued with the API key.

Returns

Promise<SessionData>


setAccessToken()

setAccessToken(access_token): void

Set access_token received after a successful authentication.

Parameters

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.

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

cb

Function

Callback

Returns

void


validatePostback()

validatePostback(postback_data, api_secret): boolean

Validate postback data checksum

Parameters

postback_data

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

checksum

string

order_id

string

order_timestamp

string

api_secret

string

Api secret of the app

Returns

boolean