Example of writing a simple bot (step by step)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • int_main
    Junior Member
    • Apr 2013
    • 9

    #1

    Example of writing a simple bot (step by step)

    Hello dear friends I apologize in advance for my english

    In this topic, I would like to run your report on how I would write the first bot. So far, the price monitoring plans and write data to the database. Try sequentially from the beginner to describe issues and their solutions, which appeared personally in my work with the API.
  • int_main
    Junior Member
    • Apr 2013
    • 9

    #2
    The first thing we try to do is write a class that will connect to the Betfair Exchange API.

    (Before writing this class you would do well to get acquainted with such concepts as HTTP protocol and object serialization, and so on JSON)

    Comment

    • int_main
      Junior Member
      • Apr 2013
      • 9

      #3
      In order to work with the exchange so we need a session key. This is the option that allows the server to uniquely identify the client. It will be sent with each request to the server in the form of the Header, as we will periodically validate its function KeepAlive.

      (This method (Interactive Login - API Endpoint) is not the safest, according to advice developers see)

      To get the session key we need to send a request for a resource that is an Uri https://identitysso.betfair.com/api/login plus a set of parameters for the next sign ? namely, a string like "username = yourUsername & password = yourPassword"

      Resulting string looks like: https://identitysso.betfair.com/api/login?username=yourUsername&password=yourPassword

      Comment

      • kawafan
        Junior Member
        • May 2011
        • 33

        #4
        at last someone is trying to help others here , following your topic and don't worry about English mistakes . :P

        Comment

        • int_main
          Junior Member
          • Apr 2013
          • 9

          #5
          Originally posted by kawafan View Post
          at last someone is trying to help others here , following your topic and don't worry about English mistakes . :P
          Thank you my friend

          In previous posts I asked you to pay attention to the concepts of HTTP and JSON is very important ...
          Today we will send your request to exchange api action and try to make login.

          For to us a very important class is the class WebReguest. This is an a abstract class, a copy of it can be obtained only by using a special method (Create()). This method accepts a string or uri object, analyzes it and returns us to the desired instance ("http:", "https:", "ftp:" or "file" specific instance) also a small example with explanations from msdn: example

          Comment

          • int_main
            Junior Member
            • Apr 2013
            • 9

            #6
            I missed another important parameter is your developer app key.
            He will also be transmitted to each request is kind of your application ID, in order to keep a record of the software on betfair.
            How to get it? Login, Betfair on the main page, your browser will get some information in the form of a line of cookies, then follow instructions:
            1.click on the accounts api visualiser link https://developer.betfair.com/visual...nt-operations/
            2.select the createdeveloperappkeys operation from the list of operations on the top left hand side of the visualiser.
            3.enter your application name in the 'request' column.
            4.press execute at the bottom of the 'request' column.
            Last edited by int_main; 28-07-2014, 06:44 PM.

            Comment

            • int_main
              Junior Member
              • Apr 2013
              • 9

              #7
              Another important point, we have to work with the format of Json and i hope you understand what this. Work with it quite simple when there are wonderful people like the creator of this library http://james.newtonking.com/json

              All we need is to download the library and next in your solution select the menu add reference (right click mouse on References node in the Solution Explorer). You have to become available namespace Newtonsoft.Json!

              Comment

              • int_main
                Junior Member
                • Apr 2013
                • 9

                #8
                Finally, let's write his first metod, this is the beginning of our plans to conquer the world

                public static bool Login()
                {
                Uri temp_uri = new Uri(@" https://identitysso.betfair.com/api/login?username=yourUsername&password=yourPassword");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(temp_uri);

                //set required headers

                request.Method = "POST";//set the type of request

                request.Accept = "application/json";//accept format

                request.Headers.Add(string.Format("X-Application: {0}", appKey_));//your app key

                WebResponse response = null;

                try
                {
                response = request.GetResponse();
                }

                catch (WebException WebEx)
                {
                //some additional exception handling

                return false;
                }

                Stream temp_stream = response.GetResponseStream();

                string json_result = null;//JSON is a string, do not forget about it

                using (StreamReader reader = new StreamReader(temp_stream))
                {
                json_result = reader.ReadToEnd();//read the data from the stream to line
                }

                var temp_type = new { token = "", product = "", status = "", error = ""};//object that represents the type which immediately created

                //next line creates through our library JSON object, it creates a string of data that have been received in response to the request. This object will be already in response to a request not serialized form

                var temp_obj = JsonConvert.DeserializeAnonymousType(json_result, temp_type);// JsonConvert it static class from a library which we downloaded

                //this is sesion token from Betfair api that we need so mach

                string session_token_ = temp_obj.token;


                response.Close();

                return (temp_obj.status == "SUCCESS");

                }

                Comment

                • geoffw123
                  Senior Member
                  • Mar 2014
                  • 250

                  #9
                  Thanks for that code snippet

                  Yay, brilliant, thanks very much for that code snippet, I have been stuck for ages trying to figure out how to login using the new api-ng. I had previously got the C# Betfair demo example working OK but it was a pain as you had to go and get the session token from a browser manually. I had posted a question asking how to get the session token programmatically weeks ago without really getting an explanation or a solution.

                  The above code worked fine when I tried it. The only thing that confused me for a little while was the deserialise the anonymous object. If you type

                  Code:
                  var temp_obj = JsonConvert.DeserializeAnonymousType(.....)
                  you get an error as there is no such function in the JsonConvert class. I had forgotton that JsonConvert is just a wrapper around the Newtonsoft JSON library. Once I realised that fact, it was easy to fix, if it helps anyone else, you just need to addd this to the Betfair demo code jsonConvert.cs module.

                  Code:
                   // Added this so I can call it for the login function
                   public static T DeserializeAnonymousType<T>(string json, T tempType)
                   {
                     return Newtonsoft.Json.JsonConvert.DeserializeAnonymousType<T>(json, tempType);
                   }
                  Its easy now to tweak this sample code to also implement the logout function.

                  Thanks again "int main" I owe you a pint
                  Last edited by geoffw123; 31-07-2014, 01:36 PM.

                  Comment

                  • int_main
                    Junior Member
                    • Apr 2013
                    • 9

                    #10
                    Check to be sure the string using Newtonsoft.Json; This method (DeserializeAnonymousType) exists, it is from a static class JsonConvert.

                    Solution with a temporary anonymous type, for example. For further work we Obtain your class library that will simulate the types Betting Type Definitions
                    Last edited by int_main; 31-07-2014, 02:59 PM.

                    Comment

                    • int_main
                      Junior Member
                      • Apr 2013
                      • 9

                      #11
                      As you can guess the other methods of communicating with our api similar to the previous function. The only difference is that you must pass a parameter that identifies our session (Session token).
                      We got it in the login function, and I would recommend to make it a static field, so it may need to access from other classes.

                      This parameter is send to api in the form of Header:

                      X-Authentication: "session token"
                      In other methods, we will be adding a line of code as:

                      request.Headers.Add(string.Format("X-Authentication: {0}", session_token_));
                      Also note that, depending on the method of changing our Uri resource whose services we require.

                      Below I will give an example function logout (notice how to the changed Uri and now we will send header with session token)

                      public static bool LogOut()
                      {
                      Uri temp_uri = new Uri(@"https://identitysso.betfair.com/api/logout");//new uri to logout

                      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(temp_uri);

                      request.Method = "POST";

                      request.Accept = "application/json";

                      request.Headers.Add(string.Format("X-Authentication: {0}", session_token_));//new header with your session token

                      request.Headers.Add(string.Format("X-Application: {0}", appKey_));

                      WebResponse response = null;

                      try
                      {
                      response = request.GetResponse();
                      }

                      catch (WebException WebEx)
                      {//some exception handling

                      return false;
                      }

                      Stream temp_stream = response.GetResponseStream();

                      string json_result = null;

                      using (StreamReader reader = new StreamReader(temp_stream, Encoding.ASCII))
                      {
                      json_result = reader.ReadToEnd();//string with your response data
                      }

                      var temp_type = new { token = "", product = "", status = "", error = "" };

                      var temp_obj = JsonConvert.DeserializeAnonymousType(json_result, temp_type);

                      session_token_ = temp_obj.token;//it does not necessarily


                      response.Close();

                      return (temp_obj.status == "SUCCESS");
                      }

                      Comment

                      Working...
                      X