Click or drag to resize

Introduction

DotNet Library For Kite Connect API

Two keys to successful trading are taking a business-like approach (complete with a business and trading plan) and effectively using available trading technology. Algorithmic trading or Algo trading as it is known in the financial sector is the future and this library is our small contribution for that.

Kite Connect API

So actually, what is an API?

You can refer the Wiki definition of API from here and much better definition from here.

An API (Application Programming Interface) is a set of procedures, protocols and methods that enable one application or server to communicate with the other and request or retrieve data.

API is everywhere in your life,

  • the app you use in your android phone uses API,

  • the online portal through which your are paying your bills is using API,

  • train ticket you book through IRCTC website uses API,

  • internet/mobile banking uses API

  • and countless services uses API.

If API is not there, the digital world which we are enjoying now wouldn't exist.

What's the scope of API in Stock Trading? Why one needs API, when the trading member is providing Desktop/Web trading platform to trade stocks, check positions and account details?

API has its own purpose in stock trading as well. The default platform provided by the trading member will have only basic functionalities. API is for those who need functionalities beyond what is offered in the standard trading platform.

Example:

  • Position Alerts on Profit/Loss

  • Customized Order Window

  • Multi Leg/ Spread Orders

  • Real-time Position Sizing

  • Order Slicing

  • Order Placement from Charting Software

  • Execute Option Strategies

  • and many more

Please note, API is just an interface, you need to write your own program or code to do your requirements like above. You must be a programmer to use API or you can hire professional programmers to program your logic.

What is Kite Connect API?

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

As said, the purpose of API is to request or retrieve data from other program or server, here we are requesting data related to the trading account from broker server or OMS.

In other words, you can build your own trading platform (with or without UI) and access your trading account.

Since Kite Connect API is a HTTP API, most programming language can call its methods.

KiteNet

KiteNet is a .Net library for Kite Connect API. It’s a wrapper built around Kite Connect API and supports all methods exposed by Kite Connect API. This library can be effectively used to build rich UI applications or Console Applications etc. KiteNet also supports COM, so you can call its function from other applications like MS Excel etc.

Why separate library, when I am able to directly call the Kite Connect API methods from my code as it is a HTTP API?

Yes, of-course you can directly call all the Kite Connect API methods from your code without using any libraries. But library will help you to do things more quickly/easily. For example, to get positions, with raw HTTP API you need to write 10 to 15 lines of code to make HTTP request and parse the returned response, but with library the same can be achieved with single line as all the works are wrapped inside the function. By using library, your workload is greatly reduced.

KiteNet wraps all the raw HTTP API calls of Kite Connect API as simple functions and returns data that's ready to use for analysis

User needs to just call the Functions or Methods by passing valid parameters.

Example:

To see the Positions.

Kite.GetPositions() 'This will return position details as comma separated values. You can just save it in Csv format or analyze.

To Cancel a Order

Kite.CancelRegularOrder("160012345656") 'This will cancel the Order

Order Status

Kite.GetOrderStatus("160012345656") 'This returns order status of the given order id

KiteNet supports custom exceptions, this will help user to debug his code.

Example:

If user passes 0 as price in a Limit Order,

Unlike the other libraries, where the order request is sent and exception is thrown from API server, KiteNet will throw exception "InvalidPriceException" and will not send order request to API server. This may little reduce load in API server.

Another good example is

In a Buy SL order, if the user passes Trigger Price higher than the Limit Price, KiteNet will throw Exception "BuySLPriceExeption"

Basically, these are designed to restrict invalid request to reach API server.

The main purpose of KiteNet is to let the developers concentrate on their trading system; instead of working on execution system, this greatly reduces burden of the developers and helps to deploy their trading system very quickly. KiteNet provides complete set of tools required by the developers to build their trading system.

Please note, KiteNet do not provide any kind of strategies or indicators, it's a .Net library for Kite Connect API. It takes request from the user and passes to API server, receives response from API server and passes to the user.

Microsoft Excel Support

Microsoft's Excel spreadsheet program is wonderful and powerful tool that allows investor and traders to keep track of investment and trading activity in an organized manner. Most of the price action strategies can be easily built with Microsoft Excel only. Many people around the world are using Excel to build their Trading System, but still one needs to execute their trade manually in the trading platform as there is no connectivity between the excel and trading platform.

