keepAlive sample code needed

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Neophyte
    Junior Member
    • Sep 2016
    • 12

    #1

    keepAlive sample code needed

    I am still struggling to understand the instructions for the API. I have a working app but it stops every few hours because I cannot work out how to operate keepAlive. The best I can understand is to treat it like any other operation eg listMarketBook and run it at intervals. So using Javascript and node that is what I have done and the relevant lines of code are shown below. Trouble is I get a No Such Operation error report and the whole thing comes to a halt.

    To log in I am logging in to the website manually and then generating a Session Token which is the ssid in options. I can then run every other Exchange Operation using the code below with whatever exchange operation it is substituting for keepAlive.

    I have searched the forum for a program example of how to do keepAlive with no success and hope someone can explain where I am going wrong.

    I get exactly the same error code DSC-0021 if I run keepAlive directly so I believe the problem is with function keepAlive(options) rather than the syntax of my setInterval


    var options = {
    hostname: 'api.betfair.com',
    port: 443,
    path: '/exchange/betting/json-rpc/v1',
    method: 'POST',
    headers: {
    'X-Application' : appkey,
    'Accept': 'application/json',
    'Content-type' : 'application/json',
    'X-Authentication' : ssid
    }
    }

    setInterval(keepAlive,1000*60*15,options);


    function constructJsonRpcRequest(operation, params) {
    return '{"jsonrpc":"2.0","method":"SportsAPING/v1.0/' + operation + '", "params": ' + params + ', "id": 1}';
    }

    function keepAlive(options) {

    var str = '';
    var requestFilters = '{"filter":{}}';
    var jsonRequest = constructJsonRpcRequest('keepAlive', requestFilters );
    var req = https.request(options,function (res){
    res.setEncoding(DEFAULT_ENCODING);
    res.on('data', function (chunk) {
    str += chunk;
    });
    res.on('end', function (chunk) {
    var response = JSON.parse(str);
    handleError(response);
    console.log("keep Alive = ");
    console.log(JSON.stringify(response, null, DEFAULT_JSON_FORMAT));

    });
    });
    req.write(jsonRequest, DEFAULT_ENCODING);
    req.end();
    req.on('error', function(e) {
    console.log('Problem with request: ' + e.message);
    });

    } // end of keepAlive
  • jabe
    Senior Member
    • Dec 2014
    • 705

    #2
    The KeepAlive, like Login and Logout*, has is own URL:

    https://identitysso.betfair.com/api/keepAlive

    When I've completed the current code input and can make my program run, I'll get hold of the JSON string and post it on here for you.


    * not that I have logout working...

    Comment

    • Grantay.
      Junior Member
      • Jan 2010
      • 53

      #3
      KeepAlive Function

      Here is a vb.net function I use in my code...

      Code:
       Public Function KeepAlive() As String
      
              Dim Url As String = "https://identitysso.betfair.com/api/keepAlive"
      
              Dim request As System.Net.HttpWebRequest = Nothing
              Dim response As WebResponse = Nothing
              Dim strResponseContent As String = ""
              Dim strResponseStatus As String = ""
      
              Dim responseFromServer As String = ""
              Try
                  request = WebRequest.Create(New Uri(Url))
                  System.Net.ServicePointManager.Expect100Continue = False
                  With request
                      .Method = "POST"
                      .Accept = "application/json"
                      .Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
                      .Headers.Add("X-Authentication", Constants.sessionToken)
                      'request.Headers.Add("X-Authentication", Constants.appId)
                      response = request.GetResponse
                  End With
      
                  '~~>Dim strShowResponse as String = responseFromServer  '~~>If required
              Catch ex As APINGException
                  '~~> Show any errors in this method for an error log etc Just use a messagebox for now
                  MsgBox("CreateRequest APINGException Error" & vbCrLf & ex.Message)
              Catch ex As System.Exception
                  MsgBox("CreateRequest Error" & vbCrLf & ex.Message)
              End Try
              Return responseFromServer   '~~> Function Output
          End Function

      Comment

      • Neophyte
        Junior Member
        • Sep 2016
        • 12

        #4
        Thanks to both of you. I still can’t get the forum to email me when there is a response so I didn’t know these replies were here.

        I think I may have solved this now and set out my reasoning and code below.

        I was trying to use my code for exchange operations modified for keepAlive whereas a better starting point would have been login code which I was not using because I was doing a manual login. However I had attempted automatic login in the past which failed because of certificate problems so I dug out the code and compared endpoints.

        Endpoint for keepAlive https://identitysso.betfair.com/api/keepAlive

        endpoint for login https://identitysso.betfair.com/api/login

        endpoint for betting operations

        https://api.betfair.com/exchange/betting/json-rpc/v1

        The endpoint for betting operations is quite different because api is part of the hostname whereas for the others it is part of the path. Here is my final code which I believe works but only time will tell. I found that you do not include https:// as part of the hostname maybe because right at the start of the program I have

        var https = require('https');

        setInterval(keepAlive,1000*60*15);

        function keepAlive() {

        var options = {

        hostname: 'identitysso.betfair.com',
        path: '/api/keepAlive',
        method: 'POST',
        headers: {
        'X-Application' : appkey,
        'Accept': 'application/json',
        'Content-type' : 'application/json',
        'X-Authentication' : ssid
        }
        }

        var req = https.request(options, function(res)
        {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        });
        });

        req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
        });

        req.end();
        } //end of keepAlive

        And here is the response

        STATUS: 200
        HEADERS: {"content-type":"application/json","content-length":"115","date":"Wed, 14 Sep 2016 11:08:27 GMT","connection":"close"}
        BODY: {"token":"ssid","product":"appkey","status":"SUCCE SS","error":""}

        Comment

        • SimonN
          Junior Member
          • Dec 2014
          • 71

          #5
          What's the point of keep alive?

          Why not just repeatedly resubmit (every 3.5 hours)
          'https://identitysso.betfair.com/api/certlogin'?
          What am I missing here?
          Last edited by SimonN; 14-09-2016, 06:39 PM.

          Comment

          • betdynamics
            Junior Member
            • Sep 2010
            • 534

            #6
            KeepAlive keeps your CURRENT session active.

            Resubmitting the login would create a new session and, unless you logged out of the old session, would result in there being an increase in the number of active sessions held on the Betfair servers.

            The old session would expire at some point (presumably after 4 hours) but why burden the servers with more sessions than are needed?

            From a Betfair technical perspective, I'm sure that processing the KeepAlive is much easier/faster than performing a complete authentication of the user.

            Comment

            • jptrader
              Junior Member
              • Nov 2009
              • 82

              #7
              Also, for the stream API, a new session would mean that the initial images for every market would have to be resent.

              Comment

              • merecat_
                Junior Member
                • May 2009
                • 35

                #8
                "What's the point of keep alive?"

                At a guess I expect it would be marginally quicker than logging in again

                Looks like you have it working, anyway here's my options parcel...

                config.methods[constants.API_ALIVE] = {
                host : "identitysso.betfair.com",
                port : 443,
                path : "/api/keepAlive",
                method : "POST",
                headers : {
                'X-Authentication': sessionToken,
                'X-Application': 'XXXX',
                'Accept': 'application/json'
                }
                };

                Comment

                • merecat_
                  Junior Member
                  • May 2009
                  • 35

                  #9
                  BTW on my system...

                  login == ~390ms

                  keep alive == ~27ms

                  Quite a bit quicker!

                  Comment

                  • bnl
                    Junior Member
                    • Nov 2012
                    • 108

                    #10
                    To log in I am logging in to the website manually and then generating a Session Token which is the ssid in options. I can then run every other Exchange Operation using the code below with whatever exchange operation it is substituting for keepAlive.
                    Why don't you run login (the manual way) from your code
                    and parse the resulting ssoid from it ? That will save you from
                    manually login every time.

                    /Björn

                    Comment

                    • SimonN
                      Junior Member
                      • Dec 2014
                      • 71

                      #11
                      Greetings,

                      Do we have or may I ask anyone to share keep alive and logout code in C#?

                      I'm just not experienced enough to be able to figure it out without an example.

                      Much appreciated.

                      Simon

                      EDIT: Is there any reason why I couldn't simply make a CURL call from the C# code in a batch file or something using the keep alive sample in the documentation?
                      Last edited by SimonN; 22-09-2016, 03:59 AM.

                      Comment

                      • jabe
                        Senior Member
                        • Dec 2014
                        • 705

                        #12
                        These came up when I searched for free converters. Might save you time in future. That said, I'm sure someone will come up with the code for you.

                        http://converter.telerik.com/
                        http://www.developerfusion.com/tools.../vb-to-csharp/
                        http://www.carlosag.net/tools/codetranslator/

                        My logout doesn't work. I always have to login when I run my program because of the way it's coded, but I'm changing it to read a saved ssio and try it in a KeepAlive call, and if that works, it won't make me log in again.

                        Comment

                        • betdynamics
                          Junior Member
                          • Sep 2010
                          • 534

                          #13
                          *** WARNING - UNTESTED CODE ***

                          Create a generic routine to handle the calls (note - this could also be used for other calls to the API)

                          Code:
                          private static readonly string KEEPALIVE_ENDPOINT = @"https://identitysso.betfair.com/api/keepAlive";
                          private static readonly string LOGOUT_ENDPOINT = @"https://identitysso.betfair.com/api/logout";
                          
                          private string InvokeJSONAPI(string endpoint, string appKey, string sessionId, string jsonData)
                          {
                            string responseText = String.Empty;
                          
                            try
                            {
                              System.Net.ServicePointManager.Expect100Continue = false;
                          
                              HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
                              request.Method = "POST";
                              request.Timeout = 5000;
                              request.ContentType = "application/json";
                              request.Accept = "application/json";
                              request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                              request.KeepAlive = true;
                              request.Headers.Add("Accept-Encoding", "gzip, deflate");
                              request.Headers.Add("X-Application", appKey);
                              request.Headers.Add("X-Authentication", sessionId);
                              if (String.IsNullOrEmpty(jsonData) == false)
                              {
                                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                                {
                                  streamWriter.Write(jsonData);
                                }
                              }
                          
                              using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                              {
                                using (var streamReader = new StreamReader(response.GetResponseStream()))
                                {
                                  responseText = streamReader.ReadToEnd();
                                }
                              }
                            }
                            catch (System.Exception e)
                            {
                              // Error handling
                            }
                          
                            return responseText;
                          }
                          Then you can call them like this:

                          KeepAlive
                          Code:
                          string response = InvokeJSONAPI(KEEPALIVE_ENDPOINT, appKey, sessionId, null);
                          Logout
                          Code:
                          string response = InvokeJSONAPI(LOGOUT_ENDPOINT, appKey, sessionId, null);
                          Don't forget that the response will be a json string and, therefore, needs to be decoded.

                          If using the generic routine for other calls to the API, you may need to adjust the timeout value (especially if betting InPlay on football matches)
                          Last edited by betdynamics; 22-09-2016, 11:10 AM.

                          Comment

                          • SimonN
                            Junior Member
                            • Dec 2014
                            • 71

                            #14
                            Thank you very much indeed, betdynamics and jabe.

                            Had the chance to plug your code in betdynamics and it's working beautifully!!

                            Sooooooooo grateful, Thank you again.
                            Last edited by SimonN; 23-09-2016, 04:25 AM. Reason: Edit> Working!

                            Comment

                            • SimonN
                              Junior Member
                              • Dec 2014
                              • 71

                              #15
                              Just looking at your code, betdynamics, I notice that you have..

                              Code:
                              System.Net.ServicePointManager.Expect100Continue = false;
                              I see that Best Practice advises that:

                              You should be aware that if using the .Net Framework you will need to set the relevant property in the ServicePointManager which then prevents the "Expect" header from being added:
                              Looking at the C# sample non interactive login code, I can't see anywhere they actually use this.

                              Is it definitely needed in that case and, if so, how/where do I insert/integrate it with the sample non interactive code?

                              https://github.com/betfair/API-NG-sa...ractive-cSharp

                              Thank you..

                              Comment

                              Working...
                              X