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
Name | Type |
---|---|
params | KiteConnectParams |
Returns
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
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
variety | "amo" | "auction" | "bo" | "co" | "iceberg" | "regular" | Order variety (ex. bo, co, amo) |
order_id | string | ID of the order. |
params? | Object | Order params. regular). |
params.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
Name | Type | Description |
---|---|---|
params | ConvertPositionParams | params. |
Returns
Promise
<boolean
>
deleteGTT
deleteGTT(trigger_id
): Promise
<{ trigger_id
: number
}>
Get list of order history.
Parameters
Name | Type | Description |
---|---|---|
trigger_id | string | GTT ID |
Returns
Promise
<{ trigger_id
: number
}>
exitOrder
exitOrder(variety
, order_id
, params?
): Promise
<{ order_id
: string
}>
Exit an order
Parameters
Name | Type | Description |
---|---|---|
variety | "amo" | "auction" | "bo" | "co" | "iceberg" | "regular" | Order variety (ex. bo, co, amo) |
order_id | string | ID of the order. |
params? | Object | Order params. |
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
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. |
Returns
Promise
<SessionData
>
getAuctionInstruments
getAuctionInstruments(): Promise
<any
>
Returns
Promise
<any
>
getGTT
getGTT(trigger_id
): Promise
<Trigger
>
Get list of order history.
Parameters
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
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
}>>
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
Name | Type | Description |
---|---|---|
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
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
Name | Type | Description |
---|---|---|
sip_id? | string | ID of the SIP (optional) whose details are to be retrieved. |
Returns
getMargins
getMargins(segment?
): Promise
<{ commodity?
: UserMargin
; equity?
: UserMargin
}>
Get account balance and cash margin details for a particular segment.
Parameters
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
order_id | string | ID 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
Name | Type | Description |
---|---|---|
order_id | string | ID 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
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
refresh_token | string | Token to invalidate. |
Returns
Promise
<boolean
>
modifyGTT
modifyGTT(trigger_id
, params
): Promise
<{ trigger_id
: number
}>
Modify GTT.
Parameters
Name | Type | Description |
---|---|---|
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
Name | Type | Description |
---|---|---|
sip_id | string | ID of the SIP. |
params | Object | Modify params. |
params.frequency? | "weekly" | "monthly" | "quarterly" | Order frequency. weekly, monthly, or quarterly. |
params.instalment_day? | string | If frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on. |
params.instalments? | number | Number 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
Name | Type | Description |
---|---|---|
variety | "amo" | "auction" | "bo" | "co" | "iceberg" | "regular" | Order variety (ex. bo, co, amo, regular). |
order_id | string | ID of the order. |
params | Object | Order modify params. |
params.disclosed_quantity? | number | Disclosed quantity |
params.order_type? | "LIMIT" | "MARKET" | "SL" | "SL-M" | Order type (NRML, SL, SL-M, MARKET). |
params.parent_order_id? | string | Parent order id incase of multilegged orders. |
params.price? | number | Order Price |
params.quantity? | number | Order quantity |
params.trigger_price? | number | Trigger 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
Name | Type | Description |
---|---|---|
orders | MarginOrder [] | Margin fetch orders. |
Returns
Promise
<{ final
: Margin
; initial
: Margin
; orders
: Margin
[] }>
orderBasketMargins(orders
, consider_positions
): Promise
<{ final
: Margin
; initial
: Margin
; orders
: Margin
[] }>
Parameters
Name | Type |
---|---|
orders | MarginOrder [] |
consider_positions | boolean |
Returns
Promise
<{ final
: Margin
; initial
: Margin
; orders
: Margin
[] }>
orderBasketMargins(orders
, consider_positions
, mode
): Promise
<{ final
: CompactMargin
; initial
: CompactMargin
; orders
: CompactMargin
[] }>
Parameters
Name | Type |
---|---|
orders | MarginOrder [] |
consider_positions | boolean |
mode | "compact" |
Returns
Promise
<{ final
: CompactMargin
; initial
: CompactMargin
; orders
: CompactMargin
[] }>
orderMargins
orderMargins(orders
): Promise
<Margin
[]>
Fetch required margin for order/list of orders
Parameters
Name | Type | Description |
---|---|---|
orders | MarginOrder [] | Margin fetch orders. |
Returns
Promise
<Margin
[]>
orderMargins(orders
, mode
): Promise
<CompactMargin
[]>
Parameters
Name | Type |
---|---|
orders | MarginOrder [] |
mode | "compact" |
Returns
Promise
<CompactMargin
[]>
placeGTT
placeGTT(params
): Promise
<{ trigger_id
: number
}>
Place GTT.
Parameters
Name | Type | Description |
---|---|---|
params | GTTParams | Place GTT params |
Returns
Promise
<{ trigger_id
: number
}>
placeMFOrder
placeMFOrder(params
): Promise
<{ order_id
: number
}>
Place a mutual fund order.
Parameters
Name | Type | Description |
---|---|---|
params | Object | MF Order params. |
params.amount? | number | Amount worth of units to purchase. Not applicable on SELLs |
params.quantity? | number | Quantity to SELL. Not applicable on BUYs. |
params.tag? | string | An optional tag to apply to an order to identify it (alphanumeric, max 20 chars) |
params.tradingsymbol | string | Tradingsymbol (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
Name | Type | Description |
---|---|---|
params | Object | SIP params. |
params.amount | number | Amount worth of units to purchase. |
params.frequency | "weekly" | "monthly" | "quarterly" | Order frequency. weekly, monthly, or quarterly. |
params.initial_amount? | number | Amount worth of units to purchase before the SIP starts. |
params.instalment_day? | string | If frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on. |
params.instalments | number | Number of instalments to trigger. If set to -1, instalments are triggered at fixed intervals until the SIP is cancelled |
params.tag? | string | An optional tag to apply to an order to identify it (alphanumeric, max 20 chars) |
params.tradingsymbol | string | Tradingsymbol (ISIN) of the fund. |
Returns
Promise
<{ sip_id
: number
}>
placeOrder
placeOrder(variety
, params
): Promise
<{ order_id
: string
}>
Place an order.
Parameters
Name | Type | Description |
---|---|---|
variety | "amo" | "auction" | "bo" | "co" | "iceberg" | "regular" | Order variety (ex. bo, co, amo, regular). |
params | PlaceOrderParams | Order 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
Name | Type | Description |
---|---|---|
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
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. |
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
Name | Type | Description |
---|---|---|
cb | Function | Callback |
Returns
void
validatePostback
validatePostback(postback_data
, api_secret
): boolean
Validate postback data checksum
Parameters
Name | Type | Description |
---|---|---|
postback_data | Object | Postback data received. Must be an json object with required keys order_id, checksum and order_timestamp |
postback_data.checksum | string | - |
postback_data.order_id | string | - |
postback_data.order_timestamp | string | - |
api_secret | string | Api secret of the app |
Returns
boolean