NAV

Introduction

Kite Connect is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (WebSockets), and more, with the easy to understand API collection.

All requests happen over HTTPs. Inputs are form-encoded parameters and responses are JSON unless stated otherwise. The responses may be Gzipped. Standard HTTP codes are used to indicate success and error states with accompanying JSON data. The API endpoints are not cross site request enabled, hence cannot be called directly from browsers.

You are issued an api_key + api_secret pair and you have to register a redirect url (HTTPS) where a user is sent after the login flow. For mobile and desktop applications, there has to be a remote backend which does the handshake on behalf of the mobile app and the api_secret should never be embedded in the application itself.

Libraries and resources

Here’s a list of client libraries for Kite Connect in various programming languages that you can just download and use without having to make raw HTTP calls to the API.

Version and API endpoint

The current major stable version of the API is v1. All requests go to v1 by default. It is recommended that you request a specific version of the API explicity for production applications as major releases may break older implementations.

Root API endpoint

https://api.kite.trade

Requesting a particular version

To request a particular version of the API, set the HTTP header X-Kite-version: v where v is the version number, major or full (eg: 1 or 1.3)

Login flow

Authentication involves redirecting a user to the public Kite login endpoint https://kite.trade/connect/login?api_key=xxx.

A successful login comes back with a request_token as a URL query parameter to the registered redirect url. This request_token, along with a checksum (SHA-256 of api_key + request_token + api_secret) should be POSTed to the token API to obtain a secret access_token, which is then used for all subsequent requests. The authentication and token exchange are detailed in the User section.

Kite Connect handshake flow

Response structure

Successful request

Success

HTTP/1.1 200 OK
Content-Type: application/json

{
    "status": "success",
    "data": {}
}

All responses from the API server are JSON with the content-type application/json unless specifically stated otherwise. A successful response is preceded by a 200 OK header with a status key with the value success in the response body. The data key contains the full response payload.

Failed request

Failure

HTTP/1.1 500 Server error
Content-Type: application/json

{
    "status": "error",
    "message": "Error message",
    "error_type": "GeneralException"
}

A failure response is preceded by the corresponding 40x or 50x header and the status key in response contains the value error. The message key contains a textual description of the error and error_type contains the name of the exception.

Data types

Values in JSON responses are of types string, int, float, or bool.

Timestamp (datetime) strings in the responses are represented in the form yyyy-mm-dd hh:mm:ss, set under the Indian timezone (IST) — UTC+5.5 hours.

A date string is represented in the form yyyy-mm-dd.

Exceptions and errors

In addition to the 40x and 50x headers, error responses come with the name of the exception generatd internally by the API server. You can define corresponding exceptions in your language or library, and raise them by doing a switch on the returned exception name.

exception  
TokenException Preceded by a 403 header, this indicates the expiry or invalidation of an authenticated session. This can be caused by the user logging out, a natural expiry, or the user logging into another Kite instance. When you encounter this error, you should clear the user’s session and re-initiate a login.
UserException Represents user account related errors
OrderException Represents order related errors such placement failures, a corrupt fetch etc
InputException Represents missing required fields, bad values for parameters etc.
NetworkException Represents a network error where the API was unable to communicate with the OMS (Order Management System)
DataException Represents an internal system error where the API was unable to understand the response from the OMS to inturn respond to a request
GeneralException Represents an unclassified error. This should only happen rarely

Common HTTP error codes

code  
400 Missing or bad request parameters or values
403 Session expired or invalidate. Must relogin
404 Request resource was not found
405 Request method (GET, POST etc.) is not allowed on the requested endpoint
410 Gone – The kitten requested has been removed from our servers
429 Too many requests to the API (rate limiting)
500 Something unexpected went wrong
502 The backend OMS is down and the API is unable to communicate with it
503 Service unavailable; the API is down
504 Gateway timeout; the API is unreachable

Parameters

Unless stated otherwise, every request requires the following parameters.

api_key

Every request before and after authentication requires the api_key

access_token

Every request after authentication requires the access_token along with api_key

Default parameter values

Example request

curl "https://api.kite.trade/parameters?api_key=xxx"
<?php
    $response = file_get_contents("https://api.kite.trade/parameters?api_key=xxx");
?>
import requests

response = requests.get("https://api.kite.trade/parameters?api_key=xxx")

Example response

{
  "status": "success",
  "data": {
    "order_variety": [
      "regular",
      "amo",
      "bo",
      "co"
    ],
    "segment": [
      "equity",
      "commodity"
    ],
    "transaction_type": [
      "BUY",
      "SELL"
    ],
    "order_type": [
      "MARKET",
      "LIMIT",
      "SL",
      "SL-M"
    ],
    "position_type": [
      "day",
      "overnight"
    ],
    "validity": [
      "DAY",
      "IOC",
      "GTC",
      "AMO"
    ],
    "product": [
      "NRML",
      "MIS",
      "CNC",
      "CO"
    ],
    "exchange": [
      "NSE",
      "BSE",
      "NFO",
      "CDS",
      "MCX",
      "MCXSX",
      "BFO"
    ]
  }
}

The API has several parameters whose values are sets of enums, from exchange names, order types, to margin and product types. Although these change rarely, it’s best not to hardcode their string values in your implementation. You should create a mutable map of these values that can be updated programmatically. The /parameters call gives you a complete list of such parameters with their enum values.

Response attributes

attribute  
order_varietystring[] This is only used to construct order URIs in order related calls
segmentstring[]
transaction_typestring[]
order_typestring[]
position_typestring[]
validitystring[]
productstring[]
exchangestring[]

User

type endpoint  
POST /session/token Authenticate and obtain the access_token after the login flow
GET /user/margins/:segment Fetch detailed funds and margin information
DELETE /session/token Logout and invalidate the session and access_token

Authentication

Example request

curl https://api.kite.trade/session/token
 -d "api_key=xxx"
 -d "request_token=yyy"
 -d "checksum=zzz"
<?php
    // Compute the SHA-256 checksum.

    $api_key = "xxxx";
    $api_secret = "yyyy";

    // Incoming request token from the redirect.
    $request_token = $_GET["request_token"];

    $checksum = hash("sha256", $api_key . $request_token . $api_secret);
?>
import hashlib

# Compute the SHA-256 checksum.
api_key = "xxxx"
api_secret = "yyyy"

# Comes from the redirect parameters.
request_token = "zzzz"

h = hashlib.sha256(api_key + request_token + api_secret)
checksum = h.hexdigest()

Response

{
  "status": "success",
  "data": {
    "access_token": "f67c2bcbfcfa30fccb36f72dca22a817",
    "public_token": "5dd3f8d7c8aa91cff362de9f73212e28",
    "user_id": "AB0012",
    "user_type": "investor",
    "email": "kite@connect",
    "user_name": "Kite Connect",
    "login_time": "2015-12-19 17:16:36",
    "broker": "ZERODHA",
    "exchange": [
      "MCXSXFO",
      "MCXSXCM",
      "BSE",
      "NSE",
      "BFO",
      "NFO",
      "NCDEX",
      "MCX",
      "CDS",
      "MCXSX"
    ],
    "product": [
      "BO",
      "CO",
      "CNC",
      "MIS",
      "NRML"
    ],
    "order_type": [
      "LIMIT",
      "MARKET",
      "SL",
      "SL-M"
    ]
  }
}

