Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/anurag-roy/kiteconnect-ts/llms.txt

Use this file to discover all available pages before exploring further.

KiteConnect is the primary HTTP API client. Instantiate it once per api_key and reuse it across your application. Every method returns a Promise, so you can use async/await or .then()/.catch(). The client automatically handles authentication headers, URL encoding, response parsing, and datetime conversion.
import { KiteConnect } from 'kiteconnect-ts';

const kc = new KiteConnect({ api_key: 'YOUR_API_KEY' });

Session methods

generateSession()

generateSession(request_token: string, api_secret: string): Promise<SessionData>
Exchanges the one-time request_token obtained from the login redirect for an access_token. The client automatically sets the returned token as the active access token. The response also contains user metadata.
request_token
string
required
The token present in the ?request_token= query parameter after a successful login redirect.
api_secret
string
required
The API secret issued alongside your api_key. Never expose this in client-side code.
const session = await kc.generateSession('request_token_here', 'api_secret_here');
console.log(session.access_token);

invalidateAccessToken()

invalidateAccessToken(access_token?: string): Promise<boolean>
Kills the current session by deleting the access_token on the server. Accepts an optional token to invalidate a specific session rather than the active one.
access_token
string
Token to invalidate. Defaults to the currently active token.
await kc.invalidateAccessToken();

renewAccessToken()

renewAccessToken(refresh_token: string, api_secret: string): Promise<SessionData>
Renews the access_token using a long-lived refresh_token. The new access token is automatically set as the active token.
refresh_token
string
required
Refresh token obtained from a previous generateSession() response.
api_secret
string
required
Your API secret.
const session = await kc.renewAccessToken('refresh_token_here', 'api_secret_here');

invalidateRefreshToken()

invalidateRefreshToken(refresh_token: string): Promise<boolean>
Permanently invalidates a refresh token so it can no longer be used to obtain new access tokens.
refresh_token
string
required
The refresh token to invalidate.
await kc.invalidateRefreshToken('refresh_token_here');

getLoginURL()

getLoginURL(): string
Returns the URL to which you should redirect users to begin the Kite Connect OAuth login flow. The URL embeds your api_key and the API version.
const loginUrl = kc.getLoginURL();
// Redirect the user to loginUrl

setAccessToken()

setAccessToken(access_token: string): void
Sets the active access token on the client instance. Use this if you have a persisted token and want to skip generateSession().
access_token
string
required
A valid access token obtained from a previous login session.
kc.setAccessToken(process.env.KITE_ACCESS_TOKEN!);

setSessionExpiryHook()

setSessionExpiryHook(cb: Function): void
Registers a callback that fires whenever the API returns a TokenException. Use this to log the user out, clear stored tokens, or initiate a fresh login without wrapping every API call in a try/catch.
cb
Function
required
A no-argument callback invoked on token expiry.
kc.setSessionExpiryHook(() => {
  console.warn('Session expired — redirecting to login');
  redirectToLogin();
});

getProfile()

getProfile(): Promise<UserProfile>
Returns the authenticated user’s profile details including name, email, enabled exchanges, and products.
const profile = await kc.getProfile();
console.log(profile.user_id, profile.exchanges);

getMargins()

getMargins(segment?: 'equity' | 'commodity'): Promise<{
  equity?: UserMargin;
  commodity?: UserMargin;
}>
Returns account balance and cash margin details. When segment is provided, only that segment’s UserMargin is returned; without it, both segments are returned.
segment
'equity' | 'commodity'
Trading segment to filter by. Omit to fetch both segments.
const margins = await kc.getMargins();
console.log(margins.equity?.net);

const equity = await kc.getMargins('equity');
console.log(equity.equity?.available.cash);

Order methods

placeOrder()

placeOrder(variety: Variety, params: PlaceOrderParams): Promise<{ order_id: string }>
Places a new order. Returns the exchange-assigned order_id.
variety
Variety
required
Order variety: regular, amo, co, bo, iceberg, or auction.
params
PlaceOrderParams
required
const { order_id } = await kc.placeOrder('regular', {
  exchange: 'NSE',
  tradingsymbol: 'INFY',
  transaction_type: 'BUY',
  quantity: 1,
  product: 'CNC',
  order_type: 'MARKET',
});
console.log('Placed order:', order_id);

modifyOrder()

