The world’s leading publication for data science, AI, and ML professionals.

An Introduction to Betfair API and How to Use it

A Look into the Ever Changing World of Online Gambling

Betfair Logo from lbbonline.com
Betfair Logo from lbbonline.com

Introduction

The world of online gambling is an ever changing beast which allows very few people outside of the business to take a glimpse into their ever changing world. Betfair is one of the few online bookies to allow everyone access to their API. This is because of the Betfair Exchange which works on similar principles as that of the Stock Market on Wall Street, with millions of users backing and laying bets in the hopes of making some money. Some people are able to earn a living on the Exchange but it isn’t for everyone as many of these people are using bots to place these bets by using the API.

When I first wanted to start using the API it was mainly to track how odds of certain markets would change over time and in the future analyse these changes and see what was causing the changes in price. When reading through the Betfair API documentation there wasn’t exactly clear instructions on how to gain access to it, and also helped by the fact that the documentation hasn’t really been updated since it was uploaded. So below I have created a basic guide on how to gain access to the Betfair API and how to use it. The full Notebook can be accessed from my GitHub. Also, before you start make sure you are able to access/place bets on Betfair. I also started trying to access the API on Google Colaboratory but was denied access as the servers are based in the US, a country that can’t access Betfair.

Gaining Access to your API Keys

To begin you will need to have a Betfair account in order to gain access to the API key. To gain access to your API keys you will first need to have your SSOID and use the APING Demo Tool. When you are logged into Betfair right click and select Inspect Element. On Chrome you are looking for the Applications tab and then Cookies. It should look similar to this.

When you have your SSOID paste it into the APING Demo Tool and add an application name then press execute at the bottom of the page.

You should then have an app show up like this:

Notice that there are 2 keys. For this application we are using the Delayed key as this is free whereas the other has no delay and costs £200. If you want to use it just make sure you have that amount in your Betfair account as it will be deducted from there. If you have already created an App, then select the getDeveloperAppKeys button and press execute at the bottom and this should display the keys.

Time to Get a Certificate and Key

Now that you have access to your API Keys you will now need to download XCA. It is more beneficial to follow the guide for creating them from here this is the only piece of documentation that I found exceptionally useful. Make sure to double check all the information and settings are correct before advancing as these can’t be changed and will have to be created again if they are wrong. When you have your certificate and key exported from XCA its time to upload the certificate to your Betfair account. This is done by going into your "My Betfair Account" then the "My Details" dropdown menu and selecting "Security Settings".

On this page click "edit" next to the "Automated Betting Program Access" menu. Upload the .crt file and you should be ready to get into the programming.

Throughout this example my key will have the extension .key this is because I changed it from .pem, either works as long as it is the correct extension in your code.

Step 1: Loading Libraries

First things first, import the libraries that are used

Step 2: Getting an SSOID

To get started I am using POST just to login and access the SSOID. The SSOID that you found at the start was only to gain access to the API once you have your keys you can get it whenever you log in this way. The way I am setting the username, password and app key isn’t necessary, but it will prove more time efficient later on. In this instance I am keeping my certificate and key in the same place as the notebook for ease, but you can save them elsewhere and use an absolute address.

Step 3: Querying the API to get Specific Markets

Here we are setting the URL that will be posting to, the request, and the headers. This particular request will provide a list of all available sports from Betfair. The URL below is set once and is the same URL that all requests are sent to. The event_req is the request that is being sent to the URL. This has to be set up like below bet can be changed when in this format. The method can be changed using the operations that can be found here. req retrieves the HTML response and is then converted into json to allow us to read it.

The json response is made up of Dicts and Lists, or more accurately a Dictionary containing a List of Dictionaries which contains a Dictionary. The results show the name of the market, the market ID (which is used later on when filtering for upcoming matches), and the market count (the number of available markets to bet on). This will provide the number of markets that include inplay and upcoming, this can be set to show only upcoming or inplay which will be mentioned later. Below is the output of the above code. Notice how the ‘id’ doesn’t follow the usual way of indexing and starts at 1 with a number of events not even following that convention.

Below is an example of how to see the name of the event. Notice the aforementioned Dictionary with a List of Dictionaries which contain a Dictionary. If at any time you are unsure of what the dictionaries keys are use .keys() like so