After obtaining the request_token from the login flow, you should POST it to /session/token to retrieve the access_token

Request parameters

parameter  
api_key The public API key
request_token The one-time token obtained after the login flow. This token’s lifetime is only a few minutes and it is meant to be exchanged for an access_token immediately after being obtained
checksum SHA-256 hash of (api_key + request_token + api_secret)

Response attributes

attribute  
access_tokenstring The token that is to be used with every request after authentication
public_tokenstring A token for public session validation where requests may be exposed to the public, for instance, browser WebSocket connections for streaming market data
user_idstring The unique, peramanent user id registered with the broker and the exchanges
user_typestring User’s registered role at the broker
user_namestring User’s real name
exchangestring[] Exchanges enabled for trading on the user’s account
productstring[] Order product types (margin related) enabled for the user
order_typestring[] Order types enabled for the user

Funds and margins

Example request

curl "https://api.kite.trade/user/margins/equity?api_key=xxx&access_token=yyy"
<?php
    // Fetch margins
    $margins = file_get_contents("https://api.kite.trade/user/margins/equity?api_key=xxx&access_token=yyy");
?>
import requests

# Fetch margins
margins = requests.get("https://api.kite.trade/user/margins/equity?api_key=xxx&access_token=yyy")

Example response

{
  "status": "success",
  "data": {
    "enabled": true,
    "net": 0.0,
    "available": {
      "cash": 0.0,
      "intraday_payin": 0.0,
      "adhoc_margin": 0.0,
      "collateral": 0.0
    },
    "utilised": {
      "m2m_unrealised": 0.0,
      "m2m_realised": 0.0,
      "debits": 0.0,
      "span": 0.0,
      "option_premium": 0.0,
      "holding_sales": 0.0,
      "exposure": 23285.85,
      "turnover": 0.0
    }
  }
}

A GET request to /user/margins/:segment returns funds, cash, and margin information for the user. segment in the URI can be either equity or commodity.

Response attributes

attribute  
enabledbool Indicates whether the segment is enabled for the user
netfloat Net cash balance available for trading (intraday_payin + adhoc_margin + collateral)
available.cashfloat Raw cash balance in the account available for trading (also includes intraday_payin)
available.intraday_payinfloat Amount that was deposited during the day
available.adhoc_marginfloat Additional margin provided by the broker
available.collateralfloat Margin derived from pledged stocks
utilised.m2m_unrealisedfloat Un-booked (open) intraday profits and losses
utilised.m2m_realisedfloat Booked intraday profits and losses
utilised.debitsfloat Sum of all utilised margins (unrealised M2M + realised M2M + SPAN + Exposure + Premium + Holding sales)
utilised.spanfloat SPAN margin blocked for all open F&O positions
utilised.option_premiumfloat Value of options premium received by shorting
utilised.holding_salesfloat Value of holdings sold during the day
utilised.exposurefloat Exposure margin blocked for all open F&O positions
utilised.turnoverfloat Utilised portion of the maximum turnover limit (only applicable to certain clients)

Logout

Example request

curl --request DELETE \
  "https://api.kite.trade/session/token?api_key=xxx&access_token=yyy"
import requests

# Logout
requests.delete("https://api.kite.trade/session/token?api_key=xxx&access_token=yyy")

This call invalidates the access_token and destroys the API session. After this, the user should be sent through a new login flow before further interactions.

Orders

The order APIs let you place orders of different varities on the user’s account, modify and cancel pending orders, retrieve the daily order log etc. Some call URIs are formed with the :variety of the order, and many request parameters take constant, preset values. You can get possible values for the parameters here.

type endpoint  
GET /orders Retrieve the list of all orders (open and executed) for the day
GET /orders/:order_id Retrieve an individual order’s details
GET /orders/:order_id/trades Retrieve trades generated by an order
POST /orders/:variety Place an order of a particular variety
PUT /orders/:variety/:order_id Modify an open or pending order
DELETE /orders/:variety/:order_id Cancel an open or pending order

Placing orders

Placing an order means registering it with the OMS via the API. This does not guarantee the order reaching the exchange. The fate of the order is dependent on many factors including market hours, margin requirements, risk checks, and so on. Under normal circumstances, everything from placement to confirmation of order receipt by the OMS happens in several hundred milliseconds.

When an order is successfully placed, the API returns an order_id. The status of the order is not known at the moment of placing for the aforementioned reasons.

Moreover, in case of non-MARKET orders that may be open for an indefinite time, it is not practical to poll the orders API continuously to know the status. For this, you should setup an HTTP postback endpoint where Kite Connect will asynchronously post updates to orders as they happen.

Order varieties

You can place orders of varieties; regular orders, after market orders, cover orders etc. See the list of varieties here.

Example request

curl https://api.kite.trade/orders/regular \
    -d "api_key=xxx" \
    -d "access_token=yyy" \
    -d "tradingsymbol=ACC" \
    -d "exchange=NSE" \
    -d "transaction_type=BUY" \
    -d "order_type=MARKET" \
    -d "quantity=1" \
    -d "product=MIS" \
    -d "validity=DAY"
import requests

payload = {
  "api_key=xxx",
  "access_token=yyy",
  "tradingsymbol=ACC",
  "exchange=NSE",
  "transaction_type=BUY",
  "order_type=MARKET",
  "quantity=1",
  "product=MIS",
  "validity=DAY"
}

response = requests.post("https://api.kite.trade/orders/regular", data=payload)

Example response

{
  "status": "success",
  "data": {
    "order_id": "151220000000000"
  }
}

Regular order parameters

These parameters are common across different order varieties.

parameter  
tradingsymbol Tradingsymbol of the instrument
exchange Name of the exchange
transaction_type BUY or SELL
order_type Order type (MARKET, LIMIT etc.)
quantity Quantity to transact
product Margin product applied to the order (margin is blocked based on this). More on margin products here.
price For LIMIT orders
trigger_price For SL, SL-M etc.
disclosed_quantity Quantity to disclose publicly (for equity trades)
validity Order validity
tag An optional tag to apply to an order to identify it (alphanumeric, max 8 chars)

Bracket Order (BO) parameters

Bracket orders require these additional parameters. Bracket orders only support the LIMIT order type.

parameter  
squareoff_value Price difference at which the order should be squared off and profit booked (eg: Order price is 100. Profit target is 102. So squareoff_value = 2)
stoploss_value Stoploss difference at which the order should be squared off (eg: Order price is 100. Stoploss target is 98. So stoploss_value = 2)
trailing_stoploss Incremental value by which stoploss price changes when market moves in your favor by the same incremental value from the entry price (optional)

Response attributes

attribute  
order_idstring Unique order id

Modifying orders

As long as on order is open or pending in the system, certain attributes of it may be modified. Although, many unomodifiable parameters derived from the placed order still have to be sent because of the way the OMS is designed.