The Excel Limitation is no More. Thanks to the Kite Connect API, now it’s possible to build the entire trading and execution system within Excel, get fast real time quotes. Everything is possible from within Excel, you can place orders, check order book and whatever you do in trading platforms (Basic functionalities) are possible in MS Excel.

You can build trading system in excel with KiteNet as it supports COM.

Please note, to be able to call KiteNet functions from excel cell, you need to wrap the functions of KiteNet in UDF (VBA) first. In the sample excel sheet, we already wrapped all KiteNet functions in UDF, you can modify the existing UDF to meet your requirement.

Main Features
  • Inbuilt Webbrowser control for login flow

  • RTD Server

  • Real-time MTM and Position details

  • Mail Alerts

  • Tray Notification

  • New and Modify Order Window

  • Market Depth

  • Automatic reconnection of Websocket in case of error

  • Events for Quotes, MTM, Positions, Order, Trade

  • Custom Tag for orders

  • Historical Data batch downloader

  • Batch order placement from csv or text file

  • Proxy support

  • Paper Trading

  • Ticks and MTM logs

  • and many more

Dependency

KiteNet depends on the following libraries

Credits

This library uses Open Source components. You can find the details of their open source projects along with license information below. We acknowledge and are grateful to these developers for their contributions to open source.

System Requirements
  • Operating System: Windows 7 SP1 or higher

  • RAM: 2 GB or higher

  • CPU: 2 GHz or faster and minimum 2 cores

  • Dot Net Framework: 4.5.2 or higher

  • MS Office: 2007 or higher

  • Web Browser: Chrome or Internet Explorer or any latest browser

  • Administrator rights

  • Good Quality Internet

User Requirements
  • Zerodha Trading Account

  • Kite Connect API Subscription

  • Excel/VBA Knowledge

  • VB.Net or C# Knowledge

  • Of course the most important requirement: Good Strategy a.k.a Buy/Sell logic

Excel Settings

The below settings must be done in Excel to use KiteNet

Enabling Macros:

  • Open Trust Center : Office Button --> Excel Options --> Trust Center

  • Open Trust Center Settings : Trust Center --> Trust Center Settings

  • Macros Settings: Select ‘Enable all macros’

  • ActiveX Settings: Select ‘Enable all controls without restriction’ and uncheck ‘Safe mode’

  • External Content: Select ‘Enable All Data Connections’ and ‘Enable Automatic Update for all workbook links’

Changing RTD throttle interval:

By default, Excel will request real time data from RTD server at an interval of 2 seconds. Who wants to lag behind by 2 seconds in the stock markets where the prices are changing in micro seconds?

We will change the throttle interval to 0, so that Excel will update quotes in real time.

To Change RTD Interval:

  • In Excel, go to the Visual Basic Editor by pressing ALT+F11

  • Once you are in Visual Basic Editor, Press CTRL+G to open Immediate Window

  • Once you are in Immediate Window, Type the below command and Press enter

  • Application.RTD.ThrottleInterval = 0

To Check whether the interval is updated or not:

  • Type the below command in Immediate Window and Press enter

  • ? Application.RTD.ThrottleInterval

  • The above command will return 0; if not 0 again set the interval as mentioned above

Internet Explorer Settings

Since, the in-built Webbrowser control uses Internet Explorer; the following sites must be added to Trusted Sites in Internet Options

Adding Trusted Sites:

  • Open Internet Options: Control Panel --> Network and Internet --> Internet Options

  • Open Trusted Sites: Internet Properties --> Security --> Trusted Sites --> Sites

  • Add the above sites one by one

  • Uncheck ‘Require Server verification’

Logs

KiteNet logs files are stored date wise, this log files will help developer to debug issues, errors and exceptions. All the exceptions thrown by API server and system are logged in text file. The location of the log file is

[APPDIR]\KiteNet\[DDMMMYYYY]\KiteNet_Logs.txt

In case of excel, the app directory is ‘My Documents’

Please note, KiteNet will not throw any error on its own, whatever the error thrown is either from API server or System (Ex: Network disconnect) or buggy code.

Ticks and MTM Logs

This is one of the best feature that KiteNet supports. Each and every ticks received in Websocket is saved to text file, which can be used for analysis. Real time MTM is also saved to text file and you can check your positions performance i.e. Highest and Lowest MTM achieved etc.