Next, we will move on and find how to get the available markets available for a specific event that is currently inplay. By using the listMarketTypes method the request is asking for all markets and with the addition of filters it can be fine-tuned to see markets specific to an event. The first filter used finds only the events for that specific id in this case it is Football using its id of 1. The other filter is whether it is inplay or not, if it is omitted it will provide both inplay and not inplay markets, this way it can effectively toggle between inplay and not.

The market types above can be used to find out what teams are playing with the selected market by using the listMarketCatalogue method. Sticking with Football as the event with the addition of the filter marketTypeCodes. In this example MATCH_ODDS is used and shows the fixtures with this market. Another addition is setting a time range. This is set before adding it to the request as it is easier to add to the request with a single name rather than a large line. The response is sorted to display the first fixture to start and will only have 1 result. Note that max results will only accept a maximum of 1000. To see the teams playing in the fixture marketProjection is added.

From this point on we will be looking at Horse Racing. Let’s add some more details to our API request. You can see that I have pulled a number of variables from the request, this is to make it easier if changes need to be made. The variables are the same as the above example with the addition of metadata and inplay.

The result of this request will give all the races in the UK and Ireland over the next 24 hours. When checking each race, it shows the all the information associated with the race importantly the marketId, which will be useful later. It also lists the runners and all the metadata associated with them including the horse’s form, which will also be important, alongside its selectionId. To explore further into this output it is the same as before.

Step 4: Querying the API to Get the Latest Odds

An API request can be used to get the odds for a specific team/person/horse within which ever market you select. For this the horse from above will be used. To get the odds for the horse the API URL is set up the same as the previous URLs except it is the listRunnerBook that will be requested. The operations used can be found here. Note: You can only pass in one marketId and one selectionId in that market per request. If the selectionId being passed in is not a valid one/doesn’t belong in that market then the call will still work but only the market data is returned.

To get the necessary Ids you can just look at the output and enter it in manually or you can set them as variables.

This is the output if there is an invalid selectionId passed. No odds are shown as there was nothing specific to get the odds for.

This is the output if there is an valid selectionId passed. As can be seen there is now information connected to the selectionId used. It shows the Price that it was last traded at on the Betfair Exchange along with the prices that it can be backed at and the price that it can be layed against it. I will not get into what a lay bet is and for this example will only be looking at the first price available to back.

Step 5: Add It All Together and Add a Little Math

Now that the basics have been covered on how to get the Races in a 24 hour period, the horses running in the races and the odds a specific horse. why not combine them all into one function, with a couple of additions.

The function that will be created will calculate the average of each horses form in each race. It will then determine which horse has the best average form and it will be added to a dataframe alongside the odds for the selected horse, race, and the name of the horse.

A horses form is made up of the positions that it has placed in its last 6 races. However not every horse can place, there are a number of different codes used in horse racing for which can’t be added to the horses average. To combat this, you can weight these codes with whatever value you think is reasonable, which I have done below. Now, some of the code will rarely come up but that doesn’t mean they won’t, that is why I have added them anyway otherwise it will break. This function is also intended to be the only thing need to be run that is why I have added the first part about getting the SSOID.

The first part of the function is the declaration of variables and lists that will be used within the function, along with the creation of the pandas dataframe. after that it is the same as before when the getting the SSOID, then getting the races and runners. It is at this point where the form is averaged out, as can be seen this is a bit messy and requires some clean-up but for the time being it operates as required.

As can be seen the averaged number is added to a list. This list is then iterated through and checked against the lowest average that was set to 100 at the beginning. If the average at the current list location is less than the lowest average, then the new average is set as the new lowest average and the name of the horse and selectionId are appended to a list. Once the list has been iterated through, the odds of the horse with the best average is collected by using the method shown above. The values are then added into the dataframe. The reason for using horsename[-1] and selectionID[-1] is because the last item in the list is needed.

Conclusion

And there you have it. A basic guide through the somewhat confusing Betfair API. Now, there is many more ways to use the Betfair API and I have only scratched the surface of the possibilities that can come from this. The form function is only a guideline to follow when looking at picking a horse to place a bet on as there are a number of other variables which haven’t even been addressed like the horses weight, the jockey, the trainer, the condition of the track, or weather. Like anything that has to do with predicting the outcomes of races or matches take it with a grain of salt and use it in conjunction with whatever other information you would be usually look at when deciding on which bet to place.


Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.


Related Articles