Token Expires too frequent

Prem
Hi @vivek,

I woul like to know that whay my to Request Token expires too frequent. Means, After my login I get Request Token and after it I have run my program two times. First time it response for query for user detail an second time it throws Exception by showing "Request Token Expired"

Also I want to know the detail of my zerodha account such as balance in my account. Then which model I can used?

Kindly reply.
  • Vivek
    You should generate access token only once and use it to run your program multiple times. For example if you are running your strategy every five minutes then you should generate access token initially only once and use it in your program and run it multiple times.

    The reason you are getting TokenException is a given request token can be used only once to get access token and if you try to use it again it will throw the exception.
  • Prem
    Hi @vivek

    I know that but currently I am implementing by system so during this process I need to execute my program multiple times. So, when I change something in my code and want to execute then it throws "Toke Exception" But when I ping my login URL again then it will give me new "Request Token"

    So, its very frustrating to me. If I want to execute my program multiple times then first I need to ping my login URL Manually then modify my request token and then execute my program. Below is the code and When I am executing my programs more than one time then every time below line will be executed and we need to ping login URL manually again and again. I need to set RequestToken by using KiteConnect Class Method "requestAccessToken" After this I received "UserModel" then I can access "accessToken" property of this to work.

    But I don't want to ping Login URL manually again and again in my development phase. How can I restrict it only once. When first time when I execute my program manually I will do my login process by giving ID and PASSOWRD. After it my session will maintained because second time when I ping my login URL again then it simply redirects at my "REDIRECT URL" with new "REQUEST TOKEN" without asking my "ID" and "PASSWORD" again.

    But this process I need to do again and again to execute my program multiple times. But the right way is: very first time when I execute my program it give me "Request Token" at my "REDIRECT URL" after LOGIN by "ID" and "PASSWORD" an when my session is maintained then it automatically sets "Access Token" in after checking my Session via "put("api.validate", "/session/token")"

    If you understand then kindly reply. If not then I need a call to clarify this.

    Kindly reply


    public static void main(String args[]) throws ParseException, JSONException, KiteException, IOException {


    KiteConnect kiteconnect = new KiteConnect("xxxx");

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

    // Get login url
    String url = kiteconnect.getLoginUrl();

    // KiteRequest kr=new KiteRequest();

    System.out.println("Login URL=== "+url);

    // Set session expiry callback.
    kiteconnect.registerHook(new SessionExpiryHook() {
    @Override
    public void sessionExpired(String message,int errorCode) {
    System.out.println("Session expired"+errorCode);
    }
    });

    Routes routes=new Routes();

    UserModel userModel = kiteconnect.requestAccessToken("e99hojpz6teovhnfri41ub0whxww0jsm", "jdyrv6en9qxuto3eidvl0wpjvvu2g1gk");

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


    String acc_tok=kiteconnect.getAccessToken();

    String url2=(routes.get("parameters")+"?api_key="+"lkr48bh5lq9718wu"+"&access_token="+acc_tok);

    JSONObject json=new KiteRequest().getRequest(url2);

    System.out.println("User Product Type== "+json.toString());

    System.out.println("User Product Type== "+userModel.product.toString());
    System.out.println("User Exchange == "+userModel.exchange.toString());



    System.out.println("Positions"+kiteconnect.getMargins("equity").net);

    Margins margins = kiteconnect.getMargins("equity");
    System.out.println(margins.available.cash);
    System.out.println(margins.utilised.debits);
    }

    }
  • sujith
    Log access token first time you run and reuse the same by hard-coding it in code till it expires. There is no workaround other than this.
  • Vivek
    @Prem Ideally your program should store the access token centrally (database, redis etc) and access it whenever it needs. If the given access token throws TokenException then you should reinitiate the login and replace the old access token.
  • ruchanavjyot1907
    I am not able to get accessToken, could you please check my api_key, api secrete key and other parameters are correct or need to be regenerated?
    client ID: ZX7343.
  • sujith
    Hi Rucha,
    Everything looks fine with your account. Can you explain what you are trying to do?
  • ruchanavjyot1907
    I am a developing java code for automated trading.

    I completed login using API key, my password and security questions and copied the request_token from URL. While trying to get accessToken (UserModel) using request_token and api_secret_key, it is throwing below exception:

    com.TradeRobotBatch.kiteAPI.api.kitehttp.exceptions.KiteTokenException
    at com.TradeRobotBatch.kiteAPI.api.kitehttp.KiteRequest.dealWithKiteException(KiteRequest.java:224)
    at com.TradeRobotBatch.kiteAPI.api.kitehttp.KiteRequest.postRequest(KiteRequest.java:46)
    at com.TradeRobotBatch.kiteAPI.api.kiteconnect.KiteConnect.requestAccessToken(KiteConnect.java:174)
    at com.TradeRobotBatch.kiteAPI.sample.Test.main(Test.java:54)


    I am using Test.java file provided by you in API pack. If you need to check logs at your side, please note that the exception copied above has been thrown today morning around 10:00 to 11:45 AM
  • sujith
    Can you PM me your redirect url with request_token?

    PS: Make sure you are using same user_id as you have logged in. "request_token" is valid only for 5 minutes and it can only be used once to get "access_token".
  • ruchanavjyot1907
    @sujith my redirect URL is 'http://127.0.0.1' (i.e. default test url suggested while creating app).

    I use my client_ID: ZX7343 while login in order to get request_token, however my developer account login username is [email protected]. I am not sure what is to be used as userId, right now I am trying to get accessToken using my client_id (ZX7343) as userId of KiteConnect class/object, please correct me if I am going wrong here.

    Moreover, I came across one more exception on further analysis/logging which is copied below. As per my primary analysis, it seems mismatch in received JSON response and it's mapping class, could you please ask some technical expert to look into it.
    My api_key is 'rcampmcqbs2t1fqv' and if required I will provide my secret_key and other details (will not copy here) to technical analyst for further analysis.

    Exception:
    com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 319 path $.exchange
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at com.google.gson.Gson.fromJson(Gson.java:852)
    at com.google.gson.Gson.fromJson(Gson.java:801)
    at com.google.gson.Gson.fromJson(Gson.java:773)
    at com.TradeRobotBatch.kiteAPI.api.models.UserModel.parseResponse(UserModel.java:42)
    at com.TradeRobotBatch.kiteAPI.api.kiteconnect.KiteConnect.requestAccessToken(KiteConnect.java:174)
    at com.TradeRobotBatch.kiteAPI.sample.Test.main(Test.java:54)
    Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 319 path $.exchange
    at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
    at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:70)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
    ... 7 more
  • sujith
    Hi Rucha,
    After successful login, your redirect_url should look like this 'http://127.0.0.1/?status=success&request_token=265rk95bpibbkvvcp7izze3yom46khml

    You are using same client id with which you have created App, So it is correct.

    It looks like, you are not getting expected response. So there is a parsing error.

    Checkout demo login in this webinar
  • ruchanavjyot1907
    ruchanavjyot1907 edited January 2017
    Yes my redirect URL looks like similar, however I observed in above shared video that after inserting login credentials and security questions it is been redirected to screen with 'Authorize' button but I am not getting such screen rather I am being redirected to blank/error page (with error message 'Site cannot be reached') with similar URL you mentioned above. This is the only mismatch I could spot in my process and that described in this video.
  • sujith
    That doesn't have to match. It is fine. It is just a webpage, we only need url in this scenario. Can you private message redirect url? I will try using it.
  • ruchanavjyot1907
    @sujith posting this message in wider audience to help other members if anyone facing same issue.

    If user profile is configured for only one single exchange (MCX in my case) then JSON response cannot be parsed by existing API due to mismatch in mapping class (UserModel.java). The 'exchange' varibale is defined as String[] (String array) and the JSON response contains exchange as String (single String without array) and throws exception. @sujith has forwarded this issue to concerned team to fix the issue and they are working on the same.

    Moreover, I have made small change in UserModel.java at my end and I could now get accessToken and publicToken successfully without any issue, however my version of UserModel.java cannot be used for user profiles with multiple exchanges and permanent fix is required to handle both types of user profiles in single class, I hope @sujith and his team will provide the fix at earliest.

    Regards,
    Rucha.
  • ajay_varma
    Hello, my access_token is expiring frequently within a minute or two. I have created an automated trading system for personal use and since last month i do update fresh token daily morning around 9am which remains active for the whole day, but now my token is expiring very frequently within a minute. Whenever i update fresh token, my app just works smoothly and the content stops in the next minute... Please help me
  • sujith
    Hi @ajay_varma,
    Are you sure you are not calling generate access token again?
    Do you use Pi or NEST?
    Can you run your program in debug mode and check if logout call is made?
Sign In or Register to comment.