• Stars
    star
    203
  • Rank 192,890 (Top 4 %)
  • Language
    Java
  • License
    MIT License
  • Created about 8 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The official Java client for communicating with Kite Connect API.

The Kite Connect 3.3.2 API Java client

The official Java client for communicating with Kite Connect API.

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

Zerodha Technology Pvt Ltd (c) 2019. Licensed under the MIT License.

Documentation

Usage

  • Download Kite Connect 3 jar file and include it in your build path.

  • Include com.zerodhatech.kiteconnect into build path from maven. Use version 3.3.2

  • To use javakiteconnect in Android, you need to include jar file in the libs directory and add the following line in you module's gradle file compile files('libs/kiteconnect.jar')

API usage

// Initialize Kiteconnect using apiKey.
KiteConnect kiteSdk = new KiteConnect("your_apiKey");

// Set userId.
kiteSdk.setUserId("your_userId");

/* First you should get request_token, public_token using kitconnect login and then use request_token, public_token, api_secret to make any kiteconnect api call.
Get login url. Use this url in webview to login user, after authenticating user you will get requestToken. Use the same to get accessToken. */
String url = kiteSdk.getLoginUrl();

// Get accessToken as follows,
User user =  kiteSdk.generateSession("request_token", "your_apiSecret");

// Set request token and public token which are obtained from login process.
kiteSdk.setAccessToken(userModel.accessToken);
kiteSdk.setPublicToken(userModel.publicToken);

// Set session expiry callback.
kiteSdk.setSessionExpiryHook(new SessionExpiryHook() {
    @Override
    public void sessionExpired() {
        System.out.println("session expired");                    
    }
});

// Get margins returns margin model, you can pass equity or commodity as arguments to get margins of respective segments.
Margin margins = kiteSdk.getMargins("equity");
System.out.println(margins.available.cash);
System.out.println(margins.utilised.debits);

/** Place order method requires a orderParams argument which contains,
   * tradingsymbol, exchange, transaction_type, order_type, quantity, product, price, trigger_price, disclosed_quantity, validity
   * squareoff_value, stoploss_value, trailing_stoploss
   * and variety (value can be regular, bo, co, amo)
   * place order will return order model which will have only orderId in the order model
   * Following is an example param for LIMIT order,
   * if a call fails then KiteException will have error message in it
   * Success of this call implies only order has been placed successfully, not order execution. */

   OrderParams orderParams = new OrderParams();
   orderParams.quantity = 1;
   orderParams.orderType = Constants.ORDER_TYPE_LIMIT;
   orderParams.tradingsymbol = "ASHOKLEY";
   orderParams.product = Constants.PRODUCT_CNC;
   orderParams.exchange = Constants.EXCHANGE_NSE;
   orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY;
   orderParams.validity = Constants.VALIDITY_DAY;
   orderParams.price = 122.2;
   orderParams.triggerPrice = 0.0;
   orderParams.tag = "myTag"; //tag is optional and it cannot be more than 8 characters and only alphanumeric is allowed

   Order order = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR);
   System.out.println(order.orderId);

For more details, take a look at Examples.java in sample directory.

WebSocket live streaming data

 /** To get live price use websocket connection.
         * It is recommended to use only one websocket connection at any point of time and make sure you stop connection, once user goes out of app.
         * custom url points to new endpoint which can be used till complete Kite Connect 3 migration is done. */
        KiteTicker tickerProvider = new KiteTicker(kiteConnect.getAccessToken(), kiteConnect.getApiKey());

        tickerProvider.setOnConnectedListener(new OnConnect() {
            @Override
            public void onConnected() {
                /** Subscribe ticks for token.
                 * By default, all tokens are subscribed for modeQuote.
                 * */
                tickerProvider.subscribe(tokens);
                tickerProvider.setMode(tokens, KiteTicker.modeFull);
            }
        });

        tickerProvider.setOnDisconnectedListener(new OnDisconnect() {
            @Override
            public void onDisconnected() {
                // your code goes here
            }
        });

        /** Set listener to get order updates.*/
        tickerProvider.setOnOrderUpdateListener(new OnOrderUpdate() {
            @Override
            public void onOrderUpdate(Order order) {
                System.out.println("order update "+order.orderId);
            }
        });

        tickerProvider.setOnTickerArrivalListener(new OnTicks() {
            @Override
            public void onTicks(ArrayList<Tick> ticks) {
                NumberFormat formatter = new DecimalFormat();
                System.out.println("ticks size "+ticks.size());
                if(ticks.size() > 0) {
                    System.out.println("last price "+ticks.get(0).getLastTradedPrice());
                    System.out.println("open interest "+formatter.format(ticks.get(0).getOi()));
                    System.out.println("day high OI "+formatter.format(ticks.get(0).getOpenInterestDayHigh()));
                    System.out.println("day low OI "+formatter.format(ticks.get(0).getOpenInterestDayLow()));
                    System.out.println("change "+formatter.format(ticks.get(0).getChange()));
                    System.out.println("tick timestamp "+ticks.get(0).getTickTimestamp());
                    System.out.println("tick timestamp date "+ticks.get(0).getTickTimestamp());
                    System.out.println("last traded time "+ticks.get(0).getLastTradedTime());
                    System.out.println(ticks.get(0).getMarketDepth().get("buy").size());
                }
            }
        });

        tickerProvider.setTryReconnection(true);
        //maximum retries and should be greater than 0
        tickerProvider.setMaximumRetries(10);
        //set maximum retry interval in seconds
        tickerProvider.setMaximumRetryInterval(30);

        /** connects to com.zerodhatech.com.zerodhatech.ticker server for getting live quotes*/
        tickerProvider.connect();

        /** You can check, if websocket connection is open or not using the following method.*/
        boolean isConnected = tickerProvider.isConnectionOpen();
        System.out.println(isConnected);

        /** set mode is used to set mode in which you need tick for list of tokens.
         * Ticker allows three modes, modeFull, modeQuote, modeLTP.
         * For getting only last traded price, use modeLTP
         * For getting last traded price, last traded quantity, average price, volume traded today, total sell quantity and total buy quantity, open, high, low, close, change, use modeQuote
         * For getting all data with depth, use modeFull*/
        tickerProvider.setMode(tokens, KiteTicker.modeLTP);

        // Unsubscribe for a token.
        tickerProvider.unsubscribe(tokens);

        // After using com.zerodhatech.com.zerodhatech.ticker, close websocket connection.
        tickerProvider.disconnect();