RTD Support

One of the cool features of KiteNet is, it supports RTD server. Now you can get streaming real-time quotes in Excel.

RTD server gets data through Websocket, parses the received data and streams real time quotes to Excel.

The Syntax for Excel RTD Function is =RTD(ProgID,ServerName,Topic1,[Topic2])

  • ProgID: KiteNet.Rtd

  • ServerName: Blank

  • Topic1 - Ticker in the Format of [TRADESYMBOL].[EXCH] Ex: AXISBANK.NSE, NIFTY18FEBFUT.NFO, SILVERM18FEBFUT.MCX

  • Topic2 - Price Filed.

Supported Price Fields:

{"LAST", "PCTCHG", "NETCHG", "LASTSIZE", "BID", "BIDSIZE", "ASK", "ASKSIZE", "MTM", "NETQTY", "AVGPRICE", "VOLUME", "TOTALBUYQTY", "TOTALSELLQTY", "OPEN", "HIGH", "LOW", "CLOSE", "OI", "LUT", "LOWERCKT", "UPPERCKT", "SPOT", "YEARLYHIGH", "YEARLYLOW", "LTT", "AVGBOUGHTPRICE", "AVGSOLDPRICE", "BOUGHTQTY", "SOLDQTY", "OIHIGH", "OILOW", "OINETCHG", "OIPCTCHG"}

Example:

=RTD("KiteNet.Rtd",,"AXISBANK.NSE","LAST")

=RTD("KiteNet.Rtd",,"AXISBANK.NSE","OPEN")

Adding RTD formula likes above in every cell is tedious, so we added a UDF "GetRTD" in the sample excel sheet, which will wrap the complex RTD function. User can use this UDF instead of the original RTD function, note this is not mandatory.

The syntax for the GetRTD is

=GetRTD(Exch, TrdSymbol, Field)

=GetRTD("NSE", "AXISBANK", "LAST") ‘ will get LTP

Subscribe Quotes:

To get Real-time quotes in "Excel RTD", you must be logged-in to KiteNet and need to call the "SubscribeQuotes" method for the Symbol which you want data. This is equivalent to adding symbols in market watch of trading platform.

=SubscribeQuotes(Exch, TrdSymbol)

=SubscribeQuotes("NSE", "AXISBANK")

Unsubscribe Quotes:

You can call the "UnSubscribeQuotes" method to stop receiving data. This is equivalent to deleting symbols in market watch of trading platform.

=UnSubscribeQuotes(Exch, TrdSymbol)

=UnSubscribeQuotes("NSE", "AXISBANK")

Login Flow

You must login through KiteNet first, before calling any utility methods. You need to call the below methods sequentially to make a successful login.

Please note, you must open your Application/Excel as Administrator.

Ensure the above Excel and Internet Explorer settings are done.

Ensure you have set API Key, Secret and Redirect URL in your code, if using MS Excel set in Settings Window (Call ‘ShowSettingsWindow’)

Please note, your redirect url in the developer console and your app/excel should match exactly (1-1 match). Please avoid using http://127.0.0.1 as redirect url as it requires web server to be running in your computer, so instead use https://zerodha.com

Set correct API Key and Secret, sometimes mistakenly leading and trailing spaces or extra characters may also be copied along with API Key which leads to login error.

1. Login

This method will open Inbuilt Webbrowser for login. Post successful login, you will be redirected to your redirect url, request token will be automatically copied and Webbrowser will automatically close.

Please note, the inbuilt Webbrowser uses Internet Explorer to open web page. Internet Explorer behaves differently on every OS and version. So, the automatic login (capturing request token) may or may not work properly in your system. If the automatic login not working, then you need to do manual login using Login("Chrome") and copy the request token from the browser and paste it in the GetAccessToken("RequestToken") method

2. GetAccessToken

This method will request access token from API server.

Please note, if you done manual login, then call the GetAccessToken("RequestToken") method to pass the request token.

3. GetMasterContract

This method will start a background thread to download master contract from API server and will return immediately. You need to wait for the download to finish before calling any methods. You can check the symbol_download_status property for download status.

