• Home
  • Twitter
  • SmarterSig
  • Betfair
  • About Me
  • Post Cats
    • Betfair API-NG
    • Horse Stride Length
    • Web Scraping Race Data
  • Books
    • Precision CX Wong
    • Hands on ML

Make Your Betting Pay

~ Improve Your Horse Betting

Make Your Betting Pay

Category Archives: Betfair API-NG

Betfair API NG Session 12

20 Sunday Nov 2016

Posted by smartersig in Betfair API-NG

≈ Leave a comment

In this session we will look at how to access Irish racing in addition to UK racing.

This is a fairly simple process and involved editing one line in our MyAPILib library that we created. This will hardwire so to speak our library to pick up Irish and UK races in the same way that the library at the moment is hard wired to pick up only UK races. It might be better to write the subroutine so that we pass it a parameter indicating what markets to pick up.

First let us take the simple approach and simply change the routine to gather Irish and UK races. In our library we need to edit only one line within the getEvents subroutine. This line will now read as

market_catalogue_req = ‘{“jsonrpc”: “2.0”, “method”: “SportsAPING/v1.0/listMarketCatalogue”, “params”: {“filter”:{“eventTypeIds”:[‘+eventId+’],”marketCountries”:[“GB”, “IE”],”marketTypeCodes”:[“WIN”], “marketStartTime”:{“from”:”‘ + now + ‘”,”to”:”‘ + to + ‘”}},”sort”:”FIRST_TO_START”,”maxResults”:”100″,”marketProjection”:[“MARKET_START_TIME”,”RUNNER_DESCRIPTION”, “RUNNER_METADATA”, “EVENT”]}, “id”: 1}’

Notice how the marketCountries parameter has IE added to it. API NG takes two letter country codes as specified by ISO 3166 at https://en.wikipedia.org/wiki/ISO_3166

To make the getEvents sub routine more generic we need to modify it to receieve an extra parameter stating the required markets

def getEvents(appKey, sessionToken, eventId, reqMarkets):

Now we can call this routine with the following modified call

myMarkets = ‘”GB”,”IE”‘
races = myAPILib2.getEvents(appKey, sessionToken, horseRacingEventTypeID, myMarkets)

The market_catalogue_req initialisation line will now need changing to

market_catalogue_req = ‘{“jsonrpc”: “2.0”, “method”: “SportsAPING/v1.0/listMarketCatalogue”, “params”: {“filter”:{“eventTypeIds”:[‘+eventId+’],”marketCountries”:[‘+reqMarkets+’],”marketTypeCodes”:[“WIN”], “marketStartTime”:{“from”:”‘ + now + ‘”,”to”:”‘ + to + ‘”}},”sort”:”FIRST_TO_START”,”maxResults”:”100″,”marketProjection”:[“MARKET_START_TIME”,”RUNNER_DESCRIPTION”, “RUNNER_METADATA”, “EVENT”]}, “id”: 1}’

Betfair API-NG Session 11

28 Monday Apr 2014

Posted by smartersig in Betfair API-NG

≈ 8 Comments

In this session we will look at how to access the array of runner meta data available through the API.

There is all kinds of data we can access, for example the draw, sire damsire, cloth number, days since last run and so on. For a complete list of what can be accessed see https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Runner+Metadata+Description

To access this data we first need to make a small change to the getEvents procedure in myAPILib. We need to add RUNNER_METADATA as an extra marketProjection parameter (see below)

market_catalogue_req = ‘{“jsonrpc”: “2.0”, “method”: “SportsAPING/v1.0/listMarketCatalogue”, “params”: {“filter”:{“eventTypeIds”:[‘+eventId+’],”marketCountries”:[“GB”],”marketTypeCodes”:[“WIN”], “marketStartTime”:{“from”:”‘ + now + ‘”,”to”:”‘ + to + ‘”}},”sort”:”FIRST_TO_START”,”maxResults”:”100″,”marketProjection”:[“MARKET_START_TIME”,”RUNNER_DESCRIPTION”, “RUNNER_METADATA”]}, “id”: 1}’

Note– dont copy and paste the above, add the extra RUNNER_METADATA text manually

To access say the STALL_DRAW data item in our testLib program we can add the following bit of code

for selection in allRunners:
  print (selection[‘runnerName’] + ” ” + str(selection[‘selectionId’]) )
  print (‘Draw is ‘ + selection[‘metadata’][‘STALL_DRAW’])

The third line is one you will need to add the other two are just for points of reference and are already in your file. If you copy and paste it make sure that you change all the wonky quote marks to single quotes. As I mentioned before WordPress has a mind of its own when displaying quotes and its tedious for me to edit them on the wordpress site.