Example request

curl --request PUT https://api.kite.trade/orders/regular/151220000000000 \
    -d "api_key=xxx" \
    -d "access_token=yyy" \
    -d "tradingsymbol=ACC" \
    -d "exchange=NSE" \
    -d "transaction_type=BUY" \
    -d "order_type=MARKET" \
    -d "quantity=3" \
    -d "product=MIS" \
    -d "validity=DAY"
import requests

payload = {
  "api_key=xxx",
  "access_token=yyy",
  "tradingsymbol=ACC",
  "exchange=NSE",
  "transaction_type=BUY",
  "order_type=MARKET",
  "quantity=3",
  "product=MIS",
  "validity=DAY"
}

response = requests.put("https://api.kite.trade/orders/regular/151220000000000", data=payload)

Example response

{
  "status": "success",
  "data": {
    "order_id": "151220000000000"
  }
}

Regular order parameters

parameter  
order_id Id of the order to be modified
tradingsymbol Tradingsymbol of the instrument
exchange Name of the exchange
transaction_type BUY or SELL
order_type Order type (MARKET, LIMIT etc.)
quantity Quantity to transact (modifiable)
product Margin product applied to the order (margin is blocked based on this). More on margin products here.
price For LIMIT orders (modifiable)
trigger_price For SL, SL-M etc.
disclosed_quantity Quantity to disclose publicly (for equity trades) (modifiable)
validity Order validity (modifiable)

Bracket Order (BO) parameters

For bracket orders, only the following parameters are necessary.

parameter  
order_id Id of the order to be modified
parent_order_id Id of the parent order (obtained from the /orders call) as BO is a multi-legged order
tradingsymbol Tradingsymbol of the instrument
exchange Name of the exchange
quantity Quantity to transact (modifiable)
price Price to execute at (modifiable)
trigger_price (modifiable)

Cover Order (CO) parameters

For cover orders, only the following parameters are necessary. The same parameters are modifiable as well. Cover orders only support the MARKET order type.

parameter  
order_id Id of the order to be modified
tradingsymbol Tradingsymbol of the instrument
exchange Name of the exchange
trigger_price (modifiable)

Cancelling orders

As long as on order is open or pending in the system, it can be cancelled.

Example request

curl --request DELETE \
    "https://api.kite.trade/orders/regular/151220000000000?api_key=xxx&access_token=yyy"
# Exit / cancel a bracket order.
curl --request DELETE \
    "https://api.kite.trade/orders/bo/151220000000000?api_key=xxx&access_token=yyy&parent_order_id=151210000000000"
import requests
response = requests.delete("https://api.kite.trade/orders/regular/151220000000000?api_key=xxx&access_token=yyy")
# Exit / cancel a bracket order.
import requests
response = requests.delete("https://api.kite.trade/orders/regular/151220000000000?api_key=xxx&access_token=yyy")

Example response

{
  "status": "success",
  "data": {
    "order_id": "151220000000000"
  }
}

Cancelling and exiting Bracket Orders (BO)

As a bracket order is a two-legged order, it can only be “cancelled” when the first entry order is pending. This works like cancelling any other order. However, if the entry order is executed and the second order is pending, the order can only be exited. The API call for cancellation and exiting is the same.

For cancelling or exiting bracket orders, an additional parameter has to be sent.

parameter  
parent_order_id Id of the parent order (obtained from the /orders call) as BO is a multi-legged order

Retrieving orders

Order history is transient, and only lives for a day in the system. When you retrieve orders, you get all the orders for the day including open, pending, and executed ones.

Example request

curl --compressed "https://api.kite.trade/orders?api_key=xxx&access_token=yyy"
<?php
    $response = file_get_contents("https://api.kite.trade/orders?api_key=xxx&access_token=yyy");
?>
import requests

response = requests.get("https://api.kite.trade/orders?api_key=xxx&access_token=yyy")

Example response

{
  "status": "success",
  "data": [{
    "order_id": "151220000000000",
    "parent_order_id": "151210000000000",
    "exchange_order_id": null,
    "placed_by": "AB0012",
    "variety": "regular",
    "status": "REJECTED",

    "tradingsymbol": "ACC",
    "exchange": "NSE",
    "instrument_token": 22,
    "transaction_type": "BUY",
    "order_type": "MARKET",
    "product": "NRML",
    "validity": "DAY",

    "price": 0.0,
    "quantity": 75,
    "trigger_price": 0.0,

    "average_price": 0.0,
    "pending_quantity": 0,
    "filled_quantity": 0,
    "disclosed_quantity": 0,
    "market_protection": 0,

    "order_timestamp": "2015-12-20 15:01:43",
    "exchange_timestamp": null,

    "status_message": "RMS:Margin Exceeds, Required:0, Available:0",
    "tag": null
  }]
}

Response attributes

attribute  
order_idstring Unique order id
parent_order_idstring Order id of the parent order (only applicable in case of multi-legged orders like BO and CO)
exchange_order_idnull, string Exchange generated order id. Orders that don’t reach the exchange have null ids
placed_bystring Id of the user that placed the order. This may different from the user’s id for orders placed outside of Kite, for instance, by dealers at the brokerage using dealer terminals
varietystring Order variety (regular, amo etc.)
statusstring Current status of the order. Most common values or COMPLETE, REJECTED, CANCELLED, and OPEN. There may be other values as well.
tradingsymbolstring Exchange tradingsymbol of the of the instrument
exchangestring Exchange
instrument_tokenstring The numerical identifier issued by the exchange representing the instrument. Used for subscribing to live market data over WebSocket
transaction_typestring BUY or SELL
productstring Margin product applied to the order (margin is blocked based on this). More on margin products here.
validitystring Order validity
pricefloat Price at which the order was placed (LIMIT orders)
quantityint Quantity ordered
trigger_pricefloat Trigger price (for SL, SL-M, CO orders)
average_pricefloat Average price at which the order was executed (only for COMPLETE orders)
peding_quantityint Pending quantity to be filled
filled_quantityint Quantity that’s been filled
disclosed_quantityint Quantity to be disclosed (may be different from actual quantity) to the public exchange orderbook. Only for equities
order_timestampstring Timestamp at which the order was registered by the API
exchange_timestampstring Timestamp at which the order was registered by the exchange. Orders that don’t reach the exchange have null timestamps
status_messagenull, string Textual description of the order’s status. Failed orders come with human readable explanation

Retrieving an individual order

Example request

curl "https://api.kite.trade/orders/151220000000000?api_key=xxx&access_token=yyy"
<?php
    $response = file_get_contents("https://api.kite.trade/orders/151220000000000?api_key=xxx&access_token=yyy");
?>
import requests

response = requests.get("https://api.kite.trade/orders/151220000000000?api_key=xxx&access_token=yyy")

Example response

