Kite Connect Java Client

repository·master·Indexed 42 days ago

https://github.com/zerodha/javakiteconnect

The official Java SDK (v4.0.1) for interacting with Zerodha's Kite Connect REST APIs and WebSockets. It provides developers with tools for real-time order execution, portfolio management, and live market data streaming via KiteTicker. The library supports Maven and Android integration, offering features such as session authentication, order placement with auto-slice capabilities, and multiple market data quote modes (LTP, Quote, and Full).

Tokens
3.1K
Snippets
8
Records
12
Agent score
4%

What's inside Kite Connect

  1. Install the Kite Connect Java client

    master

    You can include the Kite Connect library in your project using Maven or by manually adding the JAR file. For Android development, you must include the JAR in your libs directory and update your Gradle configuration.

    ### Maven
    
    ```xml
    <!-- https://central.sonatype.com/artifact/com.zerodhatech.kiteconnect/kiteconnect -->
    <dependency>
        <groupId>com.zerodhatech.kiteconnect</groupId>
        <artifactId>kiteconnect</artifactId>
        <version>4.0.1</version>
    </dependency>

    Android

    Add the following line to your module's build.gradle file:

    compile files('libs/kiteconnect.jar')
  2. Migrate Order placement from 3.5.1 to 4.0.0

    master

    In version 4.0.0, the placeOrder(...) method signature changed its return type. It no longer returns an Order object; it now returns an OrderResponse object. To access the order ID, use orderResponse.orderId.

    // Before 4.0.0
    Order order = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR);
    System.out.println(order.orderId);
    
    // After 4.0.0
    OrderResponse orderResponse = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR);
    System.out.println(orderResponse.orderId);
  3. Migrate Kite Ticker (Websockets) from version 2 to 3

    master

    In version 3, the KiteTicker authentication mechanism changed. It now requires access_token instead of public_token. You must initialize the KiteTicker using the user ID, access token, and API key obtained from the KiteConnect instance.

    Additionally:

    • Order postbacks are now streamed directly on the KiteTicker.
    • The OnTick callback was renamed to OnTicks.
    • netPriceChangeFromClosingPrice was renamed to change.
    • setTimeIntervalForReconnection was replaced by setMaximumRetryInterval.
    // Version 2
    KiteConnect kiteSdk = new KiteConnect("your_apiKey");
    
    // Version 3
    KiteTicker tickerProvider = new KiteTicker(kiteConnect.getUserId(), kiteConnect.getAccessToken(), kiteConnect.getApiKey());
  4. Initialize KiteConnect and authenticate a session

    master

    To use the SDK, initialize KiteConnect with your apiKey, set your userId, and obtain a login URL. After the user authenticates via the login URL, use the resulting request_token and your api_secret to generate a session. Once the session is generated, set the accessToken and publicToken on the KiteConnect instance to authorize subsequent API calls.

    // Initialize Kiteconnect using apiKey.
    KiteConnect kiteSdk = new KiteConnect("your_apiKey");
    
    // Set userId.
    kiteSdk.setUserId("your_userId");
    
    // Get login url. Use this url in webview to login user.
    String url = kiteSdk.getLoginUrl();
    
    // Get accessToken using request_token and api_secret
    User user = kiteSdk.generateSession("request_token", "your_apiSecret");
    
    // Set request token and public token obtained from login process.
    kiteSdk.setAccessToken(user.accessToken);
    kiteSdk.setPublicToken(user.publicToken);
    
    // Set session expiry callback.
    kiteSdk.setSessionExpiryHook(new SessionExpiryHook() {
        @Override
        public void sessionExpired() {
            System.out.println("session expired");                    
        }
    });
  5. Use Auto-slice orders in 4.0.0

    master

    The dedicated placeAutoSliceOrder(...) API has been removed in version 4.0.0. Auto-slice functionality is now integrated into the standard placeOrder(...) method. To use it, set the autoslice field to true within your orderParams object.

    Key details:

    • Child sliced order results are accessible via orderResponse.children.
    • Child-level failures are returned in BulkOrderResponse.bulkOrderError and are not thrown as KiteException.
    // Instead of placeAutoSliceOrder, use placeOrder with autoslice set to true
    orderParams.autoslice = true;
    OrderResponse orderResponse = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR);
  6. Stream live market data with KiteTicker

    master

    Use KiteTicker to establish a WebSocket connection for real-time market data. You must provide the accessToken and apiKey. The workflow involves setting up listeners for connection status, order updates, and incoming ticks, then calling connect().

    Key Lifecycle Methods:

    • connect(): Starts the WebSocket connection.
    • disconnect(): Closes the connection.
    • subscribe(tokens): Subscribes to specific tokens.
    • unsubscribe(tokens): Unsubscribes from tokens.
    • setMode(tokens, mode): Sets the data granularity for specific tokens.

    Reconnection Settings:

    • setTryReconnection(true): Enables automatic reconnection.
    • setMaximumRetries(int): Sets the max number of retry attempts.
    • setMaximumRetryInterval(int): Sets the max interval between retries in seconds.
    KiteTicker tickerProvider = new KiteTicker(kiteConnect.getAccessToken(), kiteConnect.getApiKey());
    
    tickerProvider.setOnConnectedListener(new OnConnect() {
        @Override
        public void onConnected() {
            tickerProvider.subscribe(tokens);
            tickerProvider.setMode(tokens, KiteTicker.modeFull);
        }
    });
    
    tickerProvider.setOnTickerArrivalListener(new OnTicks() {
        @Override
        public void onTicks(ArrayList<Tick> ticks) {
            if(!ticks.isEmpty()) {
                System.out.println("Last price: " + ticks.get(0).getLastTradedPrice());
            }
        }
    });
    
    tickerProvider.setTryReconnection(true);
    
    tickerProvider.connect();
  7. Migrate from version 2 to version 3

    master

    Major migration guide for moving from version 2 to version 3 of the Java client. Key changes include:

    Package Name Changes:

    • com.rainmatter.kiteconnect $\rightarrow$ com.zerodhatech.kiteconnect
    • com.rainmatter.models $\rightarrow$ com.zerodhatech.models
    • (Other com.rainmatter.* packages also moved to com.zerodhatech.kiteconnect.*)

    Method Name Changes:

    • requestAccessToken $\rightarrow$ generateSession
    • getOrder $\rightarrow$ getOrderHistory
    • getTrades(order_id) $\rightarrow$ getOrderTrades(order_id)
    • getMfOrders $\rightarrow$ getMFOrders
    • modifySip $\rightarrow$ modifySIP

    Model and Type Changes:

    • Many timestamp fields (e.g., orderTimestamp, exchangeTimestamp, created, loginTime) changed from String to Date type.
    • UserModel was renamed to User.
    • Funds model Margins was renamed to Margin.
    • User model: product $\rightarrow$ products, exchange $\rightarrow$ exchanges, orderType $\rightarrow$ orderTypes.
    • Instrument model: expiry is now Date type.

    Bracket Order Parameters:

    • squareoff_value $\rightarrow$ squareoff
    • stoploss_value $\rightarrow$ stoploss
  8. Place an order using KiteConnect

    master

    To place an order, populate an OrderParams object with required fields such as tradingsymbol, exchange, transactionType, orderType, quantity, product, price, and validity. Use the placeOrder method, specifying the order variety (e.g., Constants.VARIETY_REGULAR). Note that a successful call implies the order was placed, not necessarily executed. If the call fails, a KiteException will be thrown.

    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"; // Optional: max 8 alphanumeric chars
    
    Order order = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR);
    System.out.println(order.orderId);
  9. Breaking changes in 3.2.1: Model field updates

    master

    Version 3.2.1 introduced several type changes and removals in core models:

    Holding Model Updates:

    • lastPrice: String $\rightarrow$ Double
    • t1Quantity: String $\rightarrow$ int
    • pnl: String $\rightarrow$ Double
    • quantity: String $\rightarrow$ int
    • averagePrice: String $\rightarrow$ Double
    • Removed: accountId

    Tick Model Updates:

    • volumeTradedToday: double $\rightarrow$ long
    • Indices tick change attribute now provides percentage instead of absolute value.

    Order Model Updates:

    • Removed: userId, symbol
  10. Breaking changes in 3.3.1: Margin calculation

    master

    In version 3.3.1, the field name for option premium in margin calculation data was updated from camelCase to snake_case with a double type:

    version 3.3.1version 3.2.1
    option_premium(double)optionPremium(double)
  11. Configure KiteTicker quote modes

    master

    The KiteTicker supports three modes for data subscription via setMode(tokens, mode). Choosing the correct mode optimizes bandwidth based on your needs:

    • KiteTicker.modeLTP: Provides only the Last Traded Price.
    • KiteTicker.modeQuote: Provides Last Traded Price, last traded quantity, average price, volume traded today, total sell/buy quantity, open, high, low, close, and change.
    • KiteTicker.modeFull: Provides all data including market depth.
    // Example modes
    tickerProvider.setMode(tokens, KiteTicker.modeLTP);
    tickerProvider.setMode(tokens, KiteTicker.modeQuote);
    tickerProvider.setMode(tokens, KiteTicker.modeFull);