Wednesday, 3 February 2010

I'm Still Here

Just a quick note to say that this blog is still alive, and application development is going well! The program is currently making regular profits and I'm now working on the next posts! Stay tuned! Any questions you have, please feel free to get in touch!

Saturday, 17 October 2009

A Slowdown!

Life at work has been busy for me lately, and I've not had time to post the latest developments. The program will now monitor a single market automatically, and also implements the first of my trading indicators - though not to the point of giving back/lay indications yet. I have a hectic week coming up, but after that, my next post will cover how to unpack the string returned from GetMarketPricesCompressed - efficiently and (hopefully) in a simple to understand way. Then we'll move on to some more exciting developments!

In the meantime - happy trading!

Monday, 5 October 2009

ConvertTimeFromUtc - Market Start Times

I was having problems with the start time of my markets being an hour slower than the times on the Betfair website, before I realised that daylight saving time might have something to do with it. Here's a nice line of code that converts the UTC Market start time to the local time (I put it inside the function that populates my user interface from a MarketSummary[]):

currentMarketSummary.startTime = TimeZoneInfo.ConvertTimeFromUtc(currentMarketSummary.startTime, TimeZoneInfo.Local);

Where currentMarketSummary is an object of type MarketSummary.

This will convert the time returned by Betfair into your local time. These things seem simple once they're working correctly..!

C# Compilers