Betfair API-NG Session 10

26 Saturday Apr 2014

Posted by smartersig in Betfair API-NG

≈ 1 Comment

In this session we shall see how we can make a bet using the API

The subroutine we need to add to the MyAPILib fle has the following heading

def doWager(marketId, horseId, backOrLay, stake, price, persistence, appKey, sessionToken):
## returns betResult access status of bet through betResult[‘status’]

From this we can see that when we make a call to this subroutine to make a wager we need to pass it 8 parameters. Some need a little explanation.

The BackOrLay parameter needs to be the word BACK or LAY depending on whether we intend to back or lay the horse.

persistence will indicate what we want to happen to the bet should it not be matched and the market go’s in play. In the sample code we shall see shortly we will specify LAPSE. Using the old API we simply specify SP if we want the bet to go SP in running. Betfair in their wisdom have decided that to specify SP using NG you need to state MARKET_ON_CLOSE

The other parameters are self explanatory and in our sample call we will get our code to LAY the last horse in the last race its detects when outputing the race and horse Id’s. We shall lay it for £2 at 1.01 thus giving us ample time to manually cancel it off.

The doWager code can be copied and pasted into your MyAPILib file from the following link doWager

The call to doWager and the examination of the return code can be copied and pasted from testlib

One other useful parameter which I have not used in the above, is a customer reference which you can allocate to a bet. This can be useful when later on you need to identify bets perhaps by the different bots you have or by strategy name. The amendment to the call in doWager is shown below. Of course an extra string parameter needs to be passed into the subroutine as well

NOTE- Do not copy and paste the following I have not edited to undo wordpress mangling of quote marks

bet_place_req = ‘{“jsonrpc”: “2.0”, “method”: “SportsAPING/v1.0/placeOrders”, “params”: {“marketId”: “‘ +marketId+ ‘”,”instructions”: [{“selectionId”: “‘ +horseId+ ‘”, “handicap”: “0”, “side”: “‘ +backOrLay+ ‘”, “orderType”: “LIMIT”, “limitOrder”: { “size”: “‘ +stake+ ‘”, “price”: “‘ +price+ ‘”, “persistenceType”: “‘ +persistence+ ‘” } } ], “customerRef”:”‘ +cRef+ ‘”}, “id”: 1 }’

The subroutine header would like the following

def doWager(marketId, horseId, backOrLay, stake, price, persistence, cRef, appKey, sessionToken):

Betfair API-NG Session 9

24 Thursday Apr 2014

Posted by smartersig in Betfair API-NG

≈ Leave a comment

In this session we will access horse names and horse Id’s for the races we accessed in the previous session.

Getting hold of these two pieces of extra data, along with a host of other horse specific data, is quite simple. We simply need to add an extra parameter to our call to listMarketCatalogue within the getEvents subroutine in the myAPILib file.

Step 1 In the IDLE go to the myAPILIb file and locate the line of code within the getEvents subroutine that begins with