{
  "status": "success",
  "data": [{
    "status": "REJECTED",
    "product": "NRML",
    "pending_quantity": 0,
    "order_type": "MARKET",
    "exchange": "NFO",
    "order_id": "151220000000000",
    "price": 0.0,
    "exchange_order_id": null,
    "order_timestamp": "2015-12-20 15:01:43",
    "transaction_type": "BUY",
    "trigger_price": 0.0,
    "validity": "DAY",
    "disclosed_quantity": 0,
    "status_message": "RMS:Margin Exceeds, Required:0, Available:0",
    "average_price": 0.0,
    "quantity": 75
  }, {
    "status": "VALIDATION PENDING",
    "product": "NRML",
    "pending_quantity": 75,
    "order_type": "MARKET",
    "exchange": "NFO",
    "order_id": "151220000000000",
    "price": 0.0,
    "exchange_order_id": null,
    "order_timestamp": "2015-12-20 15:01:43",
    "transaction_type": "BUY",
    "trigger_price": 0.0,
    "validity": "DAY",
    "disclosed_quantity": 0,
    "status_message": null,
    "average_price": 0.0,
    "quantity": 75
  }, {
    "status": "PUT ORDER REQ RECEIVED",
    "product": "NRML",
    "pending_quantity": 0,
    "order_type": "MARKET",
    "exchange": "NFO",
    "order_id": "151220000000000",
    "price": 0.0,
    "exchange_order_id": null,
    "order_timestamp": "2015-12-20 15:01:43",
    "transaction_type": "BUY",
    "trigger_price": 0.0,
    "validity": "DAY",
    "disclosed_quantity": 0,
    "status_message": null,
    "average_price": 0.0,
    "quantity": 75
  }]
}

Every order, right after being placed, goes through multiple stages internally in the OMS. Initial validation, RMS (Risk Management System) checks and so on before it goes to the exchange. In addition, an open order, when modified, further goes through changes. These are recorded as a list in descending order with the latest being the first.

Retrieving trades

While an orders is sent as a single entity, it may be executed in arbitrary chunks at the exchange depending on market conditions. For instance, an order for 10 quantity of an instrument can be executed in chunks of 5, 1, 1, 3 or any such combination. Each individual execution that fills an order partially is a trade. An order may have one or more trades.

The /trades call returns a list of all trades generated by all all executed orders.

Example request

curl "https://api.kite.trade/trades?api_key=xxx&access_token=yyy"
<?php
    $response = file_get_contents("https://api.kite.trade/trades?api_key=xxx&access_token=yyy");
?>
import requests

response = requests.get("https://api.kite.trade/trades?api_key=xxx&access_token=yyy")

Example response

{
    "status": "success",
    "data": [{
        "trade_id": 159918,
        "order_id": "151220000000000",
        "exchange_order_id": "511220371736111",

        "tradingsymbol": "ACC",
        "exchange": "NSE",
        "instrument_token": "22",

        "transaction_type": "BUY",
        "product": "MIS",
        "average_price": 100.98,
        "quantity": 10,

        "order_timestamp": "2015-12-20 15:01:44",
        "exchange_timestamp": "2015-12-20 15:01:43"

    }]
}

Response attributes

attribute  
trade_idstring Exchange generated trade id
order_idstring Unique order id
exchange_order_idnull, string Exchange generated order id
tradingsymbolstring Exchange tradingsymbol of the o
exchangestring Exchange
instrument_tokenstring The numerical identifier issued by the exchange representing the instrument. Used for subscribing to live market data over WebSocket
transaction_typestring BUY or SELL
productstring Margin product applied to the order (margin is blocked based on this). More on margin products here.
average_pricefloat Price at which the was filled
filledint Filled quantity
order_timestampstring Timestamp at which the order was registered by the API
exchange_timestampstring Timestamp at which the order was registered by the exchange. Orders that don’t reach the exchange have null timestamps

Portfolio

A user’s portfolio consists of long term and short term holdings and positions. The API delivers portfolio data with up-to-date profit and loss computations.

type endpoint  
GET /portfolio/holdings Retrieve the list of long term equity holdings
GET /portfolio/positions Retrieve the list of short term positions

Holdings

Holdings contain the user’s portfolio of long term equity delivery stocks. A holdings portfolio commonly has a lifetime of a few days to many years. Holdings, post delivery, are assigned digitally to the user’s DEMAT account by the exchanges and clearing members.

Example request

curl "https://api.kite.trade/portfolio/holdings/?api_key=xxx&access_token=yyy"
<?php
    $response = file_get_contents("https://api.kite.trade/portfolio/holdings/?api_key=xxx&access_token=yyy");
?>
import requests

response = requests.get("https://api.kite.trade/portfolio/holdings/?api_key=xxx&access_token=yyy")

Example response

{
  "status": "success",
  "data": [{
    "tradingsymbol": "ABHICAP",
    "exchange": "BSE",
    "isin": "INE516F01016",
    "quantity": 0,
    "realised_quantity": 1,
    "t1_quantity": 1,

    "average_price": 94.75,
    "last_price": 93.75,
    "pnl": -100.0,

    "product": "CNC",
    "collateral_quantity": 0,
    "collateral_type": null
  }, {
    "tradingsymbol": "AXISBANK",
    "exchange": "NSE",
    "isin": "INE238A01034",
    "quantity": 1,
    "realised_quantity": 1,
    "t1_quantity": 0,

    "average_price": 475.0,
    "last_price": 432.55,
    "pnl": -42.50,

    "product": "CNC",
    "collateral_quantity": 0,
    "collateral_type": null
  }]
}

Response attributes

attribute  
tradingsymbolstring Exchange tradingsymbol of the instrument
exchangestring Exchange
isinstring The standard ISIN representing stocks listed on multiple exchanges
quantityint Quantity held
realised_quantityint
t1_quantityint Quanity on T+1 day after order execution. Stocks are usualy delivered on T+2
average_pricefloat Average price at which the net holding quantity was acquired
last_pricefloat Last traded market price of the instrument
pnlfloat Net returns on the stock; Profit and loss
productstring Margin product applied to the holding
collateral_quantityint Quantity used as collateral
collateral_typenull,string Type of collateral

Positions

Positions contain the user’s portfolio of short to medium term derivatives (futures and options contracts) and intraday equity stocks. Items in a positions portfolio usually have a lifetime of mere minutes to a few days. Derivative positions can be held overnight for many days until the contracts expire. Equity positions carried overnight become a part of the holdings portfolio.

The positions API returns two sets of positions, net and day. net is the actual, current net position portfolio, while day is a snapshot of the buying and selling activity that may have been applied to a carry forward position.

Example request

curl "https://api.kite.trade/portfolio/positions/?api_key=xxx&access_token=yyy"
<?php
    $response = file_get_contents("https://api.kite.trade/portfolio/positions/?api_key=xxx&access_token=yyy");
?>
import requests

response = requests.get("https://api.kite.trade/portfolio/positions/?api_key=xxx&access_token=yyy")

Sample response

