Kite Connect JavaScript/TypeScript Client

repository·master·Indexed 18 days ago

https://github.com/zerodha/kiteconnectjs

The official TypeScript client for the Kite Connect trading APIs (v5.3.1). It provides tools to interact with REST and WebSocket APIs for executing orders, managing portfolios, and streaming live market data via the KiteTicker class. Features include session management, GTT and Mutual Fund order handling, and historical candle data retrieval. Requires NodeJS v18.0.0 or higher.

Tokens
5.2K
Snippets
12
Records
17
Agent score
63%

What's inside kiteconnectjs

  1. Implement Kite Connect in a typical web application

    master

    In a web application where instances are created per HTTP request, you must initialize a new KiteConnect instance for every user to maintain individual authentication.

    Typical Workflow:

    1. Initialize a KiteConnect instance.
    2. Redirect the user to the login_url().
    3. At your redirect URL endpoint, extract the request_token from the query parameters.
    4. Initialize a new KiteConnect instance and use generateSession() (or the equivalent token exchange) to obtain the access_token and user data.
    5. Store the access_token in a session.
    6. For subsequent API calls, initialize a new KiteConnect instance using the stored access_token.
  2. Get started with the KiteTicker WebSocket client

    master

    The KiteTicker class is used to stream live market data via WebSockets. You must initialize it with your api_key and access_token, then call .connect(). You can listen to various events like ticks, connect, order_update, and error to handle incoming data and connection lifecycle changes.

    import { KiteTicker } from "kiteconnect";
    
    const apiKey = "your_api_key";
    const accessToken = "generated_access_token";
    
    const ticker = new KiteTicker({
      api_key: apiKey,
      access_token: accessToken,
    });
    
    ticker.connect();
    
    ticker.on("ticks", (ticks: any[]) => {
      console.log("Ticks", ticks);
    });
    
    ticker.on("connect", () => {
      const tokens = [738561, 256265];
      ticker.subscribe(tokens);
      ticker.setMode(ticker.modeFull, tokens);
    });
    
    ticker.on("order_update", (order: any) => {
      console.log("Order update", order);
    });
    
    // Other available events: "disconnect", "error", "close", "message"
  3. Get started with the KiteConnect REST API

    master

    To use the REST-like APIs (e.g., managing portfolios, executing orders), initialize a KiteConnect instance with your api_key. You must then generate a session using a request_token and your api_secret to obtain an access_token. Once obtained, use setAccessToken() to authenticate subsequent requests.

    import { KiteConnect } from "kiteconnect";
    
    const apiKey = "your_api_key";
    const apiSecret = "your_api_secret";
    const requestToken = "your_request_token";
    
    const kc = new KiteConnect({ api_key: apiKey });
    
    async function init() {
      try {
        // 1. Generate session
        const response = await kc.generateSession(requestToken, apiSecret);
        
        // 2. Set the access token for subsequent calls
        kc.setAccessToken(response.access_token);
        
        // 3. Make authenticated calls
        const profile = await kc.getProfile();
        console.log("Profile:", profile);
      } catch (err) {
        console.error(err);
      }
    }
    
    init();
  4. Initialize the KiteConnect client

    master

    To use the Kite Connect API, instantiate the KiteConnect class with your api_key. You can also provide an access_token if you have already completed the login flow, a custom root endpoint, or a debug flag to log requests and responses to the console.

    All API calls return a Promise, so you should use async/await or .then()/.catch() to handle the results and errors.

    import { KiteConnect } from 'kiteconnect';
    
    const apiKey = 'your_api_key';
    const apiSecret = 'your_api_secret';
    const requestToken = 'your_request_token';
    
    const kc = new KiteConnect({ api_key: apiKey });
    
    async function init() {
        try {
            // 1. Generate session to get access token
            const response = await kc.generateSession(requestToken, apiSecret);
            
            // 2. Set the access token for subsequent calls
            kc.setAccessToken(response.access_token);
            
            // 3. Make authenticated calls
            const profile = await kc.getProfile();
            console.log('Profile:', profile);
        } catch (err) {
            console.error(err);
        }
    }
    
    init();
  5. Enable auto re-connection for KiteTicker

    master

    To handle unreliable network conditions, you can enable client-side auto re-connection using ticker.autoReconnect(enabled, maxRetries, interval).

    • enabled: Boolean to turn on auto-reconnect.
    • maxRetries: Maximum number of reconnection attempts. Use -1 for infinite retries.
    • interval: The time interval between reconnection attempts in seconds.

    Events for Auto Re-connection:

    • reconnect: Triggered when a reconnection attempt is made. The callback receives reconnect_count and reconnect_interval.
    • noreconnect: Triggered when the maximum number of reconnection attempts is exceeded. The process will exit after this event.
    • connect: Triggered again when a reconnection is successful.
    import { KiteTicker } from "kiteconnect";
    
    const ticker = new KiteTicker({
      api_key: "api_key",
      access_token: "access_token",
    });
    
    // Enable auto reconnect: 10 retries, 5 second interval
    ticker.autoReconnect(true, 10, 5);
    
    ticker.on("reconnect", (reconnect_count: any, reconnect_interval: any) => {
      console.log("Reconnecting: attempt - ", reconnect_count, " interval - ", reconnect_interval);
    });
    
    ticker.on("noreconnect", () => {
      console.log("Maximum reconnection attempts reached. Exiting.");
    });
    
    ticker.connect();
  6. Manage GTT (Good Till Triggered) orders

    master

    Handle GTT orders using these methods:

    • placeGTT(params): Places a new GTT trigger. Supports single or two-leg (OCO) types.
    • modifyGTT(trigger_id, params): Modifies an existing GTT.
    • deleteGTT(trigger_id): Deletes a GTT order.
    • getGTTs(): Retrieves a list of all GTT triggers.
    • getGTT(trigger_id): Retrieves details for a specific GTT trigger.
  7. Manage portfolio, holdings, and positions

    master

    Monitor your account status and holdings:

    • getHoldings(): Retrieves current holdings.
    • getPositions(): Retrieves current positions.
    • getMargins(segment?): Retrieves margin details. If segment is provided, it fetches for that segment; otherwise, it fetches for all segments.
    • getAuctionInstruments(): Retrieves auction instruments from holdings.
    • convertPosition(params): Converts a position based on provided parameters.
  8. Place and manage orders

    master

    Use the following methods to interact with the order management system:

    • placeOrder(variety, params): Places a new order. If params.autoslice is set to true, the response may include a children array containing individual slice results (either order_id or an error).
    • modifyOrder(variety, order_id, params): Modifies an existing order.
    • cancelOrder(variety, order_id, params?): Cancels an existing order.
    • exitOrder(variety, order_id, params): A wrapper for cancelOrder used to exit positions.
    • getOrders(): Retrieves all active orders.
    • getOrderHistory(order_id): Retrieves the history for a specific order.
    • getTrades(): Retrieves all trades data.
    • getOrderTrades(order_id): Retrieves trades associated with a specific order.
    // Place an order
    const order = await kc.placeOrder(kc.VARIETY_REGULAR, {
        tradingsymbol: 'RELIANCE',
        exchange: kc.EXCHANGE_NSE,
        transaction_type: kc.TRANSACTION_TYPE_BUY,
        order_type: kc.ORDER_TYPE_LIMIT,
        quantity: 1,
        price: 2500
    });
    
    // Cancel an order
    await kc.cancelOrder(kc.VARIETY_REGULAR, order.order_id);
  9. Manage API sessions and access tokens

    master

    The Kite Connect API requires an access token for authenticated requests. You can manage the session lifecycle using the following methods:

    • generateSession(request_token, api_secret): Exchanges a request_token (obtained via the login flow) and your api_secret for an access_token. This method automatically sets the access token on the KiteConnect instance upon success.
    • setAccessToken(accessToken): Manually sets the access token for the client.
    • invalidateAccessToken(access_token?): Invalidates the current access token. If no token is provided, it uses the one stored in the instance.
    • renewAccessToken(refresh_token, api_secret): Renews the access token using a refresh_token. This also automatically updates the instance with the new token.
    • invalidateRefreshToken(refresh_token): Invalidates a specific refresh token.
    • getLoginURL(): Returns the Kite Connect login URL with your api_key embedded, which you can redirect users to for authentication.
    // Generate session
    const session = await kc.generateSession(requestToken, apiSecret);
    
    // Renew session
    const newSession = await kc.renewAccessToken(refreshToken, apiSecret);
    
    // Get login URL for redirection
    const url = kc.getLoginURL();
  10. Retrieve market data and historical candles

    master

    Access real-time and historical market information:

    • getInstruments(exchange?): Fetches instruments. If an exchange is provided, it fetches for that exchange; otherwise, it fetches all instruments.
    • getQuote(instruments): Retrieves quote data for one or more instruments (format: exchange:tradingsymbol).
    • getOHLC(instruments): Retrieves Open, High, Low, Close data.
    • getLTP(instruments): Retrieves the Last Traded Price.
    • getHistoricalData(instrument_token, interval, from_date, to_date, [continuous], [oi]): Fetches historical candle data.
      • interval: The time interval (e.g., 'minute', 'day').
      • from_date / to_date: Can be a string in 'YYYY-MM-DD HH:MM:SS' format or a JavaScript Date object. Note that Date objects preserve local timezone and are not converted to UTC.
    // Get LTP for multiple instruments
    const ltp = await kc.getLTP(['NSE:RELIANCE', 'NSE:TCS']);
    
    // Get historical data
    const candles = await kc.getHistoricalData(
        12345, 
        'day', 
        new Date('2023-01-01'), 
        new Date('2023-01-10')
    );
  11. Manage Mutual Fund (MF) orders and SIPs

    master

    Interact with Mutual Fund services:

    • getMFHoldings(): Retrieves MF holdings.
    • getMFInstruments(): Retrieves available MF instruments.
    • getMFOrders(order_id?): Retrieves MF orders. If order_id is provided, fetches info for that specific order; otherwise, fetches all MF orders.
    • placeMFOrder(params): Places a new MF order.
    • cancelMFOrder(order_id): Cancels an MF order.
    • getMFSIPS(sip_id?): Retrieves SIP information. If sip_id is provided, fetches info for that specific SIP; otherwise, fetches all SIPs.
    • placeMFSIP(params): Places a new SIP.
    • modifyMFSIP(sip_id, params): Modifies an existing SIP.
    • cancelMFSIP(sip_id): Cancels an existing SIP.