For more details about the different mode of quotes and subscribing for them, take a look at Examples in sample directory.

Breaking changes from 3.2.1 to 3.3.1

Margin calculation data

version 3.3.1 version 3.2.1
option_premium(double) optionPremium(double)

Breaking changes from 3.1.14 to 3.2.1

Holding (model)

version 3.1.14 version 3.2.1
lastPrice(String) lastPrice(Double)
t1Quantity(String) t1Quantity(int)
pnl(String) pnl(Double)
quantity(String) quantity(int)
averagePrice(String) averagePrice(Double)
  • Removed:
version 3.1.14 version 3.2.1
accountId NA
Tick (model)
version 3.1.14 version 3.2.1
volumeTradedToday(double) volumeTradedToday(long)
  • Change attribute for indices tick will have change percent value against the previously sent absolute change value.

Order (model)

  • Removed:
version 3.1.14 version 3.2.1
userId NA
symbol NA

Breaking changes from version 2 to version 3

Place order (bracket order) parameters

version 2 version 3
squareoff_value squareoff
stoploss_value stoploss

Model name changes

version 2 version 3
MfHolding MFHolding
MfInstrument MFInstrument
MfOrder MFOrder
MfSip MFSIP
Order (model)
  • The orderTimestamp is now Date type.
  • The exchangeTimestamp is now Date type.

Trades (model)

  • The orderTimestamp is now fillTimestamp.
  • The exchangeTimestamp is now Date type.

MFOrder (model)

  • The orderTimestamp is now Date type.
  • The exchangeTimestamp is now Date type.

MFSIP (model)

  • The created is now Date type.
  • The Date is now Date type.

MFInstrument (model)

  • The purchase_allowed is now boolean type.
  • The redemption_allowed is now boolean type.
  • The last_price_date is now Date type.

Instrument (model)

  • The expiry is now Date type.

Package name changes

version 2 version 3
com.rainmatter.kitehttp com.zerodhatech.kiteconnect.kitehttp
com.rainmatter.utils com.zerodhatech.kiteconnect.utils
com.rainmatter.kiteconnect com.zerodhatech.kiteconnect
com.rainmatter.ticker com.zerodhatech.kiteconnect
com.rainmatter.models com.zerodhatech.models

Method name changes

version 2 version 3
requestAccessToken generateSession
modifyProduct convertPosition
getOrder getOrderHistory
getTrades(order_id) getOrderTrades(order_id)
getMfOrders getMFOrders
getMfOrder getMFOrder
getMfSips getMFSIPs
getMfSip getMFSIP
modifySip modifySIP
cancelSip cancelSIP
getMfInstruments getMFInstruments

Method with signature change

version 2
placeOrder
modifyOrder
cancelOrder
convertPosition
getTriggerRange
getHistoricalData
placeMFOrder
placeMFSIP
modifyMFSIP

For more details about each method go to KiteConnect.java

Funds (model)

version 2 version 3
Margins Margin

User (model)

  • UserModel is now User.
version 2 version 3
product products
exchange exchanges
orderType orderTypes
passwordReset NA
memberId NA
NA apiKey
  • loginTime is now of Date type.

Position (model)

Added new fields

version 3
dayBuyQuantity
daySellQuantity
dayBuyPrice
daySellPrice
dayBuyValue
daySellValue
value

Kite Ticker (Websockets)

  • Kite Ticker is now authenticated using access_token and not public_token.

Version 2:

KiteConnect kiteSdk = new KiteConnect("your_apiKey");

Version 3:

KiteTicker tickerProvider = new KiteTicker(kiteConnect.getUserId(), kiteConnect.getAccessToken(), kiteConnect.getApiKey());
  • Order postbacks are now streamed on Kite Ticker.

  • Added new fields in full mode.

