NAV Navbar
Logo
cURL javascript

Introduction

Upstox API is a set of rest APIs that provide data required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (using Websocket), and more, with the easy to understand API collection.

To use the APIs we provide SDKs in the following languages:

Language Docs Repository
Javascript NodeJS docs NodeJS source
Python Python docs Python source

We also have authorized third-party libraries that cover other languages:

Language Docs Library
.NET Library docs HowUTrade .NET Library

All requests are over HTTPS and the requests are sent with the content-type ‘application/json’. Developers have the option of choosing the response type as JSON or CSV for a few API calls.

To be able to use these APIs you need to create an App in the Developer Console and generate your apiKey and apiSecret. You can use a redirect URL which will be called after the login flow.

It is highly recommended that you do not embed the apiSecret in your frontend app. Create a remote backend which does the handshake on behalf of the frontend app. Marking the apiSecret in the frontend app will make your app vulnerable to threats and potential issues.

Create an app

Create an app with the App Type API Trading in the Developer Console. Give your app a name, a description and a redirect URI. This redirect URI is used after login to pass an authorization code.

Note that if you are distributing your app to the public, please ensure that the redirect URI is stored in your server and not in your client-side application!

API key and secret

Once your app is created, you will get an API KEY and API SECRET. Your API KEY and API SECRET are used to identify the source of the connection and ensure that it is really you. Your API KEY can be distributed on the client app but your API SECRET should be stored on your backend server.

Installation

npm install --save upstox
pip install python

To facilitate easy use of the APIs, we have developed a set of libraries for different languages. If you are using one of those programming languages, you can use the library functions for the calls/functions listed below.

Authorization


var Upstox = require("upstox");

var upstox = new Upstox("{your_api_key}");

var loginUrl = upstox.getLoginUri("{your_redirect_uri}");

var params = {
    "apiSecret" : "{your_api_secret}",
    "code" : "{your_code_generated_in_login}",
    "grant_type" : "authorization_code",
    "redirect_uri" : "{your_redirect_uri}"
};

var accessToken;

upstox.getAccessToken(params)
    .then(function(response) {
      accessToken = response.access_token;
    })
    .catch(function(err) {
        // handle error 
    });

upstox.setToken(accessToken);

curl \
-u {your_api_key}:{your_api_secret} \
-H 'Content-Type: application/json' \
-H 'x-api-key: {your_api_key}' \
-d '{"code" : "{code_from_login_response}", "grant_type" : "authorization_code", "redirect_uri" : "{your_redirect_uri}"}' \
-X POST 'https://api.upstox.com/index/oauth/token'

code -- code generated on successful login 

Authentication is done via oAuth process. Initial authentication requires access to a web browser as you would have to authorize the program using your client ID (six digit UCC), trading password and year of birth. Whether your program runs on a GUI or a console, you would always have to access the web browser to create an access token which then allows you to use the API. The access token has a validity of 24 hours so you only have to authenticate yourself once during the day. (Note: All access tokens are cleared between 5 to 6 AM in the morning. We recommend you regenerate your access token after 6 AM). Once you generate your access token, you can store it and bypass authentication for subsequent connects.

  1. Open your web browser and go to the login URL. Your login URL is https://api.upstox.com/index/dialog/authorize?apiKey={your_api_key}&redirect_uri={your_redirect_uri}&response_type=code. On the libraries, you can get this URL by setting the apiKey and then calling the getLoginUri function with the redirect_uri as a parameter. Note that the redirect_uri used here must match the redirect_uri specified in your App settings on the Developer Console.
  2. Once redirected, it opens the Upstox login page where you enter your UCC, password and date of birth to authenticate yourself.
  3. Login authentication screen. Your Year of Birth is your passcode.
  4. After authentication it asks for your permission to allow the app to access your credentials.
  5. Clicking Accept will then take you to the redirect URI with the authorization code as a parameter
  6. Once you accept the permissions, Upstox redirects you to the redirectUri which was sent in step 1 with a parameter called code. This step should be done in your backend app server.
  7. With the newly generated code, you need to now generate an access token. To get the access token, you need to call the following URL https://api.upstox.com/index/oauth/token and pass the following parameters: api_key, redirect_uri, code, grant_type. This call is shown on the right side in the code tab.

    Note, the grant_type value must always be authorization_code. Do not change this value.

  8. This returns you the accessToken to your backend app server.
  9. You return this accessToken to your app via the response of your redirectUri. For future requests to the app, use the accessToken as your authorization bearer token. If you are using the library, set the accessToken received to Upstox object by using the ‘setAccessToken’ method. This is enable all your future requests to use this accessToken and provide the necessary permissions. The accessToken is valid until the next trading day.

Users

Profile

upstox.getProfile()
  .then(function (response) {
  })
  .catch(function(error){
      done(error);
  });


Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-16T11:00:04+05:30",
  "message": "success",
  "data": {
    "client_id": "240001",
    "name": "Raj Prakash",
    "email": "raj.prakash@mymail.com",
    "phone": "9820098200",
    "exchanges_enabled": [
      "BSE_EQ",
      "NSE_EQ",
      "NSE_FO",
      "MCX_FO",
      "NCD_FO",
      "BCD_FO"
    ],
    "products_enabled": [
      "OCO",
      "D",
      "CO",
      "I"
    ]
  }
}


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/index/profile'

