Brokerage API Document
Field Value Description
Wtoken WTOKEN Wtoken of scrip (Optional)
Order price in decimal value (Keep 4 decimal
Price PRICE places for Commodity, Currency and 2
decimal places for all other segments)
Quantity QTY Quantity of the scrip in multiples of lots
display_segment EQ Segment type
DERIVATIVE
COMMODITIES
CURRENCY
lot_size LOT_SIZE Size of Lot
display_fno_eq OPT OPT for Option contract
FUT
FUT for Future contract, Blank string for
Equity contract
order_type ID
DLV ID for Intraday order.DLV for Delivery order
order_action Buy Buy for Buy order
Sell Sell for Sell order
market_exchange NSE Exchange of contract
BSE
MCX
NCDEX
Display name of construct which contains
Script SCRIPT_NAME scrip name, strike price, opt/fut, expiry date
(Optional)
Description of Result items Array
{
"percentage_static_rates": {
"brokerage": "0.49%",
"transaction_charges": "0.00345%",
"stt_ctt": "0.1%",
"sebi_tax": "0.0001%",
"stamp_duty": "0.015%",
"gst": "18%"
},
"value_static_rates": {
"brokerage": 88.2,
"transaction_charges": 0.62,
"stt_ctt": 18,
"sebi_tax": 0.02,
"stamp_duty": 3,
"gst": 15.99,
"total_charges": 125.83
},
"display_rates": {
"brokerage_str": "0.49% or Rs. 21 per order whichever is higher",
"transaction_charges_str": "0.62",
"stt_ctt_str": "18",
"sebi_tax_str": "0.02",
"stamp_duty_str": "3",
"gst_str": "15.99",
"total_charges_str": "125.83"
}
}
Response of Success example
{
"result_items": [
{
"percentage_static_rates": [ "2.5%", "0.00345%", "0.1%", "0.0001%",
"0.015%", "18%" ],
"value_static_rates": [ 986.88, 1.36, 39.48, 0.04, 6, 177.89, 1211.65 ],
"display_rates": [ "2.5% or Rs. 21 per order whichever is higher",
"1.36", "39.48", "0.04", "6", "177.89", "1211.65" ]
},
{
"percentage_static_rates": [ "2.5%", "0.00345%", "0.1%", "0.0001%",
"0.015%", "18%" ],
"value_static_rates": [ 986.88, 1.36, 39.48, 0.04, 6, 177.89, 1211.65 ],
"display_rates": [ "2.5% or Rs. 21 per order whichever is higher",
"1.36", "39.48", "0.04", "6", "177.89", "1211.65" ]
},
{
"error": "inactive_segment",
"error_description": "As per our records, in your account the segment
selected for this stock is inactive and hence we are unable to show charges
related to this order. You can activate the segment by visiting the profile
section."
}
],
"sum_total_charges": [ 1973.76, 2.72, 78.96, 0.08, 12, 355.78, 2423.3 ],
"result_count": {
"success": 2,
"error": 1,
"error_message": "We are unable to calculate the charges for this order
since the trading segment you have selected for one of the scrips / contracts
is possibly inactive. You can still continue placing your order (for other
scrips) and check your charges in your contract note or you can check
individual scrip-wise charges by entering the order information on the
individual scrip order page"
}
}
Documentation
Margin API:
Margin API takes consumer key, session token and access token as header
inputs, with no data body, to return complete margin details associated
with the client, classified segment-wise.
Complete Margin Details
https://tradeapi.kotaksecurities.com/apim/margin/1.0/margin
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Order API:
The order API is concerned with all order placements, modifications, and
cancellations. The following types of orders are available at this time. Their
respective endpoints are listed as follows:
TYPES:
Normal
Order: https://tradeapi.kotaksecurities.com/apim/orders/1.0/order/
normal
MTF Order: https://tradeapi.kotaksecurities.com/apim/orders/1.0/order/
mtf
SOR Order: https://tradeapi.kotaksecurities.com/apim/orders/1.0/order/
sor
MIS Order: https://tradeapi.kotaksecurities.com/apim/orders/1.0/order/
mis
For each of the above endpoints, the request type determines whether
the request is an order placement, modification or cancellation (POST,
PUT, and DELETE respectively). For order placement, an input parameter
labelled 'instrument token' is listed. This refers to a unique number that
dictates to the server the instrument listing that the order is placed in.
Each listing on each exchange has a unique token. These values change
over time, and the latest list can be obtained via the scrip master
generation URL.
Place (places a new order)
Request type: POST
Request body parameters:
Headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Data:
Attribute Name Datatype Description
"instrumentToken" Number Numeric token assigned to each scrip
"transactionType" String "BUY" or "SELL"
"quantity" Number Quantity of shares
"price" Number 0 for market order, non-zero for limit
"validity" String "GFD" or "IOC"
"variety" String "REGULAR" or "AMO"
"disclosedQuantity" Number Input disclosed quantity
"triggerPrice" Number Price at which order will be triggered
"tag" String "string"
Modify (modify an existing pending order using order ID to identify it)
Request type: PUT
Request body parameters:
Headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Data:
Attribute Name Datatype Description
"orderId" String Order ID of the order to be modified
"quantity" Number Quantity of shares
"price" Number 0 for market order, non-zero for limit
"validity" String "GFD" or "IOC"
"disclosedQuantity" Number Input disclosed quantity
"triggerPrice" Number Price at which order will be triggered
Cancel (cancel an existing pending order using order ID)
Request type: DELETE
Request body parameters:
Headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
*NOTE: for Order cancellation, the ORDER ID is to be added to the API
request URL, instead of the header.
For example, to cancel a NORMAL order type, the url will be:
https://tradeapi.kotaksecurities.com/apim/orders/1.0/order/normal/\
<order ID\>
Positions API:
Positions API takes consumer key, session token and access token as
header inputs, with no data body, to return positions associated with the
client
Todays Position (gets the day's positions)
https://tradeapi.kotaksecurities.com/apim/positions/1.0/positions/todays
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Open Positions (gets currently open positions)
https://tradeapi.kotaksecurities.com/apim/positions/1.0/positions/open
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Stock Positions (gets stock positions for client eligible to be sold)
https://tradeapi.kotaksecurities.com/apim/positions/1.0/positions/stocks
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Quotes API:
Quotes APIs take consumer key, session token and access token as
header inputs, with no data body, to return instantaneous quotes for any
particular scrip associated with the instrument token passed into the url.
The instrument token for the scrip can be retrieved using the scrip master
generation URL.
Depth (returns the disclosed depth of existing orders for the scrip)
https://tradeapi.kotaksecurities.com/apim/quotes/v1.0/depth/
instruments/ \<instrument token\>
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
OHLC Quote (open-high-low-close information for the scrip)
https://tradeapi.kotaksecurities.com/apim/quotes/v1.0/ohlc/instruments/
\<instrument token\>
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
LTP Quote (last traded price for the scrip)
https://tradeapi.kotaksecurities.com/apim/quotes/v1.0/ltp/instruments/ \
<instrument token\>
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Full Details Quote (general quote details for the scrip)
https://tradeapi.kotaksecurities.com/apim/quotes/v1.0/instruments/ \
<instrument token\>
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Reports API:
Reports API takes consumer key, session token and access token as
header inputs, with no data body, to return order book associated with
the client, or if order ID is specified, the order status history.
Order Details (returns the general details of all orders placed by the
client)
https://tradeapi.kotaksecurities.com/apim/reports/1.0/orders
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Expanded Order Details (when order ID is specified in the API URL, it
returns the history of the order associated with the order ID instead of the
general book)
https://tradeapi.kotaksecurities.com/apim/reports/1.0/orders/\<order ID\
>
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Trade Details (returns the general details of all trades made by the client)
https://tradeapi.kotaksecurities.com/apim/reports/1.0/trades
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Expanded Trade Details (when order ID is specified in the API URL, it
returns the history of the trade associated with the order ID instead of the
general book)
https://tradeapi.kotaksecurities.com/apim/reports/1.0/trades/ \<order ID\
>
Request type: GET
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'sessionToken': '\<your session token\>',
'Authorization': '\<your access token\>',
Session API:
The first step to logging in is to generate the One-Time Token, which will
later be required for the 2-factor authentication function. For this you
must input your user ID and password associated with your Kotak
securities account as data, along with your access token, consumer key, IP
address, and app ID as header inputs (latter two being optional inputs for
clients):
Generate OTT
https://tradeapi.kotaksecurities.com/apim/session/1.0/session/login/
userid
Request type: POST
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'ip': '\<ip address\>',
'appId': '\<your app ID\>',
'Content-Type': 'application/json',
'Authorization': '\<your access token\>',
Data:
Attribute Name Datatype Description
userid String Your trading account user ID
password String Your trading account password
Once the OTT is generated by the function above, it is used as header
input for the 2-Factor Authentication function, along with your access
token, consumer key, IP address, and app ID as header inputs (latter two
being optional inputs for clients). One can choose between two possible
2FA functions, the first of which (as shown below) requires only your user
ID as input data (meaning no manual intervention is required). The other
option requires your user ID and your access code as input data. The
access code can be generated on any Kotak securities login portal (for
example, website), or by the GET request of the same end-point. Once the
access code is generated, it remains valid throughout the day. both
options are listed below:
Generate Session Token(2 Factor Authentication) (without access
code, requires no change in inputs)
https://tradeapi.kotaksecurities.com/apim/session/1.0/session/2FA/
oneTimeToken
Request type: POST
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'oneTimeToken': '\<Your One Time Token(output from previous function)\>',
'ip': '\<ip address\>',
'appId': '\<your app ID\>',
'Content-Type': 'application/json',
'Authorization': '\<your access token\>',
}
Data:
Attribute Name Datatype Description
userid String Your trading account user ID
Once the above function is executed you will have your validated session
token iin your response body that can be used as header input for all
subsequent API requests.
Generate Session Token(2 Factor Authentication) (with access code,
needs to be updated daily)
https://tradeapi.kotaksecurities.com/apim/session/1.0/session/2FA/
accesscode
Request type: POST
Request body parameters:
Headers = {
'accept': 'application/json',
'consumerKey': '\<your consumer key\>',
'oneTimeToken': '\<Your One Time Token(output from previous function)\>',
'ip': '\<ip address\>',
'appId': '\<your app ID\>',
'Content-Type': 'application/json',
'Authorization': '\<your access token\>',
Data:
Attribute
Datatype Description
Name
userid String Your trading account user ID
Your Kotak securities access code (sent to
accessCode String
mobile)
Once the above function is executed you will have your validated session
token iin your response body that can be used as header input for all
subsequent API requests.
Tokens Api
Generate access tokens using grant_type parameter
grant_type=password
URL
https://tradeapi.kotaksecurities.com/token
Method
POST
Request header
Authorization : Basic base64(client-key:client-secret)
Request body (application/x-www-form-urlencoded)
grant_type=password
username=<your_username>
password=<your_password>
Sample CURL
curl -k -X POST https://tradeapi.kotaksecurities.com/token --header
"Authorization: Basic Base64(consumer-key:consumer-secret)" --header
'Content-Type: application/x-www-form-urlencoded' --data-urlencod
"grant_type=password" --data-urlencod
"username=<username>&password=<password>"
Sample Response
{
"access_token": "4e125cd8-4e05-3ba4-b48c-eb1fe1c40743",
"refresh_token": "ad51d5e6-b3c3-39e4-adf3-5b4f17786adb",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
----------------------------------------------
grant_type=refresh_token
URL
https://tradeapi.kotaksecurities.com/token
Method
POST
Request header
Authorization : Basic base64(client-key:client-secret)
Request body (application/x-www-form-urlencoded)
grant_type=refresh_token
refresh_token=<refresh_token>
Sample CURL
curl -k -X POST https://tradeapi.kotaksecurities.com/token --header
"Authorization: Basic Base64(consumer-key:consumer-secret)" --header
'Content-Type: application/x-www-form-urlencoded' --data-urlencode
'grant_type=refresh_token' --data-urlencode
'refresh_token=<refresh_token>'
Sample Response
"access_token": "803a74b0-47e2-34e7-b1af-66eb01ad4d7b",
"refresh_token": "d668eb08-0751-33fc-8bc1-f6ebfb557418",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
----------------------------------------------
grant_type=client_credentials
URL
https://tradeapi.kotaksecurities.com/token
Method
POST
Request header
Authorization : Basic base64(client-key:client-secret)
Request body (application/x-www-form-urlencoded)
grant_type=client_credentials
Sample CURL
curl -k -X POST https://tradeapi.kotaksecurities.com/token --header
"Authorization: Basic Base64(consumer-key:consumer-secret)" --header
'Content-Type: application/x-www-form-urlencoded' --data-urlencod
"grant_type=client_credentials"
Sample Response
"access_token": "77c74dea-c463-3892-8667-36a0c7c7e890",
"scope": "am_application_scope default",
"token_type": "Bearer",
"expires_in": 3600
----------------------------------------------
ks_api_client
No description provided
API version: 1.0.1
Package version: 1.1.0
Requirements.
Python 2.7 and 3.4+
Installation & Usage
pip install
If the python package is hosted on a repository, you can install directly using:
pip install -e
"git+https://github.com/paramatrixtech/ksapi.git#egg=ks_api_client&subdirectory=./
python"
(you may need to run pip with root permission: sudo pip install -e
"git+https://github.com/paramatrixtech/ksapi.git#egg=ks_api_client&subdirectory=./
python")
Then import the package:
import ks_api_client
Setuptools
Install via Setuptools.
python setup.py install --user
(or sudo python setup.py install to install the package for all users)
Then import the package:
import ks_api_client
Getting Started
Please follow the installation procedure and then run the following:
from ks_api_client import ks_api
# Defining the host is optional and defaults to https://sbx.kotaksecurities.com/apim
# See configuration.py for a list of all supported configuration parameters.
client = ks_api.KSTradeApi(access_token = "", userid = "", consumer_key = "",ip =
"127.0.0.1", app_id = "", \
hosts=["https://tradeapi.kotaksecurities.com/apim"],
proxy_url = '', proxy_user = '', \
proxy_pass = '', consumer_secret = "")
# Get session for user
client.login(password = "")
#Generated session token
client.session_2fa(access_code = "")
# Place an order
client.place_order(order_type = "O", instrument_token = 727, transaction_type =
"BUY",\
quantity = 1, price = 0, disclosed_quantity = 0, trigger_price =
0,\
validity = "GFD", variety = "REGULAR", tag = "string", product =
"NORMAL", smart_order_routing="string")
client.place_order(order_type = "N", instrument_token = 727, transaction_type =
"BUY",\
quantity = 1, price = 0, disclosed_quantity = 0, trigger_price =
0,\
validity = "GFD", variety = "REGULAR", tag = "string")
# Modify an order
client.modify_order(order_id = "", price = 0, quantity = 1, disclosed_quantity = 0,
trigger_price = 0, validity = "GFD")
# Cancel an order
client.cancel_order(order_id = "")
# Get Report Orders
client.order_report()
# Get Report Orders for order id
client.order_report(order_id = "")
# Get FNO Report Orders for order id
client.order_report(order_id = "", is_fno = "Y")
# Get Trade Report
client.trade_report()
# Get Trade Report for order id
client.trade_report(order_id = "")
# Get FNO Trade Report for order id
client.trade_report(order_id = "", is_fno = "Y")
# Get Margin required
order_info = [
{"instrument_token": 727, "quantity": 1, "price": 1300, "amount": 0,
"trigger_price": 1190},
{"instrument_token": 1374, "quantity": 1, "price": 1200, "amount": 0,
"trigger_price": 1150}
]
client.margin_required(transaction_type = "BUY",order_info = order_info)
# Get Margin
client.margin()
# Get Positions
client.positions(position_type = "TODAYS")
# Get Quote details
client.quote(instrument_token = 110)
# Get Historical data
client.history("historicalprices",{"exchange":"bse","cocode":"476","fromdate":"01-
jan-2014","todate":"08-oct-2015"})
client.history("historicalprices-unadjusted",
{"exchange":"bse","co_code":"476","date":"16-Jun-2016"})
client.history("NSEFNO_HistoricalContinuousChart",{"symbol":"HDFC","expiry type":
"near"})
client.history("LiveorEODHistorical",
{"exchange":"BSE","co_code":"5400","period":"Y","cnt":"3"})
# Subscribe to instrument token's stream.
def callback_method(message):
print(message)
print("Your logic/computation will come here.")
client.subscribe(input_tokens="745,754", callback=callback_method)
# Unsubscribe from streaming service.
client.unsubscribe()
#Terminate user's Session
client.logout()
Documentation for API Endpoints
All URIs are relative to https://sbx.kotaksecurities.com/apim
Class Method Description
ks_api.KSTradeAp
SessionApi Initialise Session
i
SessionApi login Login using Userid
Class Method Description
SessionApi session_2fa Generate final Session Token
OrderApi place_order Place a New order
OrderApi modify_order Modify an existing order
OrderApi cancel_order Cancel an order
ReportsApi order_report Get order report
ReportsApi trade_report Get trade report
Get Margin Required for an order by amount or
MarginApi margin_required
quantity.
MarginApi margin Get all calculated margins.
PositionsApi positions Get's Open position.
QuoteApi quote Get Quote details
HistoricalApi history Get historical data.
StreamingAp Subscribe to streaming api of specified instrument
subscribe
i tokens.
StreamingAp
unsubscribe Unsubscribe from streaming api.
i
SessionApi logout Invalidate Session Token