Please note, Master Contract is downloaded only once per day from the API server. Hence first login of the day will take time as it downloads file (Appx: 6Mb) from API server. Subsequent login will be fast as symbols are loaded from locally saved files.

You will get tray notification (if enabled) once the download is finished. As soon as the download is complete, KiteNet will automatically subscribe quotes for symbols already added in the system.

Now you can call any methods of KiteNet.

Please note, call KiteNet methods in Try…Catch block to catch exceptions for debug.

Getting Live Quotes

To get live quotes, you must subscribe quotes for all symbols for which you want data.

Subscribe Quotes:

To get Real-time quotes in "Excel RTD" or "QuotesReceivedEvent", you must be logged-in to KiteNet and need to call the "SubscribeQuotes" method for the Symbol which you want data. This is equivalent to adding symbols in market watch of trading platform.

SubscribeQuotes(Exch, TrdSymbol)

SubscribeQuotes("NSE", "AXISBANK")

Unsubscribe Quotes:

You can call the "UnSubscribeQuotes" method to stop receiving data. This is equivalent to deleting symbols in market watch of trading platform.

UnSubscribeQuotes(Exch, TrdSymbol)

UnSubscribeQuotes("NSE", "AXISBANK")

License

Please go through the below link carefully

License

Legal Compliance

Please contact your stock broker or trading member for all legal compliance and regulatory approval related queries as KiteNet is a .Net library for Kite Connect API, and not a financial product of any kind.

Support Services

Because this software (.Net Library) is "as is" we will not provide support services for it.

Please understand, this is not a product of any kind, this is a .Net Library for Kite Connect API developed by us for Developers and Programmers.

Developers are free to use our library to build platforms and systems for personal and other's use if they find our library useful else it is not mandatory to use our library, they can use official library or even can build their own library.

If you find any bugs or issues in the library, you may notify us through email kitenet@howutrade.in or developer forum, we will try to rectify/fix the bugs/issues as soon as possible.

We may provide sample codes for generic use case of functions/methods of our library.

If you have any issues or errors in your system code or need help in programming/coding, you may post your queries in the developer forum, we or any fellow developer may help at our or their leisure time.

If you need immediate support or didn't get any solutions from the forum or the solution received in the forum is not efficient or the solution you asked is beyond the scope of the forum or you want full readymade solution then, you can hire some computer professionals for the same.

Please do not mail us queries related to your trading program/system, we do not support such personal requests, we do not provide any readymade solutions.

We may provide general idea or guidelines or generic samples codes to get started.

API Developments and Issues

Please visit developer forum regularly to know the latest developments, updates, announcements, issues and bugs in API.

Please note, API concept is new here and all trade API’s are evolving, and it’s in nascent stage, so bugs/errors and stability issues may be there.

Performance and Latency

Latency depends on multiple factors;

  • Internet Speed

  • Network Traffic at API server

  • Location

One can take advantage of Cloud Computing to position their system close to OMS.

Approximate time taken to reach OMS from various locations

Location

Time (in millisecond)

Chennai

60

Bangalore

40

Bangalore (Cloud)

15

Mumbai

20

Mumbai (Cloud)

≪ 1

Singapore (Cloud))

60

Developers can implement multi-threading at user level to speed up the system.

Please make sure, you do not exceed throttle limit.

MTM and Position Details

Kite Connect API doesn’t support streaming MTM and position details in Websocket. It supports positions call using GET request, since the GET request is resource hungry, calling it in a loop will lead to system stability issues, and may lead to system crash.

The real-time MTM and position details which you get in KiteNet is internally calculated by KiteNet using the order details received through websocket, so if any order update is missed due to network or API issue, this details may go wrong.

As long as you receive order updates correctly, you will get accurate real time MTM and position details which can be used to build risk management systems like exiting positions on certain profit or loss, position sizing based on the profit and loss etc.

Please careful if your system uses this details in any logic.

Samples and Demos

The sample codes, apps, excel workbooks and projects are provided "as is".

They are meant for getting started quickly with KiteNet. Developers can modify the samples as per their requirement.

Feedback and Suggestions

We always welcome feedback and suggestions. Please mail your feedback and suggestions to feedback@howutrade.in.

We will try our best to implement your feedback and suggestions, if it is useful for most users and general in nature.

Contribute

We request developers and programmers to contribute sample codes to the community and guide new developers in the forum.