{
  "status": "success",
  "data": {
    "net": [{
      "tradingsymbol": "NIFTY15DEC9500CE",
      "exchange": "NFO",
      "instrument_token": 41453,
      "product": "NRML",

      "quantity": -100,
      "overnight_quantity": -100,
      "multiplier": 1,

      "average_price": 3.475,
      "close_price": 0.75,
      "last_price": 0.75,
      "value": 75.0,
      "pnl": 272.5,
      "m2m": 0.0,
      "unrealised": 0.0,
      "realised": 0.0,

      "buy_quantity": 0,
      "buy_price": 0,
      "buy_value": 0.0,
      "buy_m2m": 0.0,

      "sell_quantity": 100,
      "sell_price": 3.475,
      "sell_value": 347.5,
      "sell_m2m": 75.0
    }],
    "day": []
  }
}

Response attributes

attribute  
tradingsymbolstring Exchange tradingsymbol of the instrument
exchangestring Exchange
instrument_tokenstring The numerical identifier issued by the exchange representing the instrument. Used for subscribing to live market data over WebSocket
productstring Margin product applied to the position
quantityint Quantity held
overnight_quantityint Quantity held previously and carried forward over night
multiplierint The quantity/lot size multiplier used for calculating P&Ls.
average_pricefloat Average price at which the net position quantity was acquired
close_pricefloat Closing price of the instrument from the last trading day
last_pricefloat Last traded market price of the instrument
valuefloat Net value of the position
pnlfloat Net returns on the position; Profit and loss
m2mfloat Mark to market returns (computed based on the last close and the last traded price)
unrealisedfloat Unrelaised intraday returns
realisedfloat Realised intraday returns
buy_quantityint Quantity bought and added to the position
buy_pricefloat Average price at which quantities were bought
buy_valuefloat Net value of the bought quantities
buy_m2mfloat Mark to market returns on the bought quantities
sell_quantityint Quantity sold off from the position
sell_pricefloat Average price at which quantities were sold
sell_valuefloat Net value of the sold quantities
sell_m2mfloat Mark to market returns on the sold quantities

Position conversion

All positions held are of specific margin products such as NRML, MIS etc. A position can have one and only one margin product. These products affect how the user’s margin usage and free cash values are computed, and a trader may want to covert or change a position’s margin product from time to time.

Example request

curl --request PUT https://api.kite.trade/portfolio/positions
    -d "api_key=xxx" \
    -d "access_token=yyy" \
    -d "tradingsymbol=INFY" \
    -d "exchange=NSE" \
    -d "transaction_type=BUY" \
    -d "position_type=overnight" \
    -d "quantity=3" \
    -d "old_product=NRML" \
    -d "new_product=MIS"
import requests

payload = {
  "api_key=xxx",
  "access_token=yyy",
  "tradingsymbol=INFY",
  "exchange=NSE",
  "transaction_type=BUY",
  "position_type=overnight",
  "quantity=3",
  "old_product=NRML",
  "new_product=MIS"
}

response = requests.put("https://api.kite.trade/portfolio/positions", data=payload)

Example response

{
  "status": "success",
  "data": true
}

Request parameters

parameter  
tradingsymbol Tradingsymbol of the instrument
exchange Name of the exchange
transaction_type BUY or SELL
position_type overnight or day
quantity Quantity to convert
old_product Existing margin product of the position
new_product Margin product to convert to

Exiting holdings and positions

There are no special API calls for exiting instruments from holdings and positions portfolios. The way to do it is to place an opposite BUY or SELL order depending on whether the position is a long or a short (MARKET order for an immediate exit). It is important to note that the exit order should carry the same product as of the existing position. If the exit order is of a different margin product, it may show up as a new position in the portfolio.

Market and instruments

Between multiple exchanges and segments, there are tens of thousands of various kinds of instruments that trade. Any application that facilitates trading needs to have a master list of these instruments.

The market API calls provide a consolidated, import-ready list of instruments enabled on Kite for trading.

type endpoint  
GET /instruments Retrieve the CSV dump of all tradable instruments
GET /instruments/:exchange Retrieve the CSV dump of instruments in the particular exchange
GET /instruments/:exchange/:tradingsymbol Retrieve market quote for an instrument

Retrieving full instrument list

Unlike the rest of the calls that return JSON, the instrument list API returns a Gzipped CSV dump of instruments across all exchanges that can be imported into a database.

Example request

curl --compressed "https://api.kite.trade/instruments?api_key=xxx"
<?php
    $response = file_get_contents("https://api.kite.trade/instruments?api_key=xxx");
?>
import requests

response = requests.get("https://api.kite.trade/instruments?api_key=xxx")

Example response

instrument_token, exchange_token, tradingsymbol, name, last_price, expiry, strike, tick_size, lot_size, instrument_type, segment, exchange
408065,1594,INFY,INFOSYS,0,,,0.05,1,EQ,NSE,NSE
5720322,22345,NIFTY15DECFUT,,78.0,2015-12-31,,0.05,75,FUT,NFO-FUT,NFO
5720578,22346,NIFTY159500CE,,23.0,2015-12-31,9500,0.05,75,CE,NFO-OPT,NFO
645639,SILVER15DECFUT,,7800.0,2015-12-31,,1,1,FUT,MCX,MCX

Response columns

column  
instrument_tokenstring Numerical identifier used for subscribing to live market quotes with the WebSocket API.
exchange_tokenstring The numerical identifier issued by the exchange representing the instrument.
tradingsymbolstring Exchange tradingsymbol of the instrument
namestring Name of the company (for equity instruments)
last_pricefloat Last traded market price
expirystring Expiry date (for derivatives)
strikefloat Strike (for options)
tick_sizefloat Value of a single price tick
lot_sizeint Quantity of a single lot
instrument_typestring EQ, FUT, CE, PE
segmentstring Segment the instrument belongs to
exchangestring Exchange

Retrieving market quotes

The market quote call of an instrument gives you quantity, price, and volume information along with the current OHLC (Open High Low Close) and 5 levels of bid-ask market depth.

Example request

curl "https://api.kite.trade/instruments/NSE/INFY?api_key=xxx&access_token=yyy"
<?php
    $response = file_get_contents("https://api.kite.trade/instruments/NSE/INFY?api_key=xxx&access_token=yyy");
?>
import requests

response = requests.get("https://api.kite.trade/instruments/NSE/INFY?api_key=xxx&access_token=yyy")

Example response

{
  "status": "success",
  "data": {
    "last_price": 1083.15,
    "change_percent": 0.0,
    "change": 0.0,
    "volume": 0,
    "buy_quantity": 0,
    "sell_quantity": 0,
    "open_interest": 0,
    "last_quantity": 5,
    "last_time": "2015-12-15 10:16:36",

    "ohlc": {
      "open": 1103.4,
      "high": 1103.4,
      "low": 1079.45,
      "close": 1083.15
    },
    "depth": {
      "buy": [{
        "price": 0,
        "orders": 0,
        "quantity": 0
      }],
      "sell": [{
        "price": 0,
        "orders": 0,
        "quantity": 0
      }]
    }
  }
}

Response attributes