version 3
lastTradedTime
openInterest
oiDayHigh
oiDayLow
tickTimestamp
  • Changes:
version 2 version 3
OnTick OnTicks
setTimeIntervalForReconnection NA
NA setMaximumRetryInterval
netPriceChangeFromClosingPrice change

Quote

  • Quote will accept multiple params and returns a map of Quote model.
  • Added new fields open interest, tick timestamp, last traded time, average price, day high OI, day low OI.
  • lastTradedPrice is now lastPrice.
version 3
instrumentToken
timestamp
averagePrice
oiDayHigh
oiDayLow
  • Changes:
version 2 version 3
lastTime(String) lastTradedTime(Date)
changePercent NA
depth(Map<String, ArrayList>) depth(MarketDepth type)
  • Removed:
version 2 version 3
IndicesQuote NA

Profile

  • Added new profile API call to fetch user details.

Trigger range

  • Trigger range API supports fetching trigger range for multiple instruments in one request.

TriggerRange (model)

version 2 version 3
start lower
end upper
percent percentage

More Repositories

1

pykiteconnect

The official Python client library for the Kite Connect trading APIs
Python
981
star
2

dungbeetle

A distributed job server built specifically for queuing and executing heavy SQL read jobs asynchronously. Separate out reporting layer from apps. MySQL, Postgres, ClickHouse.
Go
506
star
3

kiteconnectjs

The official typescript client library for the Kite Connect trading APIs
TypeScript
314
star
4

gokiteconnect

Official Go client for Kite Connect API's
Go
176
star
5

nomad-cluster-setup

Terraform modules for creating Nomad servers and clients nodes on AWS.
HCL
144
star
6

frappe-attachments-s3

A frappe app to upload file attachments in doctypes to s3.
Python
121
star
7

logf

Extremely fast, light weight, zero alloc logfmt logging library for Go.
Go
91
star
8

gchatgpt

Google Chat bot for OpenAI ChatGPT
Go
81
star
9

fastglue

Fastglue is an opinionated, bare bones wrapper that glues together fasthttp and fasthttprouter to act as a micro HTTP framework.
Go
80
star
10

dotnetkiteconnect

.NET library for Kite connect
C#
78
star
11

kaf-relay

Replicate and sync Kafka topics between clusters in realtime. Supports topic re-mapping, healthchecks, and hot failovers for high availability.
Go
67
star
12

kite-connect-python-example

Kite connect Python client example
Python
62
star
13

simplesessions

simplesessions is a Go session management library that is completely agnostic of HTTP libraries and frameworks, backend stores, and even cookie jars.
Go
62
star
14

rbiparser

A utility for downloading, parsing and sanitizing bank database (IFSC, MICR, address etc.) Excel sheets from the RBI website.
Python
54
star
15

zerodhatech.github.io

The zerodha.tech blog
HTML
48
star
16

cppkiteconnect

C++ Kite Connect API library / SDK
C++
47
star
17

kiteconnect-rs

The official Rust client library for the Kite Connect trading APIs
Rust
45
star
18

jpdfsigner

A HTTP server and a CLI for digitally signing PDFs.
Java
43
star
19

phpkiteconnect

The official PHP client library for the Kite Connect trading APIs
PHP
43
star
20

fastcache

fastcache is an HTTP response caching package that plugs into fastglue that simplifies "dumb" caching of API endpoints.
Go
34
star
21

py-frappe-client

Frappe client for humans
Python
31
star
22

pdf_text_overlay

pdf_text_overlay is a python library to write text on top of pdf.
Python
27
star
23

vendor-payments

A frappe app that has workflows and reports to make payments to vendors by a company and track them
Python
26
star
24

kiteconnect-mocks

Mock responses for kiteconnect
25
star
25

mii-lama

A tool for posting metrics from node-exporter to LAMA (Indian stock market regulatory framework) API gateways
Go
19
star
26

rms-consolidated-scrips-status

A utility that parse Zerodha Consolidated google spreadsheets and render category-wise scrip details(margins, multiplier, etc)
Python
19
star
27

fastglue-csrf

CSRF middleware for https://github.com/zerodha/fastglue
Go
15
star
28

nithinkamath.me

HTML
13
star
29

fastglue-metrics

Prometheus Metrics exposed for Fastglue HTTP Handlers.
Go
12
star
30

subscription_coupons

Subscription discount coupon code manager
Python
11
star
31

osticket-autoassign

Osticket plugin to assign tickets automatically to random agents based on teams, department, and activity
PHP
11
star
32

osticket-archive

A utility to archive all closed tickets beyond a certain age to disk (including attachments) and delete them from the database. The tickets are archived as JSON files.
PHP
8
star
33

flask-kiteconnect

Flask extension for kiteconnect API
Python
7
star
34

python-wheels

Python wheels used in other Python projects
5
star
35

kite-discourse-sso

Discourse SSO in Go for Kite Connect. Serves as a template for implementing other Discourse integrations.
Go
5
star
36

fastglue-adapter

net/http adapter for fastglue
Go
3
star
37

pdfrender

Python
2
star