Caution

Excel calculates cell formula whenever there is a change in the referenced cell value, use static variables to restrict multiple order requests.

Do not fetch order and position books in a loop, as these are GET request and consumes more resources.

Test your program thoroughly before going live, a small mistake in your code may become a disaster.

Have good quality internet, try to run your system in cloud computing. Mobile and Wi-Fi internet normally will have network fluctuation, websocket is sensitive to this fluctuation and will disconnect frequently.

Back-test result will never match in real-time due to slippages. Brokerage, taxes and commissions, will turn your profit to red. Don’t get excited with back-test results.

Monitor your system frequently.

Run your trading system in a dedicated computer, not in your personal or work computer.

Paper Trading

We added support for Paper Trading in KiteNet. Please don't expect an OMS level simulation and it is nearly impossible to implement such level of simulation as OMS is a very very big thing which requires large back-end servers and programs to process client orders.

The main purpose of Paper trading is to know 'How much you would have made or lost if you have bought and sold stocks'.

Because that's the only unknown, rest all like margin, symbols to trade, quantity to trade, maximum positions, maximum trades, risks etc are all well known even before we take a trade, and that should be a part of the trading system not the execution system.

How it works?

Paper trading will give you real time MTM and position details without actually placing an order in exchange.

Whatever the order type of your order is, Paper Trader will always assumes you want to place order at market and allot dummy order id.

Example: If you place a Buy LIMIT order at 125.65 and current Ltp is 128.75, that doesn't mean that your order will be executed only when the Ltp touches or goes below 125.65(It's how normal LIMIT Order works), Paper trader will simply assume that you want to Buy right now and accordingly allot dummy order id and Ltp (Best Bid/Ask) will be the executed price (Ex: 128.75).

If you place a Sell SL-M/SL order at trigger price 530.50 and current Ltp is 531.65, that doesn't mean that your order will be executed only when the Ltp touches or goes below 530.50(It's how normal SL-M/SL Order works), Paper trader will simply assume that you want to Sell right now and accordingly allot dummy order id and Ltp (Best Bid/Ask) will be the executed price (Ex: 531.65).

Simply put, place your bridge order only at the moment you get signal(Buy/Sell/Short/Cover) in your trading system.

The cool feature of this paper trading is 'you can run multiple strategies with same or different stock and get real time MTM and position details strategy wise and logs MTM to text file which can be used for analysis.

The Sample Strategies are just for testing purpose.

Bridge Documentation

For Beginners

If you are new to API and programmatic trading, please understand;

  • Programming knowledge is must to use our library

  • Our library is not a standalone or Plugnplay software that you can directly install and use it. It’s just a library of functions that needs to be called from another program or software.

  • If you don't know programming then,

    (a) If you are interested to do things yourself, please learn programming language before trying our library.

    (b) or you can hire some computer professionals to program your idea/logic.

  • API is not any kind of indicator or strategy, it is a platform to execute your orders and get trading account details.

  • API can be effectively used low frequency systems, not suitable for HFT kind of systems. With API, you can execute only limited number of request at a time or in a second (Max 1 to 5 requests per second; Sometime it may take a minute or more to execute a single request due to network traffic or congestion at API server)

Third Party Apps

If you are using any third party apps or platforms built with KiteNet, please note we neither gave permission nor authorised any third party apps or platforms. Use such apps or platforms at your own risk.

If you are a third party, developed or developing any apps or platforms with KiteNet and intend to distribute the same to others for free or sale, please note even though you are free to build apps or platforms with KiteNet, for distributing it to others, please contact the trading member for legal compliance and you must comply to the below points;

  • You must require end users to agree to terms that protect it at least as much as KiteNet license agreement.

  • You must display your valid copyright notice on your programs.

  • You must indemnify, defend, and hold harmless HowUTrade from any claims, including attorneys’ fees, related to the distribution or use of your programs.

  • You should not alter any copyright, trademark or patent notice in the KiteNet (Distributable Code)

  • You should not use HowUTrade’s trademarks in your programs’ names or in a way that suggests your programs come from or are endorsed by HowUTrade

  • You should not include KiteNet (Distributable Code) in malicious, deceptive or unlawful programs

Happy API Trading...!

HowUTrade

Please! read the documentation thoroughly. Highlighted points are important. ×