modifyOrder(
  variety: Variety,
  order_id: string,
  params: {
    quantity?: number;
    price?: number;
    order_type?: OrderType;
    validity?: Validity;
    disclosed_quantity?: number;
    trigger_price?: number;
    parent_order_id?: string;
  }
): Promise<{ order_id: string }>
Modifies an open order. Only the fields you provide are updated.
variety
Variety
required
Variety of the order being modified.
order_id
string
required
ID of the order to modify.
await kc.modifyOrder('regular', '220818000000001', {
  quantity: 5,
  price: 1500.5,
});

cancelOrder()

cancelOrder(
  variety: Variety,
  order_id: string,
  params?: { parent_order_id?: string }
): Promise<{ order_id: string }>
Cancels an open order. For multi-leg orders (CO), pass the parent_order_id of the first leg.
variety
Variety
required
Variety of the order to cancel.
order_id
string
required
ID of the order to cancel.
await kc.cancelOrder('regular', '220818000000001');

exitOrder()

exitOrder(
  variety: Variety,
  order_id: string,
  params?: { parent_order_id?: string }
): Promise<{ order_id: string }>
Exits a bracket or cover order. Internally delegates to cancelOrder().
await kc.exitOrder('co', '220818000000002', {
  parent_order_id: '220818000000001',
});

getOrders()

getOrders(): Promise<Order[]>
Returns the list of all orders placed for the current day.
const orders = await kc.getOrders();

getOrderHistory()

getOrderHistory(order_id: string): Promise<Order[]>
Returns the state history for a specific order — one Order object per state transition.
order_id
string
required
ID of the order whose history you want to retrieve.
const history = await kc.getOrderHistory('220818000000001');

getTrades()

getTrades(): Promise<Trade[]>
Returns all trades executed across all orders for the current day.
const trades = await kc.getTrades();

getOrderTrades()

getOrderTrades(order_id: string): Promise<Trade[]>
Returns the individual fill records (trades) for a specific order. An order can be partially filled in multiple tranches.
order_id
string
required
ID of the order whose trades you want to retrieve.
const trades = await kc.getOrderTrades('220818000000001');

orderMargins()

orderMargins(orders: MarginOrder[]): Promise<Margin[]>
orderMargins(orders: MarginOrder[], mode: 'compact'): Promise<CompactMargin[]>
Calculates required margin for one or more hypothetical orders before placement. Passing 'compact' as mode returns only the total margin without a breakdown.
orders
MarginOrder[]
required
Array of order objects to calculate margin for.
mode
'compact'
Pass 'compact' to receive CompactMargin[] with only the total margin.
const margins = await kc.orderMargins([
  {
    exchange: 'NSE',
    tradingsymbol: 'INFY',
    transaction_type: 'BUY',
    variety: 'regular',
    product: 'MIS',
    order_type: 'MARKET',
    quantity: 10,
  },
]);
console.log(margins[0]?.total);

orderBasketMargins()

orderBasketMargins(orders: MarginOrder[]): Promise<{ initial: Margin; final: Margin; orders: Margin[] }>
orderBasketMargins(orders: MarginOrder[], consider_positions: boolean): Promise<{ initial: Margin; final: Margin; orders: Margin[] }>
orderBasketMargins(orders: MarginOrder[], consider_positions: boolean, mode: 'compact'): Promise<{ initial: CompactMargin; final: CompactMargin; orders: CompactMargin[] }>
Calculates basket margin for a collection of orders, accounting for netting effects. Returns initial (before netting) and final (after netting) margins along with per-order breakdown.
orders
MarginOrder[]
required
Array of orders in the basket.
consider_positions
boolean
default:"true"
Whether to factor in existing open positions when computing net margin.
const basket = await kc.orderBasketMargins(orders, true);
console.log('Net margin required:', basket.final.total);

Portfolio methods

getHoldings()

getHoldings(): Promise<PortfolioHolding[]>
Returns the long-term equity holdings in the user’s DEMAT account.
const holdings = await kc.getHoldings();

getPositions()

getPositions(): Promise<{ net: Position[]; day: Position[] }>
Returns open positions split into net (overnight + intraday) and day (intraday only) arrays.
const { net, day } = await kc.getPositions();

convertPosition()

convertPosition(params: ConvertPositionParams): Promise<boolean>
Converts an open position from one product type to another (e.g., MIS to CNC).
params
ConvertPositionParams
required
await kc.convertPosition({
  exchange: 'NSE',
  tradingsymbol: 'INFY',
  transaction_type: 'BUY',
  position_type: 'day',
  quantity: '10',
  old_product: 'MIS',
  new_product: 'CNC',
});