attribute  
last_pricefloat Last traded market price
change_percentfloat Percent change from the last traded price to last close price
changefloat Absolute change from the last traded price to last close price
volumeint Volume traded today
buy_quantityint Total quantity of buy orders
sell_quantityint Total quantity of sell orders
open_interestfloat Total number of outstanding contracts held by market participants exchange-wide (only F&O)
last_quantityint Last traded quantity
last_timenull, string Time of last trade
ohlc.openfloat Price at market opening
ohlc.highfloat Highest price today
ohlc.lowfloat Lowest price today
ohlc.closefloat Closing price of the instrument from the last trading day
depth.buy[].pricefloat Price at which the depth stands
depth.buy[].ordersint Number of open BUY (bid) orders at the price
depth.buy[].quantityint Net quantity from the pending orders
depth.sell[].pricefloat Price at which the depth stands
depth.sell[].ordersint Number of open SELL (ask) orders at the price
depth.sell[].quantityint Net quantity from the pending orders

Offsite order execution

The offsite order execution feature allows you to redirect your users to Kite’s exchange approved order page where they place orders and come back to your application seamlessly, like a payment gateway. This way, you do not have to build, maintain, and get exchange approvals for order execution screens. The Kite Publisher program utilises offsite order execution to provide embeddable Javascript+HTML trade buttons that do not require any API integrations.

Initiating orders

Example JSON basket

[{
  "tradingsymbol": "INFY",
  "exchange": "NSE",
  "transaction_type": "BUY",
  "order_type": "MARKET",
  "quantity": 10,
  "readonly": false
}, {
  "tradingsymbol": "NIFTY15DECFUT",
  "exchange": "NFO",
  "transaction_type": "SELL",
  "order_type": "LIMIT",
  "price": 7845,
  "quantity": 1,
  "readonly": false
}]

Posting the JSON basket

<form method="post" id="basket-form" action="https://kite.trade/connect/basket">
  <input type="hidden" name="api_key" value="xxx" />
  <input type="hidden" id="basket" name="data" value="" />
</form>

<script>
  document.getElementById("basket").value = your_basket;
  document.getElementById("basket-form").submit();
</script>

It is possible to send multiple orders which the user then confirms on a shopping basket like interface. You should prepare a JSON list of instruments to be traded with the required order parameters and POST it as a form field with the name data along with your api_key to https://kite.trade/connect/basket.

This is a browser / mobile (webview) request and has to happen at the user’s end, although the basket preparation can happen in the backend. The easiest way to make the request is to create a hidden form, insert the JSON payload into it and submit it automatically using Javascript.

If you’re preparing the basket client side on your web application, you can use the Kite Publisher javascript plugin to make things easier.

Linking offsite execution to Kite Connect

Offsite order execution follows the same flow as login, except for the order basket that appears after the login. Once the user is done placing orders, the basket will redirect back to your registered redirect_login along with a request_key, exactly like login. You are free to use this key to create a new Kite Connect session for further API interactions, or disregard it altogether.

Request parameters

parameter  
tradingsymbol Tradingsymbol of the instrument
exchange Name of the exchange
transaction_type BUY or SELL
order_type Order type (MARKET, LIMIT etc.)
quantity Quantity to transact
product Margin product. More on margin products here.
price For LIMIT orders
trigger_price For SL, SL-M etc.
disclosed_quantity Quantity to disclose publicly (for equity trades)
validity Order validity
readonly Default is false. If set to true, the UI does not allow the user to edit values such as quantity, price etc., and they can only review and execute.

Postback (Webhooks)

The Postback API sends a POST request with a JSON payload to the registered postback_url of your app when an order’s status changes. This enables you to get arbitrary updates to your orders reliably, irrespective of when they happen (COMPLETE, CANCEL, REJECTED).

The JSON payload is posted as a raw HTTP POST body. You will have to read the raw body and then decode it.

Example payload

{
    "order_id": "16032300017157",
    "exchange_order_id": "511220371736111",
    "placed_by": "AB0012",
    "status": "COMPLETE",
    "status_message": "",

    "tradingsymbol": "TATAMOTORS",
    "exchange": "NSE",
    "order_type": "MARKET",
    "transaction_type": "SELL",
    "validity": "DAY",
    "product": "CNC",

    "average_price": 376.35,
    "price": 376.35,
    "quantity": 1,
    "filled_quantity": 1,
    "unfilled_quantity": 0,
    "trigger_price": 0,
    "status_message": "",
    "order_timestamp": "2015-12-20 15:01:43",
    "exchange_timestamp": "2015-12-20 15:01:43",
    "checksum": "5aa3f8e3c8cc41cff362de9f73212e28"
}

Checksum

The JSON payload comes with a checksum, which is the SHA-256 hash of (order_id + timestamp + api_secret). Every time you receive an update, you should compute this checksum at your end and match it with the one in the payload. This is to ensure that the update is being POSTed by Kite Connect and not an unauthorised third party, as only Kite Connect can generate a checksum that contains your api_secret.

Payload attributes

attribute  
order_idstring Unique order id
exchange_order_idnull, string Exchange generated order id. Orders that don’t reach the exchange have null ids
placed_bystring Id of the user that placed the order. This may different from the user’s id for orders placed outside of Kite, for instance, by dealers at the brokerage using dealer terminals.
statusstring Current status of the order. Most common values or COMPLETE, REJECTED, CANCELLED, and OPEN. There may be other values as well.
tradingsymbolstring Exchange tradingsymbol of the of the instrument
exchangestring Exchange
transaction_typestring BUY or SELL
validitystring Order validity
average_pricefloat Average price at which the order was executed (only for COMPLETE orders)
pricefloat Price at which the order was placed (LIMIT orders)
quantityint Quantity ordered
filled_quantityint Quantity that’s been filled
trigger_pricefloat Trigger price (for SL, SL-M, CO orders)
status_messagenull, string Textual description of the order’s status. Failed orders come with human readable explanation
order_timestampstring Timestamp at which the order was registered by the API
checksumstring SHA-256 hash of (order_id + timestamp + api_secret)

Streaming (WebSocket)

The WebSocket API is the most efficient (speed, latency, resoruce consumption, and bandwidth) way to receive quotes for instruments across all exchanges during live market hours. A quote consists of fields such as open, high, low, close, last traded price etc., in addition to 5 levels of bid/offer market depth data.

As the name suggests, the API uses WebSocket protocol to establish a single long standing TCP connection after an HTTP handshake to receive streaming quotes. To connect to the Kite WebSocket API, you will need a WebSocket client library in your choice of programming language.

Quotes delivered via the API are binary messages, and you need to read the bytes and cast them into appropriate quote data structures. When you initialise a WebSocket connection, you should set its type to binary. All requests you send to the API are JSON messages, and the API may also respond with non-quote, non-binary JSON messages, which you should ignore. Instruments are identified with their corresponding numerical instrument_tokens obtained from the instrument list API.

Connecting to the WebSocket

// Javascript example.
var ws = new WebSocket("wss://websocket.kite.trade/?api_key=xxx&user_id=AB0012&public_token=xxxx");

The WebSocket endpoint is wss://websocket.kite.trade. To establish a connection, you have to pass three query parameters, api_key, user_id and public_token, the latter two, which are obtained after successful authentication. This is different from other APIs where you only pass access_token, as WebSockets may be used in public contexts, such as directly inside a webpage, where the connection is exposed to the world.