Sample response
{ 
   "code":200,
   "status":"OK",
   "timestamp":"2017-07-18T10:32:02+05:30",
   "message":"success",
   "data":{ 
      "client_id": "240001",
      "name": "Raj Prakash",
      "email": "raj.prakash@mymail.com",
      "phone": "9820098200",
      "exchanges_enabled":[ 
         "BSE_EQ",
         "NSE_EQ",
         "NSE_FO",
         "MCX_FO",
         "NCD_FO",
         "BCD_FO"
      ],
      "products_enabled":[ 
         "OCO",
         "D",
         "CO",
         "I"
      ]
   }
}

This allows to fetch the complete information of the user who is logged in.

Response attributes

attribute datatype description
client_id string Uniquely identifies the user
name string Name of the user
email string E-mail address of the user
phone string Phone number of the user
exchanges_enabled string Lists the exchanges to which the user has access
products_enabled array Lists the products types to which the user has access

Balance

upstox.getBalance()
  .then(function (response) {
  })
  .catch(function (error) {
      done();
  })


Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:35:57+05:30",
  "message": "success",
  "data": {
    "equity": {
      "used_margin": 67.2125,
      "unrealized_mtm": 0,
      "realized_mtm": 0,
      "payin_amount": 0,
      "span_margin": 0,
      "adhoc_margin": 0,
      "notional_cash": 0,
      "available_margin": 99320.78,
      "exposure_margin": 0
    },
    "commodity": {
      "used_margin": 0,
      "unrealized_mtm": 0,
      "realized_mtm": 0,
      "payin_amount": 0,
      "span_margin": 0,
      "adhoc_margin": 0,
      "notional_cash": 0,
      "available_margin": 5200.45,
      "exposure_margin": 0
    }
  }
}

upstox.getBalance({"type": "commodity"})
  .then(function (response) {
  })
  .catch(function (error) {
      done();
  })


Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:35:57+05:30",
  "message": "success",
  "data": {
    "commodity": {
      "used_margin": 0,
      "unrealized_mtm": 0,
      "realized_mtm": 0,
      "payin_amount": 0,
      "span_margin": 0,
      "adhoc_margin": 0,
      "notional_cash": 0,
      "available_margin": 5200.45,
      "exposure_margin": 0
    }
  }
}


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/profile/balance'

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:35:57+05:30",
  "message": "success",
  "data": {
    "equity": {
      "used_margin": 67.2125,
      "unrealized_mtm": 0,
      "realized_mtm": 0,
      "payin_amount": 0,
      "span_margin": 0,
      "adhoc_margin": 0,
      "notional_cash": 0,
      "available_margin": 99320.78,
      "exposure_margin": 0
    },
    "commodity": {
      "used_margin": 0,
      "unrealized_mtm": 0,
      "realized_mtm": 0,
      "payin_amount": 0,
      "span_margin": 0,
      "adhoc_margin": 0,
      "notional_cash": 0,
      "available_margin": 5200.45,
      "exposure_margin": 0
    }
  }
}

curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/profile/balance/commodity'

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:35:57+05:30",
  "message": "success",
  "data": {
    "commodity": {
      "used_margin": 0,
      "unrealized_mtm": 0,
      "realized_mtm": 0,
      "payin_amount": 0,
      "span_margin": 0,
      "adhoc_margin": 0,
      "notional_cash": 0,
      "available_margin": 5200.45,
      "exposure_margin": 0
    }
  }
}

Shows the balance of the user in equity and commodity market

Request Parameter

parameter
type type of the users account
  • security
  • commodity
If type is not entered the users gets both the balances

Response attributes

attribute datatype description
used_margin number Positive values denote the amount blocked into a Open order or position. Negative value denotes the amount being released.
unrealized_mtm number Day PnL generated against open positions
realized_mtm number Day PnL generated against closed positions
payin_amount number Instant payin will reflect here
span_margin number Amount blocked on futures and options towards SPAN
adhoc_margin number Payin amount credited through a manual process
notional_cash number The amount maintained for withdrawal
available_margin number Total margin available for trading
exposure_margin number Amount blocked on futures and options towards Exposure

Positions

upstox.getPositions()
.then(function (response) {
})
.catch(function(error){
    done(error);
});

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:40:04+05:30",
  "message": "success",
  "data": [
    {
      "exchange": "NSE_EQ",
      "product": "I",
      "symbol": "RELIANCE",
      "token": 2885,
      "buy_amount": 1344.25,
      "sell_amount": 0,
      "buy_quantity": 1,
      "sell_quantity": 0,
      "cf_buy_amount": 0,
      "cf_sell_amount": 0,
      "cf_buy_quantity": 0,
      "cf_sell_quantity": 0,
      "avg_buy_price": 1344.25,
      "avg_sell_price": 0.00,
      "net_quantity": 1,
      "close_price": 1350.45,
      "realized_profit": 0.00,
      "unrealized_profit": 3.09
    }
  ]
}


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/profile/positions'

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:40:04+05:30",
  "message": "success",
  "data": [
    {
      "exchange": "NSE_EQ",
      "product": "I",
      "symbol": "RELIANCE",
      "token": 2885,
      "buy_amount": 1344.25,
      "sell_amount": 0,
      "buy_quantity": 1,
      "sell_quantity": 0,
      "cf_buy_amount": 0,
      "cf_sell_amount": 0,
      "cf_buy_quantity": 0,
      "cf_sell_quantity": 0,
      "avg_buy_price": 1344.25,
      "avg_sell_price": 0.00,
      "net_quantity": 1,
      "close_price": 1350.45,
      "realized_profit": 0.00,
      "unrealized_profit": 3.09
    }
  ]
}

Fetches the current positions for the user for the current day

Response attributes

attribute datatype description
exchange string Exchange to which the order is associated
product string Shows if the order was either Intraday, Delivery, CO or OCO
symbol string Shows the trading symbol which could be a combination of symbol name, instrument, expiry date etc
token number Token number of the order
buy_amount number Amount at which the qty is bought during the day
sell_amount number Amount at which the qty is sold during the day
buy_quantity number Qty bought during the day
sell_quantity number Qty sold during the day
cf_buy_amount number Amount at which the qty was bought in the previous session
cf_sell_amount number Amount at which the qty was sold in the previous session
cf_buy_quantity number Qty bought in the previous session
cf_sell_quantity number Qty sold short in the previous session
avg_buy_price number Average price at which the day qty was bought
avg_sell_price number Average price at which the day qty was sold
net_quantity number Quantity left after nullifying Day and CF buy quantity towards Day and CF sell quantity
close_price number Close price of the previous trading session
realized_profit number Day PnL generated against closed positions
unrealized_profit number Day PnL generated against open positions

Holdings

upstox.getHoldings()
.then(function (response) {
})
.catch(function(error){
    done(error);
});

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:42:02+05:30",
  "message": "success",
  "data": [
    {
      "instrument": [
        {
          "exchange": "NSE_EQ",
          "symbol": "DAAWAT",
          "token": 13816
        },
        {
          "exchange": "BSE_EQ",
          "symbol": "DAAWAT",
          "token": 532783
        }
      ],
      "product": "D",
      "collateral_type": "WC",
      "cnc_used_quantity": 0,
      "quantity": 1,
      "collateral_qty": 0,
      "haircut": 25
    }
  ]
}


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/profile/holdings'

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:42:02+05:30",
  "message": "success",
  "data": [
    {
      "instrument": [
        {
          "exchange": "NSE_EQ",
          "symbol": "DAAWAT",
          "token": 13816
        },
        {
          "exchange": "BSE_EQ",
          "symbol": "DAAWAT",
          "token": 532783
        }
      ],
      "product": "D",
      "collateral_type": "WC",
      "cnc_used_quantity": 0,
      "quantity": 1,
      "collateral_qty": 0,
      "haircut": 25
    }
  ]
}

Fetches the holdings which the user has bought/sold in previous trading sessions

Response attributes

attribute datatype description
exchange string Exchange to which the holding is associated
symbol string Shows the trading symbol which could be a combination of symbol name, instrument, expiry date etc
token number Unique identifier of a security in BSE and NSE
product string Shows if the order was either Intraday, Delivery, CO or OCO
collateral_type string Category of collateral assigned by RMS
cnc_used_quantity number Quantity either blocked towards open or completed order
quantity number The total holding qty
collateral_qty number Quantity marked as collateral by RMS on users request
haircut number This is the haircut percentage applied from RMS (applicable incase of collateral)

Master Contracts

//the parameter is accepted as json 
upstox.getMasterContract({
  "exchange": "nse_eq"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-07-18T10:45:33+05:30",
  "message": "success",
  "data": [
      "exchange,token,parent_token,symbol,name,closing_price,expiry,strike_price,tick_size,lot_size,instrument_type,isin",
      "NSE_EQ,16921,,20MICRONS,20 MICRONS LTD,39.7,,,5,1,EQUITY,INE144J01027",
      "NSE_EQ,11774,,3IINFOTECH,3I INFOTECH LTD.,4.45,,,5,1,EQUITY,INE748C01020",
      "NSE_EQ,474,,3MINDIA,3M INDIA LIMITED,13686.2,,,5,1,EQUITY,INE470A01017",
      "NSE_EQ,11868,,63MOONS,63 MOONS TECHNOLOGIES LTD,62.95,,,5,1,EQUITY,INE111B01023",
      "NSE_EQ,11058,,8KMILES,8K MILES SOFT SERV LTD,541.6,,,5,1,EQUITY,INE650K01021",
      "NSE_EQ,20906,,A2ZINFRA,A2Z INFRA ENGINEERING LTD,43.1,,,5,1,EQUITY,INE619I01012",
      "NSE_EQ,11341,,AIFL,ASHAPURA INTI FASHION LTD,401.4,,,5,1,EQUITY,INE428O01016",....
  ]
}


upstox.getMasterContract({
  "exchange": "nse_eq",
  "token": 2885
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});

Sample response
{ 
   "code":200,
   "status":"OK",
   "timestamp":"2017-07-18T10:47:32+05:30",
   "message":"success",
   "data":{ 
      "lower_circuit":1396.6,
      "upper_circuit":1706.9,
      "instrument_name":"EQUITY",
      "gn":-1,
      "gd":-1,
      "pn":-1,
      "pd":-1,
      "circuit_limit":"1396.60-1706.90",
      "status":"Eligible",
      "yearly_low":930,
      "yearly_high":1550,
      "symbol":"RELIANCE",
      "lot_size":1,
      "exchange":"NSE_EQ",
      "closing_price":1551.75,
      "open_interest":"",
      "tick_size":5,
      "name":"RELIANCE INDUSTRIES LTD",
      "token":2885,
      "isin":"INE002A01018"
   }
}


upstox.getMasterContract({
  "exchange": "nse_eq",
  "symbol": "infy"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});

Sample response
{ 
   "code":200,
   "status":"OK",
   "timestamp":"2017-07-18T10:49:33+05:30",
   "message":"success",
   "data":{ 
      "lower_circuit":885.65,
      "upper_circuit":1082.45,
      "instrument_name":"EQUITY",
      "gn":-1,
      "gd":-1,
      "pn":-1,
      "pd":-1,
      "circuit_limit":"885.65-1082.45",
      "status":"Eligible",
      "yearly_low":901,
      "yearly_high":1196.05,
      "symbol":"INFY",
      "lot_size":1,
      "exchange":"NSE_EQ",
      "closing_price":984.05,
      "open_interest":"",
      "tick_size":5,
      "name":"INFOSYS LIMITED",
      "token":1594,
      "isin":"INE009A01021"
   }
}


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/index/master-contract/nse_eq'

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-07-18T10:45:33+05:30",
  "message": "success",
  "data": [
      "exchange,token,parent_token,symbol,name,closing_price,expiry,strike_price,tick_size,lot_size,instrument_type,isin",
      "NSE_EQ,16921,,20MICRONS,20 MICRONS LTD,39.7,,,5,1,EQUITY,INE144J01027",
      "NSE_EQ,11774,,3IINFOTECH,3I INFOTECH LTD.,4.45,,,5,1,EQUITY,INE748C01020",
      "NSE_EQ,474,,3MINDIA,3M INDIA LIMITED,13686.2,,,5,1,EQUITY,INE470A01017",
      "NSE_EQ,11868,,63MOONS,63 MOONS TECHNOLOGIES LTD,62.95,,,5,1,EQUITY,INE111B01023",
      "NSE_EQ,11058,,8KMILES,8K MILES SOFT SERV LTD,541.6,,,5,1,EQUITY,INE650K01021",
      "NSE_EQ,20906,,A2ZINFRA,A2Z INFRA ENGINEERING LTD,43.1,,,5,1,EQUITY,INE619I01012",
      "NSE_EQ,11341,,AIFL,ASHAPURA INTI FASHION LTD,401.4,,,5,1,EQUITY,INE428O01016",....
  ]
}

curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/index/master-contract/nse_eq?token=2885'

Sample response

{ 
   "code":200,
   "status":"OK",
   "timestamp":"2017-07-18T10:47:32+05:30",
   "message":"success",
   "data":{ 
      "lower_circuit":1396.6,
      "upper_circuit":1706.9,
      "instrument_name":"EQUITY",
      "gn":-1,
      "gd":-1,
      "pn":-1,
      "pd":-1,
      "circuit_limit":"1396.60-1706.90",
      "status":"Eligible",
      "yearly_low":930,
      "yearly_high":1550,
      "symbol":"RELIANCE",
      "lot_size":1,
      "exchange":"NSE_EQ",
      "closing_price":1551.75,
      "open_interest":"",
      "tick_size":5,
      "name":"RELIANCE INDUSTRIES LTD",
      "token":2885,
      "isin":"INE002A01018"
   }
}


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/index/master-contract/nse_eq?symbol=infy'

Sample response

{ 
   "code":200,
   "status":"OK",
   "timestamp":"2017-07-18T10:49:33+05:30",
   "message":"success",
   "data":{ 
      "lower_circuit":885.65,
      "upper_circuit":1082.45,
      "instrument_name":"EQUITY",
      "gn":-1,
      "gd":-1,
      "pn":-1,
      "pd":-1,
      "circuit_limit":"885.65-1082.45",
      "status":"Eligible",
      "yearly_low":901,
      "yearly_high":1196.05,
      "symbol":"INFY",
      "lot_size":1,
      "exchange":"NSE_EQ",
      "closing_price":984.05,
      "open_interest":"",
      "tick_size":5,
      "name":"INFOSYS LIMITED",
      "token":1594,
      "isin":"INE009A01021"
   }
}

getMasterContract allows to download master contract as csv. The master contract contains all necessary information about all available contracts. Gets all contracts or filter contracts by exchange segment. You can also get the details on a single scrip by sending the either symbol or token. Sending the exchange is mandatory.

Request Parameter

parameter description
exchange optional name of the exchange
  • bse_eq - BSE Equity
  • bcd_fo - BSE Currency Futures & Options
  • nse_eq - NSE Equity
  • nse_fo - NSE Futures & Options
  • ncd_fo - NSE Currency Futures & Options
  • mcx_fo - MCX Futures
symbol optional Trading symbol which could be a combination of symbol name, instrument, expiry date etc
token optional Unique indentifier within an exchange

Symbol format

The trading symbol should be sent in the following format at the time of request

Orders

Orders History

upstox.getOrders()
.then(function (response) {
})
.catch(function(error){
    done(error);
});

Sample response
{
    "code": 200,
    "status": "OK",
    "timestamp": "2017-03-28T17:01:02+05:30",
    "message": "success",
    "data": [
        {
            "exchange": "NSE_EQ",
            "token": 2885,
            "symbol": "RELIANCE",
            "product": "I",
            "order_type": "L",
            "duration": "DAY",
            "price": 1080,
            "trigger_price": 0,
            "quantity": 1,
            "disclosed_quantity": 0,
            "transaction_type": "B",
            "average_price": 1080,
            "traded_quantity": 1,
            "message": "",
            "exchange_order_id": "1100000000006972",
            "parent_order_id": "NA",
            "order_id": "170328000000030",
            "exchange_time": "28-Mar-2017 12:42:42",
            "time_in_micro": "1490697859120172",
            "status": "complete",
            "is_amo": false,
            "valid_date": "--",
            "order_request_id": "1"
        }
    ]
}

curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/orders'

Sample response
{
    "code": 200,
    "status": "OK",
    "timestamp": "2017-03-28T17:01:02+05:30",
    "message": "success",
    "data": [
        {
            "exchange": "NSE_EQ",
            "token": 2885,
            "symbol": "RELIANCE",
            "product": "I",
            "order_type": "L",
            "duration": "DAY",
            "price": 1080,
            "trigger_price": 0,
            "quantity": 1,
            "disclosed_quantity": 0,
            "transaction_type": "B",
            "average_price": 1080,
            "traded_quantity": 1,
            "message": "",
            "exchange_order_id": "1100000000006972",
            "parent_order_id": "NA",
            "order_id": "170328000000030",
            "exchange_time": "28-Mar-2017 12:42:42",
            "time_in_micro": "1490697859120172",
            "status": "complete",
            "is_amo": false,
            "valid_date": "--",
            "order_request_id": "1"
        }
    ]
}

This API provides the list of orders placed by the user. The orders placed by the user is transient for a day and is cleared by the end of the trading session. This API returns all states of the orders, namely, open, pending, and filled ones.

Response attributes

attribute datatype description
exchange string Exchange to which the order is associated
token number Token number of the instrument
symbol string Shows the trading symbol which could be a combination of symbol name, instrument, expiry date etc
product string Shows if the order was either Intraday, Delivery, CoverOrder or OneCancelsOther
order_type string Type of order. It can be one of the following
  • M refers to market order
  • L refers to Limit Order
  • SL refers to Stop Loss Limit
  • SL-M refers to Stop loss market
duration string It can be one of the following
  • DAY
  • IOC
  • GTD
price number Price at which the order was placed
trigger_price number If the order was a stop loss order then the trigger price set is mentioned here
quantity number Quantity with which the order was placed
disclosed_quantity number The quantity that should be disclosed in the market depth
transaction_type string Indicates whether the order was a buy or sell order
average_price string Average price at which the qty got traded
traded_quantity string The total quantity traded from this particular order
message string Indicates the reason when any order is rejected, not modified or cancelled
exchange_order_id string Unique order ID assigned by the exchange for the order placed
parent_order_id string In case the order is part of the second or third leg of a CO or OCO, the parent order ID is indicated here
order_id string Unique order ID assigned internally for the order placed
exchange_time string User readable time at which the order was placed or updated
time_in_micro string Time in microseconds (Unix Epoch) at which the order was placed or updated
status string Indicates the current status of the order. Valid order status’ are outlined in the table below
is_amo string Indicates whether the order is an AMO order or not
valid_date string If the order is GTD (Good-Till-Date), this shows the valid date
order_request_id string Apart from 1st order it shows the count of how many requests were sent

Order Status

An order can be in any of the following states

order status description
put order req received Order was received by our order management system successfully. Will get sent to the exchange after checking limits
open pending Order was received by exchange and awaiting open confirmation
open Order is open. Can be modified or cancelled
complete Order is closed. Cannot be modified or cancelled
modify pending Modify request received by exchange and modification pending
modify after market order req received AMO order modified
modify validation pending Modify request was received by our order management system successfully. Will get sent to the exchange after checking limits
not modified When order is not open and traded at exchange or we have not received the last modification request and sent the request again
rejected Order was rejected. Please check the message field for rejection reason
cancel pending Cancel request received by exchange and cancellation pending
cancelled Order was cancelled. Cannot be modified or cancelled
not cancelled Order was not cancelled by cancel request
cancelled after market order Order was cancelled
after market order req received Order was received by our order management system successfully and will get sent to exchange
trigger pending modified

Trade History

upstox.getTradesInfo({
    "order_ids": "161026000000007"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:48:52+05:30",
  "message": "success",
  "data": [
    {
      "exchange": "NSE_EQ",
      "token": 2885,
      "symbol": "RELIANCE",
      "product": "I",
      "order_type": "M",
      "transaction_type": "B",
      "traded_quantity": 1,
      "exchange_order_id": "1200000003336976",
      "order_id": "170515000047270",
      "exchange_time": "15-May-2017 13:56:31",
      "time_in_micro": "1494836825761723",
      "traded_price": 0,
      "trade_id": "51345784",
    }
  ]
}

curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/orders/{order_id}/trades'

Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T14:48:52+05:30",
  "message": "success",
  "data": [
    {
      "exchange": "NSE_EQ",
      "token": 2885,
      "symbol": "RELIANCE",
      "product": "I",
      "order_type": "M",
      "transaction_type": "B",
      "traded_quantity": 1,
      "exchange_order_id": "1200000003336976",
      "order_id": "170515000047270",
      "exchange_time": "15-May-2017 13:56:31",
      "time_in_micro": "1494836825761723",
      "traded_price": 0,
      "trade_id": "51345784",
    }
  ]
}

Provides the trades for the given order

Request parameters

parameters
order_id the order id for which trade details are to be fetched

Response attributes

attribute datatype description
exchange string Exchange to which the order is associated
token number Token number of the instrument
symbol string Shows the trading symbol which could be a combination of symbol name, instrument, expiry date etc
product string Shows if the order was either Intraday, Delivery, CO or OCO
order_type string Type of order. It can be one of the following
  • M refers to market order
  • L refers to Limit Order
  • SL refers to Stop Loss Limit
  • SL-M refers to Stop loss market
transaction_type string Indicates whether the order was a buy or sell order
traded_quantity string The total quantity traded from this particular order
exchange_order_id string Unique order ID assigned by the exchange for the order placed
order_id string Unique order ID assigned internally for the order placed
exchange_time string User readable time at when the trade occurred
time_in_micro string Time in microseconds (Unix Epoch) when the trade occurred
trade_id string Trade ID generated from exchange towards traded transaction
traded_price string Price at which the traded quantity is traded

Place Order

upstox.placeOrder({
  "transaction_type":"b",
  "exchange":"NSE_EQ",
  "symbol": "RELIANCE",
  "quantity": 100,
  "order_type":"m",
  "product": "I"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});


curl \
-H 'Content-type: application/json' \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-d '{order_object}' \
-X POST 'https://api.upstox.com/live/orders'

order_object - Specifies the order object eg. '{
                      "transaction_type":"b",
                      "exchange":"NSE_EQ",
                      "symbol": "RELIANCE",
                      "quantity": 100,
                      "order_type":"m",
                      "product": "I"
                    }'

This allows you to place an order to the exchange via Upstox

Request parameters

parameters description
transaction_type required Indicates whether its a buy(b) or sell(s) order
exchange required Exchange to which the order is associated
symbol required Shows the trading symbol which could be a combination of symbol name, instrument, expiry date etc
quantity required Quantity with which the order was placed
order_type required Type of order. It can be one of the following
  • M refers to market order
  • L refers to Limit Order
  • SL refers to Stop Loss Limit
  • SL-M refers to Stop loss market
product required Shows if the order was either Intraday, Delivery, CO or OCO
price optional Price at which the order will be placed
trigger_price optional If the order is a stop loss order then the trigger price set is mentioned here
disclosed_quantity optional The quantity that should be disclosed in the market depth
duration optional It can be one of the following
  • DAY (default)
  • IOC
is_amo optional Indicates whether the order is an AMO order or not
stoploss optional Set a difference from the entry price for stoploss. Use in case the product is OCO
squareoff optional Set a difference from the entry price for profit. Use in case the product is OCO
trailing_ticks optional Indicates the number of ticks if the order placed was a trailing order. se in case the product is OCO

Response available at order update

Modify Order