getAuctionInstruments()

getAuctionInstruments(): Promise<any>
Returns the list of instruments available for auction trading from the user’s holdings.
const auctionInstruments = await kc.getAuctionInstruments();

Market data methods

getInstruments()

getInstruments(exchange?: Exchange[]): Promise<Instrument[]>
Returns the full list of tradable instruments. When exchange is provided, only instruments on those exchanges are returned. The response can be several hundred kilobytes in size.
exchange
Exchange[]
Optional array of exchanges to filter by: NSE, BSE, NFO, CDS, BCD, BFO, MCX.
// All instruments
const all = await kc.getInstruments();

// NSE only
const nse = await kc.getInstruments(['NSE']);

getQuote()

getQuote(instruments: string | string[]): Promise<Record<string, Quote>>
Returns full market depth and quote data for one or more instruments. Instruments are specified as EXCHANGE:TRADINGSYMBOL strings.
instruments
string | string[]
required
A single instrument string or an array, e.g., "NSE:INFY" or ["NSE:RELIANCE", "BSE:SENSEX"].
const quotes = await kc.getQuote(['NSE:INFY', 'NSE:RELIANCE']);
console.log(quotes['NSE:INFY']?.last_price);

getOHLC()

getOHLC(instruments: string | string[]): Promise<Record<string, {
  instrument_token: number;
  last_price: number;
  ohlc: { open: number; high: number; low: number; close: number };
}>>
Returns OHLC and last traded price for one or more instruments without market depth.
const ohlc = await kc.getOHLC('NSE:INFY');
console.log(ohlc['NSE:INFY']?.ohlc.close);

getLTP()

getLTP(instruments: string | string[]): Promise<Record<string, {
  instrument_token: number;
  last_price: number;
}>>
Returns only the last traded price for one or more instruments. This is the lightest market data call.
const ltp = await kc.getLTP(['NSE:INFY', 'NSE:RELIANCE']);

getHistoricalData()

getHistoricalData(
  instrument_token: string,
  interval: 'minute' | 'day' | '3minute' | '5minute' | '10minute' | '15minute' | '30minute' | '60minute',
  from_date: string | Date,
  to_date: string | Date,
  continuous?: boolean,
  oi?: boolean
): Promise<{
  date: Date;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
  oi?: number;
}>
Returns OHLCV candles for an instrument over the given date range and interval. Dates can be Date objects or strings in 'yyyy-mm-dd HH:MM:SS' format.
instrument_token
string
required
Numeric instrument token from getInstruments().
interval
string
required
Candle interval: minute, day, 3minute, 5minute, 10minute, 15minute, 30minute, or 60minute.
from_date
string | Date
required
Start of the date range.
to_date
string | Date
required
End of the date range.
continuous
boolean
default:"false"
Set to true to get continuous data for futures and options.
oi
boolean
default:"false"
Set to true to include open interest data for F&O instruments.
const candles = await kc.getHistoricalData(
  '408065',
  'day',
  '2024-01-01 00:00:00',
  '2024-01-31 23:59:59'
);
candles.forEach(c => console.log(c.date, c.close));

Mutual funds methods

getMFOrders()

getMFOrders(order_id?: string): Promise<MFOrder | MFOrder[]>
Returns mutual fund orders for the day. When order_id is provided, returns the single matching MFOrder; otherwise returns all orders as an array.
const allOrders = await kc.getMFOrders();
const oneOrder = await kc.getMFOrders('mf_order_id');

placeMFOrder()

placeMFOrder(params: {
  tradingsymbol: string;
  transaction_type: TransactionType;
  quantity?: number;
  amount?: number;
  tag?: string;
}): Promise<{ order_id: number }>
Places a mutual fund buy or sell order.
tradingsymbol
string
required
ISIN of the fund.
transaction_type
TransactionType
required
BUY or SELL.
quantity
number
Quantity to sell. Applicable for SELL orders only.
amount
number
Amount in rupees to invest. Applicable for BUY orders only.
const { order_id } = await kc.placeMFOrder({
  tradingsymbol: 'INF209K01YY8',
  transaction_type: 'BUY',
  amount: 5000,
});

cancelMFOrder()

cancelMFOrder(order_id: string): Promise<{ order_id: string }>
Cancels a pending mutual fund order.
await kc.cancelMFOrder('mf_order_id');

getMFSIPS()

getMFSIPS(sip_id?: string): Promise<MFSIP | MFSIP[]>
Returns active and paused SIPs. When sip_id is provided, returns the single matching MFSIP.
const sips = await kc.getMFSIPS();