Request structure

// Subscribe to quotes for INFY (408065) and TATAMOTORS (884737)
var message = {"a": "subscribe", "v": [408065, 884737]};
ws.send(JSON.stringify(message))

Requests are simple JSON messages with two parameters, a (action) and v (value). Following are the available actions and possible values. Many values are arrays, for instance, array of instrument_tokens that can be passed to subscribe to multiple instruments at once.

a v
subscribe [instrument_token … ]
unsubscribe [instrument_token … ]
mode [mode, [instrument_token … ]]
// Set INFY (408065) to 'full' mode to
// receive market depth as well.
message = {"a": "mode", "v": ["full", [408065]]};
ws.send(JSON.stringify(message))

// Set TATAMOTORS (884737) to 'ltp' to only receive the LTP.
message = {"a": "mode", "v": ["ltp", [884737]]};
ws.send(JSON.stringify(message))

Modes

There are three different modes in which quote packets are streamed.

mode  
ltp LTP. Packet contains only the last traded price (8 bytes).
quote Quote. Packet contains several fields excluding market depth (44 bytes).
full Full. Packet contains several fields including market depth (164 bytes).

Message structure

Each binary message (array of 0 to n individual bytes)–or frame in WebSocket terminology–received via the WebSocket is a combination of one or more quote packets for one or more instruments. The message structure is as follows.

WebSocket API message structure

   
A The first two bytes ([0 - 2] – SHORT or int16) represent the number of packets in the message.
B The next two bytes ([2 - 4] – SHORT or int16) represent the length (number of bytes) of the first packet.
C The next series of bytes ([4 - 4+B]) is the quote packet.
D The next two bytes ([4+B - 4+B+2] – SHORT or int16) represent the length (number of bytes) of the second packet.
C The next series of bytes ([4+B+2 - 4+B+2+D]) is the next quote packet.

Packet structure

Each individual packet extracted from the message, based on the structure shown in the previous section, can be cast into a data structure as follows. All prices are in paise. For currencies, the int32 price values should be divided by 10000000 to obtain four decimal plaes. For everything else, the price values should be divided by 100.

Bytes Type  
0 - 4 int32 instrument_token
4 - 8 int32 Last traded price (If mode is ltp, the packet ends here)
8 - 12 int32 Last traded quantity
12 - 16 int32 Average traded price
16 - 20 int32 Volume traded for the day
20 - 24 int32 Total buy quantity
24 - 28 int32 Total sell quantity
28 - 32 int32 Open price of the day
32 - 36 int32 High price of the day
36 - 40 int32 Low price of the day
40 - 44 int32 Close price (If mode is quote, the packet ends here)
44 - 164 []byte Market depth entries

Market depth structure

Each market depth entry is a combination of 3 fields, quantity (int32), price (int32), orders (int32), totalling to 12 bytes. There are ten entries in succession—five [44 - 104] bid entries and five [104 - 164] offer entries.

Historical data

The historical data API provides archived data (up to date as of the time of access) for instruments across various exchanges spanning back several years. A historical record is presented in the form of a candle (Timestamp, Open, High, Low, Close, Volume), and the data is available in several intervals—minute, 3 minutes, 5 minutes, hourly … daily.

type endpoint  
GET /instruments/historical/:instrument_token/:interval Retrieve historical candle records for a given instrument.

Example request

# Fetch minute candles off NSE-ACC.
# This will return several days of minute data ending today.
# The time of request is assumed to be to be 01:30 PM, 1 Jan 2016,
# which is reflected in the latest (last) record.

# The data has been truncated with ... in the example responses.

curl "https://api.kite.trade/instruments/historical/5633/minute?from=2015-12-28&to=2016-01-01&api_key=xxx&access_token=yyy"
<?php
    // Fetch minute candles off NSE-ACC.
    // This will return several days of minute data ending today.
    // The time of request is assumed to be to be 01:30 PM, 1 Jan 2016,
    // which is reflected in the latest (last) record.

    // The data has been truncated with ... in the example responses.
    $response = file_get_contents("https://api.kite.trade/instruments/historical/5633/minute?from=2015-12-28&to=2016-01-01&api_key=xxx&access_token=yyy");
?>
# Fetch minute candles off NSE-ACC.
# This will return several days of minute data ending today.
# The time of request is assumed to be to be 01:30 PM, 1 Jan 2016,
# which is reflected in the latest (last) record.

# The data has been truncated with ... in the example responses.

import requests

response = requests.get("https://api.kite.trade/instruments/historical/5633/minute?from=2015-12-28&to=2016-01-01&api_key=xxx&access_token=yyy")

Example response

{
    "status": "success",
    "data": {
        "candles": [
            ["2015-12-28T09:15:00+0530", 1386.4, 1388, 1381.05, 1385.1, 788],
            ["2015-12-28T09:16:00+0530", 1385.1, 1389.1, 1383.85, 1385.5, 609],
            ["2015-12-28T09:17:00+0530", 1385.5, 1387, 1385.5, 1385.7, 212],
            ["2015-12-28T09:18:00+0530", 1387, 1387.95, 1385.3, 1387.95, 1208],
            ["2015-12-28T09:19:00+0530", 1387, 1387.55, 1385.6, 1386.25, 716],
            ["2015-12-28T09:20:00+0530", 1386.95, 1389.95, 1386.95, 1389, 727],
            ["2015-12-28T09:21:00+0530", 1389, 1392.95, 1389, 1392.95, 291],
            ["2015-12-28T09:22:00+0530", 1392.95, 1393, 1392, 1392.95, 180],
            ["2015-12-28T09:23:00+0530", 1392.95, 1393, 1392, 1392.15, 1869]
            ...
            ["2016-01-01T13:22:00+0530", 1386.4, 1388, 1381.05, 1385.1, 788],
            ["2016-01-01T13:23:00+0530", 1385.1, 1389.1, 1383.85, 1385.5, 613],
            ["2016-01-01T13:24:00+0530", 1385.5, 1387, 1385.5, 1385.7, 212],
            ["2016-01-01T13:25:00+0530", 1387, 1387.95, 1385.3, 1387.95, 1208],
            ["2016-01-01T13:26:00+0530", 1387, 1387.55, 1385.6, 1386.25, 716],
            ["2016-01-01T13:27:00+0530", 1386.95, 1389.95, 1386.95, 1389, 727],
            ["2016-01-01T13:28:00+0530", 1389, 1392.95, 1389, 1392.95, 291],
            ["2016-01-01T13:29:00+0530", 1392.95, 1393, 1392, 1392.95, 180],
            ["2016-01-01T13:30:00+0530", 1392.95, 1393, 1392, 1392.15, 1869]
        ]
    }
}

URI parameters

parameter  
:instrument_token Identifier for the instrument whose historical records you want to fetch. This is obtained with the instrument list API.
:interval The candle record interval. Possible values are:
· minute
· day
· 3minute
· 5minute
· 10minute
· 15minute
· 30minute
· 60minute

Request parameters