market_catalogue_req = ‘{“jsonrpc”: “2.0”, “method”: etc etc etc etc

Step 2 Edit the line manually (ie dont copy and paste) adding ,”RUNNER_DESCRIPTION” so that it now reads

market_catalogue_req = ‘{“jsonrpc”: “2.0”, “method”: “SportsAPING/v1.0/listMarketCatalogue”, “params”: {“filter”:{“eventTypeIds”:[‘+eventId+’],”marketCountries”:[“GB”],”marketTypeCodes”:[“WIN”], “marketStartTime”:{“from”:”‘ + now + ‘”,”to”:”‘ + to + ‘”}},”sort”:”FIRST_TO_START”,”maxResults”:”100″,”marketProjection”:[“MARKET_START_TIME”,”RUNNER_DESCRIPTION”]}, “id”: 1}’

Step 3 We now need to access within the testlib program the runner data that is going to be passed back. The updated code needed can be found at testlib.txt

Don’t forget to add your username, password and app key values if using this code as is. Alternatively you can just copy and paste the final section of the code from the getEvents call onwards, into your testlib file, replacing the code already there.

The output provided should be of the form

1.113839006
2014-04-24T19:55:00.000Z
Baltic Brave 7767233

Flashy Queen 7552880

Iseemist 7185307

Miss Brazil 7645993

Bowsers Bold 7362173

Seven Lucky Seven 7361654

Black Vale 7430139

1.113839020
2014-04-24T20:15:00.000Z
One Boy 7200987

Orient Class 7652539

Noble Asset 7422371

Camanche Grey 7642225

Danfazi 7200986

Tinsill 7407448

Distant Past 7943530

Under Approval 7320027

Well done you now have access to both market id’s and horse id’s and names.

Betfair API-NG Session 8

24 Thursday Apr 2014

Posted by smartersig in Betfair API-NG

≈ 2 Comments

In this session we will ask the API for a list of all GB horse races due to run from the current time up to midnight. With this information our program can access the race ID’s for each race along with other information such as off times. We are then in a position to get individual horse ID’s. Horse ID’s and Race ID’s are needed to strike bets.

Step 1 We need to append the following statements to our testlib file in IDLE (Remember indentation is relevant in Python)

races = myAPILib.getEvents(appKey, sessionToken, horseRacingEventTypeID)
if races != -1:
  for race in races:
    print (race[‘marketId’])
    race[‘marketStartTime’] = myAPILib.checkSummerTime(race[‘marketStartTime’])
    print (race[‘marketStartTime’])
    print ()

Step 2 Looking at the above we can see that two new subroutines need to be added to the myAPILib file, namely getEvents and checkSummerTime. The latter checks for summer time and edits the Betfair off times accordingly otherwise all times returned by Betfair would be one hour out here in the UK.

You can copy and paste a complete to date myAPILib content from the following link myAPILib

The output should be a list of race ID’s and offtime details such as

1.113839006
2014-04-24T19:55:00.000Z

1.113839020
2014-04-24T20:15:00.000Z

Well done your program now has the race details for the day safely stored. In the next session we will look at getting hold of horse ID’s

Betfair API-NG Session 7

23 Wednesday Apr 2014

Posted by smartersig in Betfair API-NG

≈ 6 Comments

In this session we will add some code that will obtain the code number for horse racing. All sports have a code number on Betfair, at the moment horse racing is 7 but of course this could change so we need some code to ask Betfair for the code number for horse racing. In the next session we will then be in a position to ask Betfair for all of todays race ID’s for UK racing. We can use these individual race ID’s to obtain specific data on a race, such as horse names, horse ID’s and odds.

Step 1 Make sure you have the python IDLE running with both the MYAPILib.py file and the testlib.py file open.

Step 2 Append the following statement to the testlib.py file. Obviously add your API key that you created in the earlier session. Our program will need to communicate this to Betfair through the calls we will make in this session.

appKey = ‘yourappkeyhere’

Step 3  Add the following line to the testlib.py file

eventTypesResult = myAPILib.getEventTypes (appKey, sessionToken)

In the above we are making a call to a subroutine called getEventTypes in our MyAPILib file. If you have looked in that file you will have noticed that there is not subroutine in there called getEventTypes but dont worry we will add this in due course. The above will assign the eventTypesResult variable a list of codes for all sports, amongst which horse racing will be one of them (probably the number 7).

Step 4 Add the following line to the testlib file

horseRacingEventTypeID = myAPILib.getEventTypeIDForEventTypeName(eventTypesResult, ‘Horse Racing’)

The subroutine getEventTypeIDForEventTypeName expects two parameters to be passed to it. The list of event types and the text describing the eventID that you want passing back, in this case Horse Racing. On completion of this statement the variable horseRacingEventTypeID should contain the ID number for horse racing (currently the number 7). If this gets changed in the future we dont have to worry, our program will still pick up the number for horse racing.

Step 5 Finally add the following line of code

print (‘The number for horse racing is ‘ + horseRacingEventTypeID)

To keep things simple we are at the moment not adding any error checking. The routines in MyAPILib could fail for some reason (eg Betfair down) and in most cases return the number -1 but for simplicity we are ignoring this possibility at the moment.

Step 6 Before we run this code we need to add the missing subroutines to the MyAPILib.py file which you have loaded up at the moment. Copy and paste the following text into the MyAPILib file and save it.

def callAping(jsonrpc_req, appKey, sessionToken):

  headers = {'X-Application': appKey, 'X-Authentication': sessionToken, 'content-type': 'application/json'}
  url = "https://api.betfair.com/exchange/betting/json-rpc/v1 "
  try:
    req = urllib.request.Request(url, jsonrpc_req.encode('utf-8'), headers)
    response = urllib.request.urlopen(req)
    jsonResponse = response.read()
    return jsonResponse.decode('utf-8')
  except urllib.error.URLError as e:
    print (e.reason)
    print ('Oops no service available at ' + str(url))
    exit()
  except urllib.error.HTTPError:
    print ('Oops not a valid operation from the service ' + str(url))
    exit()

############################################################

def getEventTypes(appKey,sessionToken):
  ### returns eventypeids eg racing = 7 or -1 if fails ###

  event_type_req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listEventTypes", "params": {"filter":{ }}, "id": 1}'

  eventTypesResponse = callAping(event_type_req, appKey, sessionToken)
  eventTypeLoads = json.loads(eventTypesResponse)

  try:
   eventTypeResults = eventTypeLoads['result']
   return eventTypeResults
  except:
   print ('Exception from API-NG' + str(eventTypeLoads['error']))
   return -1

############################################################

def getEventTypeIDForEventTypeName(eventTypesResult, requestedEventTypeName):

  ## returns specific event ID for a given sport or -1 if fails ##

  if(eventTypesResult is not None):
   for event in eventTypesResult:
     eventTypeName = event[‘eventType’][‘name’]
     if( eventTypeName == requestedEventTypeName):
      return event[‘eventType’][‘id’]
  else:
   print ('Oops there is an issue with the input')
   return -1

###########################################################

Step 7 Save and run the testlib file, you should get an ouput line stating that The number for horse racing is 7

Betfair API-NH Session 6

22 Tuesday Apr 2014

Posted by smartersig in Betfair API-NG

≈ 11 Comments

In this session we are now ready to start talking to Betfair through the API

Step 1 Double click on your desktop Python IDLE icon to open up the Python development tool

Step 2 Click the file tab followed by new file

Step 3 In the new file window that has just appeared paste in the following code. (NOTE indentation is important in Python, it delimits the scope of an IF or a FOR loop so make sure you paste as is with indentation in place)

#!/usr/bin/env python

#API-NG library

import requests

import urllib
import urllib.request
import urllib.error
import json
import datetime
import sys
import time

############################################################

def loginAPING(userName,passWord):
  ### returns session token or -1 if fails ###

  appKey = “1” # seems to be needed although not a valid appkey

  payload = 'username='+userName+'&password='+passWord
  headers = {'X-Application': appKey,'Content-Type': 'application/x-www-form-urlencoded'}

  resp = requests.post('https://identitysso.betfair.com/api/certlogin ', data=payload, cert=('client-2048.crt', 'client-2048.key'), headers=headers)
  resp_json = resp.json()
  if resp_json['loginStatus'] == 'SUCCESS':

    return resp_json['sessionToken']
  else:
    return -1

#############################################################

Step 4 Save the file with the file name myAPILib.py

Step 5 Open another new file and paste in the following text

#!/usr/bin/env python

import myAPILib

sessionToken = myAPILib.loginAPING("yourusername","yourpassword")

print (sessionToken)

In the above substitute your Betfair account name and password

Save the file as testlib.py

Step 6 In the testlib window click the run tab and select run module

Step 7 Output will appear in the shell window and it should print out your session taken for the login just performed by the program. If it failed it will have printed out the number -1

Well done you now have a program that is using a python library to execute commands to the Betfair API. You have successfully logged in and we can in the next session look at how to get hold of race ID’s for the day along with race off times.

Betfair API-NG Session 5

21 Monday Apr 2014

Posted by smartersig in Betfair API-NG

≈ 29 Comments

In this session we will use openSSL to create the required link between our programs and Betfair. In some ways its the most challenging session in that there are plenty of opportunities to mistype stuff

Step 1 Open Wordpad and then using Wordpad open the configuration file. It will probably be in your c:\openSSL-Win64\bin folder under the name openssl.cfg

Step 2 Within the file add the following text

[ ssl_client ]

basicConstraints = CA:FALSE

nsCertType = client

keyUsage = digitalSignature, keyEncipherment

extendedKeyUsage = clientAuth

Step 3 Save the file and then rename it as

openssl.cnf

Step 4 Open a black MSDOS command window in administrator mode. Make sure you have it open in admin’ mode (right click on command prompt and select run as administrator) otherwise you may not be able to write to your root directory.

Step 5 Make sure within the MSDOS window you are at the pythonstuff folder that you created. Navigate to it if need be using the cd command

Step 6 Enter the command c:\openssl-Win64\bin\openssl in your MSDOS window

This should invoke openssl and you should have the openssl prompt ‘openSSL>’

Enter the following openSSL command

genrsa -out client-2048.key 2048

Now enter the following openSSL command

req -new -config c:\openSSL-Win64\bin\openssl.cnf -key client-2048.key -out client-2048.csr

Step 7 At the openssl prompts enter the following. For the challenge password I used the Betfair account password

Country Name (2 letter code) [AU]:GB

State or Province Name (full name) [Some-State]:London

Locality Name (eg, city) []:London

Organization Name (eg, company) [Internet Widgits Pty Ltd]:yourcompany.com

Organizational Unit Name (eg, section) []:Security Team

Common Name (e.g. server FQDN or YOUR name) []:Test API-NG Certificate

Email Address []:my.name@mydomain.com

Please enter the following ‘extra’ attributes

to be sent with your certificate request

A challenge password []:

An optional company name []:

 Step 8 After completing step7 enter the following openssl command

x509 -req -days 365 -in client-2048.csr -signkey client-2048.key -out client-2048.crt -extfile c:\openSSL-Win64\bin\openssl.cnf -extensions ssl_client

Step 9 Using a text editor copy the contents of your client-2048.crt file and your client-2048.key file into a new file called client-2048.pem. Note- These files will be found in your Pythonstuff folder but the .crt extension may be hidden when you check the file name in explorer.

Step 10 Before you login using the certificate, it must be attached to your Betfair account, as follows:

1. Login to betfair using your web browser
2. Go to: https://myaccount.betfair.com/accountdetails/mysecurity?showAPI=1
3. Find the "Automated Betting Program Access" header and click "Edit"
4. Click the "Choose File" button and select your "client-2048.crt" file
5. Click "Upload Certificate"
6. Certificate info should now be displayed

Scroll down to the “API-NG Configuration” section if required and the certificate details should be shown.  You should now be able to log in to your Betfair account using the API-NG endpoint.

Well done that was the toughest section but we are now ready to start communicating with Betfair through the API. We will start to do this in the next session. You can ‘quit’ the openSSL session. NOTE If you have sub accounts you will need to do step 10 for each account should you want to access the API through them.

 

 

Betfair API-NG Session 4

20 Sunday Apr 2014

Posted by smartersig in Betfair API-NG

≈ Leave a comment

In this session we will download OpenSSL in preparation for creating a secure connection between our Python programs and Betfair

Step 1 In your web browser goto

https://slproweb.com

Click on the products tab on the web site

Click the win32 openSSL link

Step 2 Scroll down and choose the appropriate file for your PC. My PC is a 64 bit so I chose Win64 OpenSSL V1.0.1g

Step 3 When the file has downloaded double click the downloaded .exe file in the bottom left of your browser

Step 4 Answer Yes to ‘do you want to allow this program to modify your computer’

Step 5 At this stage it may say that you do not have Visual C++ 2008 redistributable installed.

If this happens go to http://www.microsoft.com/en-gb/download/details.aspx?id=29

Download and run the above using the default settings before answering the prompt from the OPenSSL install

Step 6 When the install of OPenSSL has finished unclick the donate button if you do not wish to donate and then click finish

Step 7 Check in your c: folder that you have a folder called openSSL-Win64

Well done you have installed openSSL. In the next session we will move onto using it.

Betfair API-NG Session 3

19 Saturday Apr 2014

Posted by smartersig in Betfair API-NG

≈ Leave a comment

We now need to turn our attention away from Python for a while and set up some of the communication data needed by the Betfair API. First thing we need to do is create an API APP KEY

Step 1 Open up your browser and login to your Betfair account

Step 2 Open up a new tab in your browser and navigate to the Betfair API-NG visualiser at

https://docs.developer.betfair.com/visualisers/api-ng-account-operations/

Step 3 Check that the box towards the top of the screen labelled Session Token has an entry in it. If for some reason it does not, you will find instructions on how to find your current logged in session token here

https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/API-NG+-+Visualiser

Assuming it is already filled in for you we can proceed to the next step

Step 4 Look to the left of the visualiser and check that ‘create developerAppKeys’ option is selected and highlighted

Step 5 In the next column type in an application name of your choice eg FredsAPI or whatever you prefer

Step 6 Now click on the execute button at the bottom of the page

Step 7 Check the main right hand column. NOTE the number displayed IS NOT your APP KEY. Click on the + sign to the left of it to reveal two APP KEYS

Step 8 Make a note of the application key (in the application key column) that is NOT the DELAYED one. If the app key shown ends in ‘…’ then expand the column to show all the key

Step 9 If you forget the key you can always come back and check it using the GetDeveloperAppKeys option on the left hand list

Well done you have now created your APP KEY and associated it with your Betfair account. This APP KEY will be communicated to Betfair using Python on all API service calls

Footnote – Betfair have now implemented a £299 fee to ‘activate’ the APP key after you have completed the above. To do this just google ‘Betfair activate API App key’

← Older posts

Archives

Create a free website or blog at WordPress.com.

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Follow Following
    • Make Your Betting Pay
    • Join 50 other followers
    • Already have a WordPress.com account? Log in now.
    • Make Your Betting Pay
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar