NOTICE:

I have suspended this API until further notice. Etelej

Introduction - The NSE End-Of-Day API v1

If you follow the Nairobi Stock prices, I'm sure you know that they are few sites online that offer the data and even fewer that provide stock data for, let's say, a week.This API was written in order to provide developers NSE data to build applications across any platform.

As I was beginning work on the Blogs-Kenya community portal and writing its API, I realized how hard it was to get usable Kenyan information for application development. I then started writing a set of my own unofficial APIs from various Kenyan sites. I've decided to clean up and publish publicly one of those APIs to help any developers out there who might need it.

The NSE v1 API allows a developer to access stocks up to a month (31 days) old. While some companies offer these data as packaged commercial products, this API allows free access to the same.

Why write a public API?

While many Kenyan techies and developers have the talent and ideas to create awesome applications, there are very few publicly accessible portals for freely consumable Kenyan content. One such portal, which I think you should check out as a developer, is the Open Data Initiative. Though it has a lot of data and in a large number of formats, their API is not well documented nor even specific to the Open Kenya site. It is a real bother to use, but hopefully, we'll write a set of SDKs and libraries on The OK Developers Portal to help.

Anyway, to answer the question: Why write a public API?, this project is part my own little contribution to the Open Data philosophy; the Free Kenyan Data Project. This project ventures to provide free-to-use public APIs, SDKs and applications to allow the sharing and distribution of Kenyan content to The Online Kenyan.

While developing an NSE application would be much faster, easier and maybe even profitable, writing a public interface pretty much gives all developers access to the data. Meaning more applications in the long run, leaving The Online Kenyan with more options and more informed. It was also an opportunity for me to educate myself and get sufficient experience on the various practices for writing a great API.

What about Apps?

A good thing about an API is that it can be used to whip up a bunch applications using the same data much faster and easier. Personally, I'll use this API to write a mobile site for accessing NSE information, as well as add ons and plugins for the variety of CMS templates out there. You're welcome to build your own applications using this API or invite your developer friends to give it a try.

In the meantime, there a nifty little widget I developed with the API that you can embed into your website/blog and get an the latest end-of-day stocks displayed on your page. It's requires javascript and runs much like the widgets we're used to: Facebook Like, Disqus Comments, Google+ button.. Plus, it's completely free. Get it here: Pata NSE Stocks widget.

Getting Started

https://theok-apis.appspot.com/nse-api/v1/nse.json

This is the url you'll come to love. It is the only endpoint used for the ReSTful NSE v1 API service. You can visit the address now and check it out for yourself. Using HTTP GET parameters, it allows you to specify what data you need and returns a json object with the data. I used the JSON format because it is, IMO, the best data interchange format. It is easy to integrate in the three of the top web application languages (Javascript, PHP and Python) plus it's also smaller that the likes of xml. I have nothing against xml, rss or atom, it's just that I haven't had time to do the conversions.

What about authentication, rate limits?

I have currently not put in place authentication or rate limits to help developers easily access the API. However, I will monitor traffic and may put in place authentication later, but will still allow good old unauthenticated requests with a set limit which will be sufficient for most developers in order not to break any of your apps.

As a bit of a counter to misuse of service, I use a set of caching layers to hold and release the data. Key of these is the client side cache, where the API Response JSON's header has set cache-control max-age of 900 since response data almost never changes. This simply means that when the JSON is requested, it is stored by the client browser for up to 15 minutes.

Using the NSE API

When requesting for data from the API, you will use the url above, preferably in an application, and pass parameters to select specific data.
For example, use the url https://theok-apis.appspot.com/nse-api/v1/nse.json?data=indices to request for only the market indices. By passing different parameter values you can get stocks, totals, indices, or specify what date you want.

Cache, cache, cache

When fetching data from the API, I recommend keeping in storage, where in a database, filing system or temporary storage. It's win-win-win, it helps you avoid frequent calls to the API, faster and searchable (depending on your storage system) and less API calls means I save on bandwidth, meaning many more free apis for other developers.

If you're doing server side web development, or desktop application development, this will be pretty much easy to do. If however you're building client side browser applications, let's say with HTML5 and friends, you can always use localStorage.

Note: This API will only provide End of Day statistics, not live feeds. Mostly because it's free and I have to watch my bandwidth. It does, however, allow you to browse through stock stats going back one month.

API Reference

The Parameters - GET Request Parameters (all optional)

  • data [optional]    Default = stocks

    It specifies the type of data you want. It has the following options:

    • stocks - Return a JSON object of stock prices for the given day. This includes: a stocksId - a unique integer ID for each day's stocks, date - Human readable date for the stocks formatted like so: 23 August 2012 and stocks - an array/list of stocks for each company (price day before, price that day, company name,and change difference)
    • indices - Returns a JSON object with NSE indices for the given day. This includes: ALL SHARE INDEX, 20 SHARE INDEX, FTSE NSE Kenya 15 Index and FTSE NSE Kenya 25 Index, as well as date and stocksId
    • totals - Returns a JSON object of other trading statistics like market capitalization, total shares traded, equity turnover and total deals, plus date and stocksId
    • all - Returns all stats. It returns a JSON object that includes stocks, indices and totals as well as the stocksId, and date
  • date [optional]    Default = yesterday e.g if today's 26 Aug 2012 then date=25-August-2012

    The date parameter allows a user to specify the date of the stocks wanted. This is limited between yesterday's date and exactly a month ago. The parameter accepts the date in the following format: date=25-August-2012
    If the date is not entered in the specified format, an error will be returned. If this method of specifying the date proves hard, please use the days_ago parameter, but don't use both.

  • days_ago [optional]     Default = 0 (then 1)

    This is simply as it's name states. You pass in a number for how many days ago you want to specify. For example 0 is today, 1 means yesterday, 2 the day before etc. The API engine will process your number and determine the date you want, as well as check if it has that data and send the response. Since you cannot access data older than a month old, the day_ago has a maximum limit of 31. And since, the API can't fetch data from the future, it has a minimum limit of 0, meaning today. The default is a bit different, it first checks 0 (today) then checks 1 (yesterday) and returns that if today's stocks don't exist.

The days_ago and date parameters are both used to specify the date of the stocks wanted. Therefore, both cannot be used at the same time.

NSE API RESPONSE JSON - The API endpoint Response object

  • stocks_id [integer]     Unique for each day

    This is a unique ID for each stock batch, meaning that it is unique to all data for a specific date. You can use it to determine if the stocks have been updated by comparing what you have with what's on the API. It is not unique for each data type; meaning if you request data=stock or data=indices for the same day, the stocks_id will be the same

  • date [string]     Human readable date for stocks batch

    A human readable date for the stock batch. In the format %d %B 20%y meaning that the 25th of August 2012 would appear as "date" : "25 August 2012" .

  • response_type [string]     The type of data in response

    It returns the type of data in response. If stocks where requested it returns "response_type"="stocks". Other values it returns are indices,totals,all. Please note that it returns error if there was an error getting the data. This is crucial to note when debugging and should be checked for before displaying the results to end users.

    When checking the status of the API response, do not use the HTTP Response Header Code. All Requests will receive a 200 OK response from the NSE API. This means you have to check the response_type value. This is majorly to bypass application platforms like Flash and Js that intercept error codes and display them to the end user.
    Meaning that your code should be something like:
    //assuming response is the object from the API 
    var error = false;
    if ( response.response_type === "error" ) {
        // Execute a statement that reports error, for example
        error = true;
        display_error(response.message);
    }else{
        //Proceed with Displaying data to end-user
        display_nse_data(response.stocks);
    }
  • message [string]     A message about the error

    This is only important if you receive a "responseType":"error" because it displays information about the error message. If there was no error, it just asks you to visit The OK Developers Portal to join the Project

  • indices [string]     An Array/list of indices

    It displays a list od the indices for the specified date and their values. It is only returned if you requested data as indices or all . You have to loop through the list in order to get the data, a simple foreach or for in loop would suffice.

    	"indices": [
    	
    	    {
    	        "indice": "ALL SHARE INDEX",
    	        "value": "84.01"
    	    },
    	    {
    	        "indice": "20 SHARE INDEX",
    	        "value": "3,817.70"
    	    },
    	    {
    	        "indice": "FTSE NSE Kenya 15 Index",
    	        "value": "110.67"
    	    },
    	    {
    	        "indice": "FTSE NSE Kenya 25 Index",
    	        "value": "113.19"
    	    }
    	]
  • totals [string]     An array/list of Other trading statistics for the specified date

    It includes market capitalization, total shares traded, equity turnover, and totals deals. It is only returned if you requested data as totals or all.

  • stocks [string]     An array/list of all stock prices for a specified date

    It includes company (the company name), end_of_day (the end of day price), prev_day (price of day before), and change (percentage difference between the end of day and the day before). It is only returned if you requested data as stocks or all. You can store these values to generate graphs for a given company over a period of time.

SDKs and Libraries

I plan on writing libraries for Javascript, Python, Java and PHP to provide functions to access, store and filter through the data more easily. The libraries will be written as based on the demand for the service, so if you're a developer; you can send me a quick message in order to get support for your language of choice. Anyone interested in writing libraries for the NSE API is also free to do so.

In the meantime, I've written a jQuery plugin that fetches the latest stocks and displays them inserts them into your site. The Pata NSE Stocks widget uses this plugin, it automatically checks if NSE Stocks are available from 1,2 or 3 days ago and uses the data found. Here's a link to the source code: PataNSE.jQuery.js. Feel free to reverse engineer, play around with it or customize it to suit your needs.

The Free Kenyan Data Project

What is it?

This is a project here at The Online Kenyan to provide cheap and easily accessible information and applications to the common mwananchi. It is no Wikileaks, we do not wish to share private, copyrighted or corporate information belonging to anyone or any organization without permission to do so. If you are an organization and would like to share large scale public information, the Free Kenyan Data Project is a good way to go. If you would like a secure internal company info-center for your data, you can contact me and we can work on something different.

Join the Project

You don't have to be a programmer or developer take part in the Free Kenyan Data Project. If you have ideas on how to provide information, or technical skills to do so, or have relevant data to publicize please feel free to get in touch or join The Online Kenyan Developers community.

NOTICE:

I have suspended this API until further notice. Etelej

The NSE API v1 was written by . It is free for use and distribution.