parameter  
from yyyy-mm-dd formatted date indicating the start date of records.
to yyyy-mm-dd formatted date indicating the end date of records.

Response structure

The response is an array of records, where each record in turn is an array of the following values — [timestamp, open, high, low, close, volume].

Publisher JS Plugin

The Kite Publisher Javscript plugin lets you add one-click trade buttons to your webpage. It works like a basket combined with a payment gateway, where an inline popup opens on your webpage, guides the user through a trade, and lands the user back on your page. As described in the offset order execution section, it is possible to capture the request_token from this flow to start a Kite Connect session as well.

You can add one or more stocks to the basket (maximum 10) dynamically using the Javascript plugin, or embed simple static buttons using plain HTML.

Getting started

<script src="https://kite.trade/publisher.js?v=1"></script>

Include Kite Publisher on your webpage by pasting the following script tag at the end of your webpage, just before the closing </body> tag. You only need to include this once to render any number of buttons on a page.

Branded HTML5 buttons

<!--  A link that initiates a buy (market) of the SBIN stock //-->
<kite-button href="#" data-kite="your_api_key"
            data-exchange="NSE"
            data-tradingsymbol="SBIN"
            data-transaction_type="BUY"
            data-quantity="1"
            data-order_type="MARKET">Buy SBI stock</kite-button>

You can use the custom <kite-button> HTML5 tag to render branded Kite buttons that initiate a trade with a single click. The branded buttons work in a similar fashion to social media buttons, and you can include as many as you want on a page.

Custom HTML5 buttons

<!--  A link that initiates a buy (market) of the SBIN stock //-->
<a href="#" data-kite="your_api_key"
            data-exchange="NSE"
            data-tradingsymbol="SBIN"
            data-transaction_type="BUY"
            data-quantity="1"
            data-order_type="MARKET">Buy SBI stock</a>


<!--  A button that initiates a sell (limit) of the RELIANCE stock //-->
<button data-kite="your_api_key"
        data-exchange="NSE"
        data-tradingsymbol="RELIANCE"
        data-transaction_type="SELL"
        data-quantity="1"
        data-order_type="LIMIT"
        data-price="100">Buy RELIANCE</button>

You can use the HTML5 data attributes on any HTML element and turn it into a trade button which gets invoked with a single click. The examples on the right show a link and a button being turned into trade buttons.

Generating dynamic buttons with Javascript

<!-- A Kite button will be generated inside this container //-->
<p id="default-button"> </p>

<!-- The basket will be linked to this element's onClick //-->
<button id="custom-button">Buy the basket</button>

<!-- Include the plugin //-->
<script src="https://kite.trade/publisher.js?v=1"></script>

<script>
// Only run your custom code once KiteConnect has fully initialised.
// Use KiteConnect.ready() to achieve this.
KiteConnect.ready(function() {
    // Initialize a new Kite instance.
    // You can initialize multiple instances if you need.
    var kite = new KiteConnect("your_api_key");

    // Add a stock to the basket
    kite.add({
        "exchange": "NSE",
        "tradingsymbol": "INFY",
        "quantity": 5,
        "transaction_type": "BUY",
        "order_type": "MARKET"
    });

    // Add another stock
    kite.add({
        "exchange": "NSE",
        "tradingsymbol": "SBIN",
        "quantity": 1,
        "order_type": "LIMIT",
        "transaction_type": "SELL",
        "price": 105
    });

    // Register an (optional) callback.
    kite.finished(function(status, request_token) {
        alert("Finished. Status is " + status);
    });

    // Render the in-built button inside a given target
    kite.renderButton("#default-button");

    // OR, link the basket to any existing element you want
    kite.link("#custom-button");
});
</script>

You can create a basket of stocks and get the plugin to render a Kite button that executes it, or link the basket to your own button (or any HTML element).

The plugin loads it’s assets asynchronously, so it’s important that you initialise your custom KiteConnect calls after it has fully loaded. You need to use the KiteConnect.ready() function to achieve this.

Parameters

parameter  
exchange Exchange segment of the instrument to trade. NSE, BSE, MCX, NFO, BFO, or CDS
tradingsymbol The full exchange trading symbol of the instrument to trade eg: INFY, NIFTY16JANFUT, NIFTY15JAN8500CE, 532617 etc.
transaction_type BUY or SELL
order_type MARKET, LIMIT, SL or SL-M
quantity Net quantity to trade
price Limit price for LIMIT and SL orders
trigger_price Trigger price for SL-M orders
product MIS, CNC, or NRML

Methods

method arguments  
KiteConnect.ready() function() Safe wrapper for all API calls that waits asynchronously for all assets to load.
add() entry Adds an object literal {} with the parameters mentioned in the previous section represeting a single trading entry to the basket.
get() Returns an array[] of all added entries.
count() Returns the number of added entries.
setOption() key, value Sets the value for certain supported keys.
redirect_url A redirect URL to override the registered Kite Connect redirect URL. The value can be a single ’#’, a 127.0.0.1 url for testing, or a fully qualified URL belonging to the same domain as the registered URL.
renderButton() element_selector Renders a branded Kite button in the given target element, which when clicked, will start the transaction in an overlay popup. element_selector is an HTML selector, for example, #buy-button, .buttons etc.
link() element_selector Links the basket to the given HTML element, which when clicked, will start the transaction in an overlay popup. element_selector is an HTML selector, for example, #buy-button, .buttons etc.
html() Returns a serialized HTML form with the necessary hidden fields and the basket payload which can be written to the document body and submitted to initiate the transaction.
finished() function(status, request_token) Register a callback which is triggered after order placement is finished.

Mobile and Desktop apps

As described in the authentication section, the login flow ends with a redirect to your registered redirect_url with the request_token after a successful login. When this redirect end point is a web application, it is easy to get the token and exchange it for an access_token. When it’s a desktop or a mobile application without a server backend, the approach is different.

Similar to how Google and Facebook authentication flows work on mobile apps, you will need to open a webview (browser view) component from within your application pointing to the login url. The entire login flow will happen within this webview. As it’s an in-app component, you will have a certain level of control over it, including reading the current location (URL) of the component. It is then possible to monitor location changes using a change event or a poll timer to determine when the redirect happens, and extract the request_token from the URL.

In essence:

  • Register a redirect_url with us when you apply for your API credentials. This can be a blank page even. Eg: https://yoursite.com/kite-redirect. For personal desktop apps, you can run a local web server and use 127.0.0.1 as the redirect_url’s’ host.
  • Start the login flow by opening an webview component within your desktop or mobile application https://kite.trade/connect/login?api_key=xxx
  • From within your application, monitor changes in the URL of the component as the login happens
  • When the URL changes to https://yoursite.com/kite-redirect?request_token=yyy&status=zzz, extract the request_token and status_from the URL and close the webview component.

Changelog

Date Change
2016-03-12 Added new column exchange_token to the instrument list CSV API.
2016-05-07 /orders call and bracket order modification and cancellation now involve the new parent_order_id parameter.
2016-07-02 Several new fields added to the Webhooks payload (exchange_timestamp, order_type, product, unfilled_quantity, validity).