upstox.modifyOrder({
    "order_id" : "170307000000021",
    "price" : "280"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-d '{order_object}' \
-X PUT 'https://api.upstox.com/live/orders/{order_id}'

Modify the order by updating the order quantity. For modification order_id is mandatory. With order_id you need to send the optional parameter which needs to be modified. In case the optional paramters aren’t sent, the default will be considered from the original order. Following are those:

Request parameters

parameters description
order_id required the order id for which the order must be modified
quantity optional Quantity with which the order was placed
order_type optional Type of order. It can be one of the following
  • M refers to market order
  • L refers to Limit Order
  • SL refers to Stop Loss Limit
  • SL-M refers to Stop Loss Market
price optional Price at which the order was placed
trigger_price optional If the order was a stop loss order then the trigger price set is mentioned here
disclosed_quantity optional The quantity that should be disclosed in the market depth

Response available at order update

Cancel Order

upstox.cancelOrder({
    "order_id" : "170307000000021",
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X DELETE 'https://api.upstox.com/live/orders/{order_id}'

Cancel order can be used for two purposes:

  1. Cancelling an open order which could be an AMO or a normal order
  2. It is also used to EXIT a CO or OCO(bracket order)

Request parameters

parameters description
order_id required Unique order ID assigned internally for the order placed

Response available at order update

Feed

Live Feed

//the parameters are accepted as json 
upstox.getLiveFeeds({
  "exchange": "nse_eq",
  "symbol": "reliance",
  "type": "full"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});


If you request for LTP, the following will be the response

{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T16:45:12+05:30",
  "message": "feed",
  "data": {
    "timestamp": 1494843956000,
    "exchange": "NSE_EQ",
    "symbol": "RELIANCE",
    "ltp": 1344.1,
    "close": 1350.45
  }
}




If you request for Full, the following will be the response

{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T15:10:42+05:30",
  "message": "feed",
  "data": {
    "timestamp": 1494837991000,
    "exchange": "NSE_FO",
    "symbol": "NIFTY17MAYFUT",
    "ltp": 9446.8,
    "open": 9448,
    "high": 9454.4,
    "low": 9437,
    "close": 9414.8,
    "vtt": 2802525,
    "atp": 9446.71,
    "oi": 21256725,
    "spot_price": 9442.15,
    "total_buy_qty": 830925,
    "total_sell_qty": 858375,
    "lower_circuit": 8473.35,
    "upper_circuit": 10356.3,
    "bids": [
      {
        "quantity": 900,
        "price": 9446.7,
        "orders": 2
      },
      {
        "quantity": 75,
        "price": 9446.65,
        "orders": 1
      },
      {
        "quantity": 1050,
        "price": 9446.6,
        "orders": 4
      },
      {
        "quantity": 150,
        "price": 9446.55,
        "orders": 1
      },
      {
        "quantity": 75,
        "price": 9446.1,
        "orders": 1
      }
    ],
    "asks": [
      {
        "quantity": 450,
        "price": 9447,
        "orders": 1
      },
      {
        "quantity": 450,
        "price": 9447.3,
        "orders": 1
      },
      {
        "quantity": 900,
        "price": 9447.4,
        "orders": 1
      },
      {
        "quantity": 75,
        "price": 9447.45,
        "orders": 1
      },
      {
        "quantity": 75,
        "price": 9447.55,
        "orders": 1
      }
    ]
  }
}

curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/feed/now/{exchange}/{symbol}/{type}'

#If you request for LTP, the following will be the response

{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T16:45:12+05:30",
  "message": "feed",
  "data": {
    "timestamp": 1494843956000,
    "exchange": "NSE_EQ",
    "symbol": "RELIANCE",
    "ltp": 1344.1,
    "close": 1350.45
  }
}

#If you request for Full, the following will be the response

{
  "code": 200,
  "status": "OK",
  "timestamp": "2017-05-15T15:10:42+05:30",
  "message": "feed",
  "data": {
    "timestamp": 1494837991000,
    "exchange": "NSE_FO",
    "symbol": "NIFTY17MAYFUT",
    "ltp": 9446.8,
    "open": 9448,
    "high": 9454.4,
    "low": 9437,
    "close": 9414.8,
    "vtt": 2802525,
    "atp": 9446.71,
    "oi": 21256725,
    "spot_price": 9442.15,
    "total_buy_qty": 830925,
    "total_sell_qty": 858375,
    "lower_circuit": 8473.35,
    "upper_circuit": 10356.3,
    "bids": [
      {
        "quantity": 900,
        "price": 9446.7,
        "orders": 2
      },
      {
        "quantity": 75,
        "price": 9446.65,
        "orders": 1
      },
      {
        "quantity": 1050,
        "price": 9446.6,
        "orders": 4
      },
      {
        "quantity": 150,
        "price": 9446.55,
        "orders": 1
      },
      {
        "quantity": 75,
        "price": 9446.1,
        "orders": 1
      }
    ],
    "asks": [
      {
        "quantity": 450,
        "price": 9447,
        "orders": 1
      },
      {
        "quantity": 450,
        "price": 9447.3,
        "orders": 1
      },
      {
        "quantity": 900,
        "price": 9447.4,
        "orders": 1
      },
      {
        "quantity": 75,
        "price": 9447.45,
        "orders": 1
      },
      {
        "quantity": 75,
        "price": 9447.55,
        "orders": 1
      }
    ]
  }
}

Get live feed information about a single instrument

attribute description
exchange Name of the exchange
  • bse_eq - BSE Equity
  • bcd_fo - BSE Currency Futures & Options
  • nse_eq - NSE Equity
  • nse_fo - NSE Futures & Options
  • ncd_fo - NSE Currency Futures & Options
  • mcx_fo - MCX Futures
symbol Shows the trading symbol which could be a combination of symbol name, instrument, expiry date etc
type There are two ways in which you can request for feeds.
  • ltp (default)
  • full

Response attributes

For LTP

attribute datatype description
timestamp string Time in microseconds at which the feeds was updated
exchange string Name of the exchange
symbol string Shows the trading symbol
ltp number LTP is the last traded price of symbol
close string Close is the close price of the symbol from the previous session of trading

For Full

attribute datatype description
timestamp string Time in microseconds at which the feeds was updated
exchange string Name of the exchange
symbol string Shows the trading symbol
ltp number LTP is the last traded price of symbol
open string It will show the open price of the trading session
high string This will show the high price of the trading session
low string This will show the low price of the trading session
close string Close is the close price of the symbol from the previous session of trading
vtt number VTT is the volume traded today on symbol
atp number It stands for average traded price for the entire quantity traded in the exchange
oi number OI stands for open interest. It is applicable on future and option segments
spot_price number It means the underlying price of a stock. It is applicable on future and option segments
total_buy_qty string This show the total nos of bid quantity available for trading
total_sell_qty string This show the total nos of ask quantity available for trading
bid quantity string Bid quantity available for trading
bid price string Price at which the Bid quantity is available
bid orders string Number of orders requesting bids at this price
ask quantity string Ask quantity available for trading
ask price string Price at which the Bid quantity is available
ask orders string Number of orders requesting bids ask at this price

Subscribe

// the parameters are accepted as json 
upstox.subscribeFeed({
  "exchange": "nse_eq",
  "symbol": "reliance",
  "type": "full"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});


curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/feed/sub/{type}/{exchange}/?symbol={list of comma seperated symbols}'

Subscribe to get the live feed of a particular instrument in real-time

attribute description
exchange Name of the exchange
  • bse_eq - BSE Equity
  • bcd_fo - BSE Currency Futures & Options
  • nse_eq - NSE Equity
  • nse_fo - NSE Futures & Options
  • ncd_fo - NSE Currency Futures & Options
  • mcx_fo - MCX Futures
symbol Comma seperated list of trading symbols which could be a combination of symbol name, instrument, expiry date etc. Note: The symbols should not contain any spaces eg. ‘reliance,mrf,niftymay17fut’
type There are three way in which you can request for feeds.
  • ltp (default)
  • full

Unsubscribe

//the parameters are accepted as json 
upstox.unsubscribeFeed({
   "exchange": "nse_eq",
   "symbol": "reliance",
   "type": "full"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});

curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/live/feed/unsub/{type}/{exchange}?symbol={list of comma seperated symbols}'

Unsubscribe for the live data feed for the instruments chosen

attribute description
exchange Name of the exchange
  • bse_eq - BSE Equity
  • bcd_fo - BSE Currency Futures & Options
  • nse_eq - NSE Equity
  • nse_fo - NSE Futures & Options
  • ncd_fo - NSE Currency Futures & Options
  • mcx_fo - MCX Futures
symbol Comma seperated list of trading symbols which could be a combination of symbol name, instrument, expiry date etc. Note: The symbols should not contain any spaces eg. ‘reliance,mrf,niftymay17fut’
type There are three way in which you can request for feeds.
  • ltp (default)
  • full

Historical

OHLC

// the parameters are accepted as json 
upstox.getOHLC({
  "exchange": "nse_eq",
  "symbol": "reliance",
  "start": "20-01-2017",
  "end": "01-02-2017",
  "format" : "json",
  "interval" : "1day"
})
.then(function (response) {
})
.catch(function(error){
    done(error);
});

// Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "",
  "message": "ohlc",
  "data": [
    {
      "timestamp": 1485973800000,
      "open": 1050,
      "high": 1050.8,
      "low": 1038.25,
      "close": 1043.5,
      "volume": 2079908,
      "cp": 1045.55
    }
  ]
}

curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-X GET 'https://api.upstox.com/historical/ohlc/{exchange}/{symbol}?interval={interval}&start_date={start_date}&end_date={end_date}&format={format}'

# Sample response
{
  "code": 200,
  "status": "OK",
  "timestamp": "",
  "message": "ohlc",
  "data": [
    {
      "timestamp": 1485973800000,
      "open": 1050,
      "high": 1050.8,
      "low": 1038.25,
      "close": 1043.5,
      "volume": 2079908,
      "cp": 1045.55
    }
  ]
}

Get OHLC values for all instruments across various timeframes

attribute description
exchange required Name of the exchange
  • bse_eq - BSE Equity
  • bcd_fo - BSE Currency Futures & Options
  • nse_eq - NSE Equity
  • nse_fo - NSE Futures & Options
  • ncd_fo - NSE Currency Futures & Options
  • mcx_fo - MCX Futures
symbol required The symbol of the instrument. This must match exactly as given in the master contract csv. eg:NIFTY17MARFUT
interval optional Default: 1day
Allowed Values:
  • 1MINUTE

  • 5MINUTE

  • 10MINUTE

  • 30MINUTE

  • 60MINUTE

  • 1DAY

  • 1WEEK

  • 1MONTH

start_date optional Default: 15 days before today
Date format: DD-MM-YYYY
eg: 20-01-2017
end_date optional Default: today
Date format: DD-MM-YYYY
eg: 01-02-2017
format optional The data format of the ohlc representation.
  • csv

  • json (default)

Websocket

The Upstox API websocket channel can be used to receive various types of push updates from the Upstox server. These updates include:

Connection


#Sample cURL call - only use for testing
#Please note that you may get disconnected after some time
curl \
-H 'authorization: Bearer {your_access_token}' \
-H 'x-api-key: {your_api_key}' \
-H "Connection: Upgrade" \
-H "Upgrade: websocket" \
-H "Sec-WebSocket-Key: {random-number}" \
-H "Sec-WebSocket-Version: 13" \
--include \
--no-buffer \
'https://ws-api.upstox.com/?apiKey={your_api_key}&token={your_access_token}'

upstox.connectSocket()
.then(function(){
    /*
    Socket Connection successful
    Now you can setup listeners
    */
}).catch(function(err){
    /*
    Something went wrong.
    */
});

The connectSocket function in the libraries will create an always-on socket connection to the Upstox API servers. If you are using cURL, please be sure to pass your your_api_key and your_access_token as parameters in the URL.

Disconnection

upstox.closeSocket();

Upstox API libraries allow you to disconnect the socket with a method

Events

Order Update

upstox.on("orderUpdate", function(update) {
   // update will contain the JSON object of order update the structure of which is as given below    
});

{ exchange: 'NSE_EQ',
 token: 2885,
 symbol: 'RELIANCE',
 product: 'I',
 order_type: 'L',
 duration: 'DAY',
 price: 0,
 trigger_price: 0,
 quantity: 1,
 disclosed_quantity: 0,
 transaction_type: 'B',
 average_price: 0,
 traded_quantity: 0,
 message: '',
 exchange_order_id: '1200000001405029',
 parent_order_id: 'NA',
 order_id: '170516000022221',
 exchange_time: '16-May-2017 10:16:54',
 time_in_micro: '1494910048512349',
 status: 'open',
 is_amo: false,
 valid_date: '',
 order_request_id: '2',
}

The order update event comes with the message value of order_update

The response for the order update event is the same as an individual response in the order history command

Trade Update

upstox.on("tradeUpdate", function(update) {
    // update will contain the JSON object of order update the structure of which is as given below
});

{
 exchange: 'NSE_EQ',
 token: 2885,
 symbol: 'RELIANCE',
 product: 'I',
 order_type: 'L',
 transaction_type: 'B',
 traded_quantity: 1,
 exchange_order_id: '1200000001405029',
 order_id: '170516000022221',
 exchange_time: '16-May-2017 10:16:54',
 time_in_micro: '0',
 traded_price: 0,
 trade_id: '50476729',
}

The trade update event comes with the message value of fill_report

The response for the trade update event is the same as an individual response in the trade history command

Quote Update

upstox.on("liveFeed", function(message) {
    //message for live feed
});

Quote updates come as binary values. You need to first decode the binary into a string. Each quote update is separated by the semi-colon ; character. Within each quote update, each field is separated by commas ,

On Disconnect Event

upstox.on("disconnected", function(message) {
    //listener after socket connection is disconnected
});

The disconnect event is available on Upstox libraries

On Error Event

upstox.on("error", function(error) {
    //error listener 
});

The error event is available on Upstox libraries

Errors

Error Code Meaning
400 Bad Request – Your request parameters are incorrect
401 Unauthorized – Your API key is wrong
403 Forbidden – The requested resource is hidden for administrators only
404 Not Found – The specified resource could not be found
405 Method Not Allowed – You tried to access a resource with an invalid method
406 Not Acceptable – You requested a format that isn’t json
410 Gone – The resource requested has been removed from our servers
429 Too Many Requests – You’re requesting too many resources! Slow down!
500 Internal Server Error – We had a problem with our server. Try again later.
503 Service Unavailable – We’re temporarily offline for maintenance. Please try again later.