placeMFSIP()

placeMFSIP(params: {
  tradingsymbol: string;
  amount: number;
  instalments: number;
  frequency: 'weekly' | 'monthly' | 'quarterly';
  initial_amount?: number;
  instalment_day?: string;
  tag?: string;
}): Promise<{ sip_id: number }>
Creates a new systematic investment plan.
tradingsymbol
string
required
ISIN of the fund.
amount
number
required
Amount per instalment in rupees.
instalments
number
required
Number of instalments. Pass -1 for an indefinite SIP.
frequency
'weekly' | 'monthly' | 'quarterly'
required
Trigger frequency.
instalment_day
string
Day of month (1, 5, 10, 15, 20, 25) for monthly frequency.
const { sip_id } = await kc.placeMFSIP({
  tradingsymbol: 'INF209K01YY8',
  amount: 1000,
  instalments: 12,
  frequency: 'monthly',
  instalment_day: '5',
});

modifyMFSIP()

modifyMFSIP(
  sip_id: string,
  params: {
    instalments?: number;
    frequency?: 'weekly' | 'monthly' | 'quarterly';
    instalment_day?: string;
    status?: 'active' | 'paused';
  }
): Promise<{ sip_id: number }>
Modifies an existing SIP. You can pause it, resume it, or change its instalment schedule.
await kc.modifyMFSIP('sip_id', { status: 'paused' });

cancelMFSIP()

cancelMFSIP(sip_id: string): Promise<{ sip_id: string }>
Permanently cancels a SIP.
await kc.cancelMFSIP('sip_id');

getMFHoldings()

getMFHoldings(): Promise<MFHolding[]>
Returns all mutual fund holdings in the user’s account.
const holdings = await kc.getMFHoldings();

getMFInstruments()

getMFInstruments(): Promise<MFInstrument[]>
Returns the list of all mutual fund instruments available for trading.
const mfInstruments = await kc.getMFInstruments();

GTT methods

getGTTs()

getGTTs(): Promise<Trigger[]>
Returns all active Good Till Triggered orders.
const triggers = await kc.getGTTs();

getGTT()

getGTT(trigger_id: string): Promise<Trigger>
Returns details for a single GTT trigger.
trigger_id
string
required
ID of the GTT trigger.
const trigger = await kc.getGTT('trigger_id');

placeGTT()

placeGTT(params: GTTParams): Promise<{ trigger_id: number }>
Creates a new GTT trigger. Use GTT_TYPE_SINGLE for a single trigger price, or GTT_TYPE_OCO (one-cancels-other) for two trigger prices with two orders.
params
GTTParams
required
const { trigger_id } = await kc.placeGTT({
  trigger_type: 'single',
  tradingsymbol: 'INFY',
  exchange: 'NSE',
  trigger_values: [1400],
  last_price: 1500,
  orders: [{
    transaction_type: 'SELL',
    quantity: 10,
    product: 'CNC',
    order_type: 'LIMIT',
    price: 1400,
  }],
});

modifyGTT()

modifyGTT(trigger_id: string, params: GTTParams): Promise<{ trigger_id: number }>
Replaces an existing GTT trigger’s condition and orders with new values.
await kc.modifyGTT('trigger_id', updatedParams);

deleteGTT()

deleteGTT(trigger_id: string): Promise<{ trigger_id: number }>
Deletes a GTT trigger.
await kc.deleteGTT('trigger_id');

Utility

validatePostback()

validatePostback(
  postback_data: {
    order_id: string;
    checksum: string;
    order_timestamp: string;
  },
  api_secret: string
): boolean
Validates the SHA-256 checksum of a postback payload received from Zerodha’s servers. Returns true if the checksum matches, false otherwise. Throws an Error if required fields are missing.
postback_data
object
required
The raw postback JSON object containing order_id, checksum, and order_timestamp.
api_secret
string
required
Your API secret used to verify the HMAC signature.
const isValid = kc.validatePostback(
  {
    order_id: '220818000000001',
    order_timestamp: '2022-08-18 10:00:00',
    checksum: 'sha256_checksum_from_payload',
  },
  process.env.KITE_API_SECRET!
);

if (!isValid) {
  throw new Error('Postback checksum mismatch — possible tampering');
}
Always validate postback payloads before acting on them. An invalid checksum indicates the request did not originate from Zerodha’s servers.

Build docs developers (and LLMs) love