How can I use kiteSDK in spring application to trade with zerodha

amoldadas
I am trying to complete login process as per sample code given https://github.com/rainmattertech/javakiteconnect here, but I am getting this : com.rainmatter.kitehttp.exceptions.KiteNoNetworkException. Please give me sample code to get access token through java if any body has.

Thanks.
  • sujith
    Hi @amoldadas,
    It is mandatory by the exchange that a trader has to manually login at least once a day. We don't recommend automating login.
    You will have to get login URL and paste it in the browser or open in webview and after manual login user will get request token in redirect URL specified while creating the app which is valid for one-time and lasts few minutes.
    Use the request token to get the access token which has a validity of one day and you can check out the example for making the API call for access token here.
    Once you get access token store it in preferences for further use, don't call requestAccessToken everytime you run the app.
  • sun04
    @amoldadas I've been facing the same issue as yours. Getting KiteNoNetworkException while trying to get access token. Could you help me on how you resolved it?
  • amoldadas
    Please help me

    I am getting following error in stack trace, I got request token from browser after htting URL (https://kite.trade/connect/login?api_key=)

    Jul 22, 2017 7:14:35 PM org.apache.http.impl.execchain.RetryExec execute
    INFO: I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.kite.trade:443: Software caused connection abort: socket write error
    Jul 22, 2017 7:14:35 PM org.apache.http.impl.execchain.RetryExec execute
    INFO: Retrying request to {s}->https://api.kite.trade:443

    My code is below :

    package com.autotrader.robo.kite;

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.Arrays;

    import org.apache.http.HttpHost;
    import org.json.JSONException;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;

    import com.neovisionaries.ws.client.WebSocketException;
    import com.rainmatter.kiteconnect.KiteConnect;
    import com.rainmatter.kitehttp.SessionExpiryHook;
    import com.rainmatter.kitehttp.exceptions.KiteException;
    import com.rainmatter.models.UserModel;
    import java.security.GeneralSecurityException;

    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import sun.misc.*;
    /**
    * Created by sujith on 7/10/16.
    * This class has example of how to initialize kiteSdk and make rest api calls to place order, get orders, modify order, cancel order,
    * get positions, get holdings, convert positions, get instruments, logout user, get historical data dump, get trades
    */
    public class Test {
    private static final String API_KEY = "my api key";
    private static final String API_SECRET = "api secret";

    public static void main(String[] args){
    try {
    // 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.
    // Initialize KiteSdk with your apiKey.
    KiteConnect kiteconnect = new KiteConnect(API_KEY);

    // set userId
    kiteconnect.setUserId("ZO7849");

    //set proxy is optional, if you want to set proxy.
    //kiteconnect.setProxy(new HttpHost("localhost"));

    // Get login url
    //String url = kiteconnect.getLoginUrl();
    // getRequestToken(url);
    // Set session expiry callback.
    kiteconnect.registerHook(new SessionExpiryHook() {
    public void sessionExpired() {
    System.out.println("session expired");
    }
    });

    //String accessToken = kiteconnect.getAccessToken();
    // Set request token and public token which are obtained from login process.
    String hmacData = "";
    try {
    hmacData = generateHmacSHA256Signature(API_KEY+"request token"+API_SECRET, API_KEY);
    } catch (GeneralSecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    UserModel userModel = kiteconnect.requestAccessToken("request token", API_SECRET);

    kiteconnect.setAccessToken(userModel.accessToken);
    kiteconnect.setPublicToken(userModel.publicToken);

    Examples examples = new Examples();
    examples.getMargins(kiteconnect);

    examples.placeOrder(kiteconnect);

    examples.placeBracketOrder(kiteconnect);

    examples.getTriggerRange(kiteconnect);

    examples.placeCoverOrder(kiteconnect);

    examples.getOrders(kiteconnect);

    examples.getTrades(kiteconnect);

    examples.getTradesWithOrderId(kiteconnect);

    examples.modifyOrder(kiteconnect);

    examples.cancelOrder(kiteconnect);

    examples.getPositions(kiteconnect);

    examples.getHoldings(kiteconnect);

    examples.modifyProduct(kiteconnect);

    examples.getAllInstruments(kiteconnect);

    examples.getInstrumentsForExchange(kiteconnect);

    examples.getQuote(kiteconnect);

    examples.getHistoricalData(kiteconnect);

    examples.logout(kiteconnect);

    examples.tickerUsage(kiteconnect);

    } catch (KiteException e) {
    System.out.println(e.message);
    } catch (JSONException e){
    e.printStackTrace();
    } catch (WebSocketException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    public static String generateHmacSHA256Signature(String data, String key) throws GeneralSecurityException {
    byte[] hmacData = null;

    try {
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(secretKey);
    hmacData = mac.doFinal(data.getBytes("UTF-8"));
    return new BASE64Encoder().encode(hmacData);
    } catch (UnsupportedEncodingException e) {
    // TODO: handle exception
    throw new GeneralSecurityException(e);
    }
    }
    }

    Thanks,
    Amol
Sign In or Register to comment.