It occurred to me that I haven't mentioned how to compile C# programs if you don't have access to the full version of Visual Studio. Microsoft also provide a free IDE and compiler (Visual C# 2008 Express) at:

http://www.microsoft.com/express/vcsharp/Default.aspx

And there's a platform independent compiler at the Mono project, which theoretically compiles your program to work across Linux and Windows:

http://www.mono-project.com/CSharp_Compiler

Just thought I'd share! As usual, post any questions in the comments.

A Rethink - Working Asynchronously

So after spending most of the night learning about delegates and asynchronous methods, I started to implement an asynchronous wrapper for the Betfair API. Although I now feel I properly understand Delegates and Callbacks (post a comment if you'd like me to post a very simple explanation), imagine my happiness this morning when I discovered the API did in fact have asynchronous methods for pretty much all of it's services. It was one of those times when you just have to move on, coding lesson learned..

So this is a bit of a restart in the blog - I've started a new Visual Studio project, and am now working exclusively with asynchronous methods, where they are available. But first, an explanation of why working asynchronously is good when we're dealing with web services..

When you call a remote method, there is going to be a delay between when you call it, and when it returns. In a single-threaded synchronous program (which is probably the way you learned to program), the delay means that your program is going to "block", and appear to hang until the function returns. Obviously this is bad from a user interface perspective, and is also bad from a program perspective - if there's other processing your program could be getting on with, why waste processor cycles waiting for your remote function call to return?

An Asynchronous Method is one that lets you know when it is finished - so you can call the method, and the program will continue to execute. Once the method is completed, it notifies the program (via an event), and we can deal with the data in a callback method. A callback method is simply a method that is called "automatically", when the remote method returns. There seems to be a lot of complicated demonstration code on the web, so I'm going to try and keep this as simple as possible - obviously this is specific to the Betfair API as well, which means that we don't have to implement callbacks. In a later post, I'll talk about implementing "both sides" of an asynchronous method, but for now lets look again at the Login service, but this time call it asynchronously.

Logging In To The Betfair API Asynchronously

Because we're now working asynchronously, we will be subscribing to asynchronous events of the Betfair services, and so we need to make sure there is only one instance of the service - I did this by creating a static class and creating the service there:

public static class Session
{
public static global.BFGlobalService bfGlobalService = new global.BFGlobalService();
}


Nice and simple - we now have an easily accessible service. The login code is pretty much the same as before - the only difference this time is we're calling loginAsync, instead of login. So the code:

global.LoginReq loginRequest = new global.LoginReq();
loginRequest.username = USERNAME;
loginRequest.password = PASSWORD;
loginRequest.productId = 82;

Session.bfGlobalService.loginAsync(loginRequest,Guid.NewGuid().ToString());


Obviously, replace USERNAME and PASSWORD with your login details - either hardcode them, or get them from your user interface programatically.

The second parameter Guid.NewGuid().ToString() is supplied to an asychronous method to uniquely identify it. This means we can call it repeatedly, without waiting for previous calls to return. To test this, omit the second parameter, and then repeatedly call a method - an exception will be thrown. The unique identifier means that when the method returns, it knows where to return to, and so doesn't get mixed up with other calls. We don't necessarily need it - it's up to you to decided whether you need multiple calling functionality  or not..!

If you implement this, you'll see that when the program reaches the last line, it immediately returns and carries on working as normal. The login function, like all Betfair API calls, returns an APIResponseHeader, inside of which there is the session token we must send with the next API call, as well as error information. But how do we know when this data is available, and how do we retrieve it? Through event notification...which keeps things quite simple - we just have to make sure we've subscribed to this event. I want my main form to know when the data is available, so I've added the following line of code to my constructor:


Session.bfGlobalService.loginCompleted +=new loginCompletedEventHandler(bfGlobalService_loginCompleted);


This means that when the event is fired, a method called bfGlobalService_loginCompleted will be called. This method is also on my form, and looks like this:

private void bfGlobalService_loginCompleted(object sender, global.loginCompletedEventArgs e)
{
   global.LoginResp loginResponse = e.Result;

   Session.SaveAPIResponseHeader(loginResponse.header, (Enum)loginResponse.errorCode);

   if ((e.Result.errorCode == LoginErrorEnum.OK && e.Result.header.errorCode == global.APIErrorEnum.OK))
   {
      this.btnAuthenticate.Text = "Logout";
   }
   else
   {
      MessageBox.Show("Login Error");
   }
}


The return value of the function (in this case, of type LoginResp), is returned back to the program in the event arguments - we access it through e.Result. We then save the API response header, using a function in our static class called SaveAPIResponseHeader, (more on that in a future post), and then I do some error checking before updating the user interface. Post any questions on unclear code in the comments - I'll cover the use of generics and Enum to aid our error checking in a future post.

To summarise, working asynchronously with the Betfair API is fairly simple - we:

  1. Call the asynchronous version of the method.
  2. Subscribe to the asynchronous event related to the method.
  3. Retrieve the data from in the event handler.
Not much to it at all!

Sunday, 4 October 2009

Communication with the API – Logging In


To communicate with the API, we must carry out the following steps:
  1. Create an appropriate request
  2. Set up that request
  3. Submit that request to the appropriate service
  4. Store the response  and handle data + error notifications as required.
This post, I’m looking at logging in, which is a global service, therefore we will be submitting our request to the global service.

To login, I created a button on my form. When the button is clicked, the following code is executed:

global.BFGlobalService bfGlobalService = new global.BFGlobalService();
LoginReq loginRequest = new LoginReq();
loginRequest.username = USERNAME;
loginRequest.password = PASSWORD;
loginRequest.productId = 82;
LoginResp loginResponse = bfGlobalService.login(loginRequest);

Obviously you replace USERNAME and PASSWORD with your login details. It’s up to you how as to whether you hardcode these into your file, or you enter them via a textbox on your form whenever you wish to log in. Lets look at this code line by line:
The first line creates the service that we are going to submit our request to. When I added my WSDL references, I added the Global Service to a namespace called “global”, hence the label preceding the variable type. The reason I have done this, and not added a using statement at the top, is that there are a couple of methods and types that are named the same in both the Global and Exchange services. While I’m fairly sure that these types are interchangeable, it’s not going to hurt to ensure we’re being as safe as possible.
The second line creates a new login request object, called loginRequest.
Lines three, four and five set up the properties of the login request.
The final line submits the request to the Global Service, and stores the response in a login response object.  From here, you extract the relevant data (including the API header containing the session key, to be covered in a later post).
That’s all there is to it – you’re now logged in! If you’d like confirmation, write the loginResponse.errorCode to a label on your form – it will return “OK” if all is good – see what happens if you enter the wrong details.
It’s getting late now – I’ll work on bringing this blog up to my current development state over the next few days.

Inital Development


I work in Visual Studio 2008 – if you are currently registered at either a UK or US University (and possibly elsewhere in the world, I’m not sure), you can obtain a copy of this IDE for free (from Microsoft Dreamspark), along with a number of other Microsoft packages. It’s a nice thing that Microsoft are doing – have a look if you’ve not already heard of it.
To begin working with the Betfair API, start a new project (I’m using a Windows Forms Application), and add the WSDL links as Web References.

Don’t add them as Service References, as I did to start with – I then spent 6 hours writing the WSDL classes myself, before I realised my mistake (Visual Studio will generate these classes for you, that’s kind of the whole point of WSDL). So to add the links as Web References, goto Project->Add Web Reference, and enter the WSDL links before adding  the references to your project. The links can be found in the Betfair API Documentation – the versions I’m currently using are:
The Global Service contains methods that work across exchanges – such as logging in, account management, etc, while the Exchange Service contains specific methods for finding markets and placing bets, etc. There is also an Australian Exchange Service, that enables access to Betfair’s Australian betting services – this isn’t something I will be using in the near future.
The way I understand the WSDL links at present is this (please correct me if I’m wrong): They allow the .NET environment to treat the remote web services as if they were methods on the local machine. This means that we can develop with little knowledge of what is happening in the underlying SOAP and XML parsing protocols, which is a nice thing if you don’t know much about SOAP.
The next post will focus on logging in to your Betfair account using the API. How are you doing so far?

C# Programming and the Betfair API


This is my new C# programming blog, where I’m going to be documenting the development of an automated betting bot that works with the Betfair (www.betfair.com) API. This blog is intended as a kind of online logbook, where I’ll document my successes (and how I achieved them), and my struggles.
So a quick summary about the program I’m starting to develop – as I’ve already said, the intention is that it will work with the Betfair API, and once I have the basic functionality up and running, I hope to start implementing some financial modelling strategies and algorithms, with a view to testing how the Betfair exchange markets work when compared to the financial trading markets. I should mention that I am a programmer, and not a gambler, and therefore I won’t be putting huge amounts of my own money at risk to start with - to prove the concepts the program will work with a test bed, and then I'll move onto slowly seeing if it can increase a small starting bank. Not that I have huge amounts of money anyway  – I’m currently working on a PhD, and so I survive on a small PhD stipend. But anyway, the intention is for the program to harvest data about the Betfair market prices, and then allow testing of trading strategies. This is a project I will be working on in my spare time, so there may be times when I post very actively, and times when my day job takes over.
So, the next post should detail the progress I’ve made so far…comments are more than welcomed, about any aspect of this blog – not just the technical content, but my writing style, etc.