Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1.  python v 2.7.2  - http://www.python.org/getit/releases/2.7.2/
  2.  urllib2 python module  - http://docs.python.org/2/library/urllib2.html
  3.  json python module - http://docs.python.org/2/library/json.html
  4.  datetime python module - http://docs.python.org/2/library/datetime.html
  5.  sys python module - http://docs.python.org/2/library/sys.html

Installation:

   You only need to clone or download the repository linked to above. If you do not have a valid Python 2.7.X installation already then please follow the download and installation instructions from the python wiki.

Run the scripts

Change to the directory where you cloned the repository to and run the sample of your choice as follows:

JSON-RPC   

python ApiNgDemoJsonRpc.py <appkey> <sessiontoken>

Rescript   

python ApiNgDemoRescript.py <appkey> <sessiontoken>

 

Info

 Note:  If the command line arguments for application key and session token are not provided then the script will prompt for application key and session token

Code Snippets

Calling API-NG with JSON-RPC protocol

method and param values need to be changed based on the required service operation.You can execute multiple service operation together with a single call using batch json-rpc call where you can correlate the responses with value of the id.

...

languagepython

...

A note on Python3:

We have added a python3 version of the json-rpc script, which is in the python subdirectory of the github sample code repo named ApiNgDemoJsonRpc-python3.py. This functions exactly the same way as the python 2.7X sample, but with compatibility tweaks for Python 3. The documentation below reflects the python 2.7X code, but the 

Installation:

   You only need to clone or download the repository linked to above. If you do not have a valid Python 2.7.X installation already then please follow the download and installation instructions from the python wiki.

Run the scripts

Change to the directory where you cloned the repository to and run the sample of your choice as follows:

JSON-RPC   

python ApiNgDemoJsonRpc.py <appkey> <sessiontoken>

Rescript   

python ApiNgDemoRescript.py <appkey> <sessiontoken>

 

Info

 Note:  If the command line arguments for application key and session token are not provided then the script will prompt for application key and session token

Code Snippets

Calling API-NG with JSON-RPC protocol

method and param values need to be changed based on the required service operation.You can execute multiple service operation together with a single call using batch json-rpc call where you can correlate the responses with value of the id.

Code Block
languagepython
URL = url = "https://api.betfair.com/json-rpc"
jsonrpc_req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listEventTypes", "params": {"filter":{ }}, "id": 1}'
headers = {'X-Application': appKey, 'X-Authentication': sessionToken, 'content-type': 'application/json'}

def callAping(jsonrpc_req):
    try:
        req = urllib2.Request(url, jsonrpc_req, headers)
        response = urllib2.urlopen(req)
        jsonResponse = response.read()
        return jsonResponse
    except urllib2.URLError:
        print 'Oops no service available at ' + str(url)
        exit()
    except urllib2.HTTPError:
        print 'Oops not a valid operation from the service ' + str(url)
        exit()

 

Calling API-NG with Rescript protocol

Code Block
languagepython
url = 'https://api.betfair.com/json-rpc"
jsonrpc_req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listEventTypes", "params": {"filter":{ }}, "id": 1}'
headers = {'X-Application': appKey, 'X-Authentication': sessionToken, 'content-type': 'application/json'}

def callAping(jsonrpc_req/rest/v1.0/${operationName}/'
headers = {'X-Application': appKey, 'X-Authentication': sessionToken, 'content-type': 'application/json', 'accept': 'application/json'}
request = '{"filter":{"eventTypeIds":["7"],"marketCountries":["GB"],"marketStartTime":{"from":"2013-05-21T00:00:00Z"}},"sort":"FIRST_TO_START","maxResults":"1","marketProjection":["RUNNER_METADATA"]}'

def callAping(url, request):
    try:
        req = urllib2.Request(url, jsonrpc_reqrequest, headers)
        response = urllib2.urlopen(req)
        jsonResponse = response.read()
        return jsonResponse

    except urllib2.URLError:
        print 'Oops there is some issue with the request'
        exit()
    except urllib2.HTTPError:
        print 'Oops no service available at there is some issue with the request' + strurllib2.HTTPError.getcode(url)
        exit()

Get next available horse racing market and runner information using listMarketCatalogue

JSON-RPC

Code Block
languagepython
def getMarketCatalogueForNextGBWin(eventTypeID):
     except urllib2.HTTPErrorif (eventTypeID is not None):
        print 'OopsCalling notlistMarketCatalouge aOperation validto operationget from the service ' + str(url)MarketID and selectionId'
        exit()

 

Calling API-NG with Rescript protocol

Code Block
languagepython
urlnow = 'https://api.betfair.com/rest/v1.0/${operationName}/'
headers = {'X-Application': appKey, 'X-Authentication': sessionToken, 'content-type': 'application/json', 'accept': 'application/json'}
request = 'datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
        market_catalogue_req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listMarketCatalogue", "params": {"filter":{"eventTypeIds":["7' + eventTypeID + '"],"marketCountries":["GB"],"marketStartTime":{"from":"2013-05-21T00:00:00Z"}},"sort":"FIRST_TO_START","maxResults":"1","marketProjection":["RUNNER_METADATA"]}'

def callAping(url, request):marketTypeCodes":["WIN"],'\
    try:
         req = urllib2.Request(url, request, headers)
        response = urllib2.urlopen(req)
        jsonResponse = response.read()
        return jsonResponse

    except urllib2.URLError:
        print 'Oops there is some issue with the request'
        exit()
    except urllib2.HTTPError:
         print 'Oops there is some issue with the request' + urllib2.HTTPError.getcode()
        exit()

Get next available horse racing market and runner information using listMarketCatalogue

JSON-RPC

Code Block
languagepython
def getMarketCatalouge(eventTypeID):
    if (eventTypeID is not None):
        print 'Calling listMarketCatalouge Operation to get MarketID and selectionId'
        now = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
        market_catalouge_req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listMarketCatalogue", "params": {'"filtermarketStartTime":{"eventTypeIdsfrom":["' + eventTypeIDnow + '"],"marketCountries"}},"sort":"FIRST_TO_START","maxResults":"1","marketProjection":["GBRUNNER_METADATA"]},'\ "id": 1}'
        """
        print  market_catalogue_req
        """
        market_catalogue_response = callAping(market_catalogue_req)
    '"marketStartTime":{"from":"' + now + '"}},"sort":"FIRST_TO_START","maxResults":"1","marketProjection":["RUNNER_METADATA"]}, "id": 1}'
"
        print market_catalougecatalogue_response
       = callAping(market_catalouge_req)

 """
        market_catalouge_loads = json.loads(market_catalougecatalogue_response)
        try:
            market_catalouge_reslutsresults = market_catalouge_loads['result']
            return market_catalouge_reslutsresults
        except:
            print  'Exception from API-NG' + str(market_catalouge_reslutsresults['error'])
            exit()


def getMarketId(marketCatalougeResult):
    if( marketCatalougeResult is not None):
        for market in marketCatalougeResult:
            return market['marketId']


def getSelectionId(marketCatalougeResult):
    if(marketCatalougeResult is not None):
        for market in marketCatalougeResult:
            return market['runners'][0]['selectionId']

marketCatalougeResult = getMarketCatalougegetMarketCatalogueForNextGBWin(horseRacingEventTypeID)
marketid = getMarketId(marketCatalougeResult)
runnerId = getSelectionId(marketCatalougeResult)

...

Code Block
languagepython
def getMarketBookgetMarketBookBestOffers(marketId):
    print 'Calling listMarketBook to read prices for the Market with ID :' + marketId
    market_book_req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listMarketBook", "params": {"marketIds":["' + marketId + '"],"priceProjection":{"priceData":["EX_BEST_OFFERS"]}}, "id": 1}'
    """
    print  market_book_req
    """
    market_book_response = callAping(market_book_req)
     """
    parsing json using json python module
    print market_book_response
    """
    market_book_loads = json.loads(market_book_response)
    try:
        market_book_result = market_book_loads['result']
        return market_book_result
    except:
        print  'Exception from API-NG' + str(market_catalougebook_reslutsresult['error'])
        exit()


def printPriceInfo(market_book_result):
    if(market_book_result is not None):
        print 'Please find Best three available prices for the runners'
        for marketBook in market_book_result:
            runners = marketBook['runners']
            for runner in runners:
                print 'Selection id is ' + str(runner['selectionId'])
                if (runner['status'] == 'ACTIVE'):
                    print 'Available to back price :' + str(runner['ex']['availableToBack'])
                    print 'Available to lay price :' + str(runner['ex']['availableToLay'])
                else:
                    print 'This runner is not active'

market_book_result = getMarketBookgetMarketBookBestOffers(marketid)
printPriceInfo(market_book_result)

...

Code Block
languagepython
def placeBetplaceFailingBet(marketId, selectionId):
    if( marketId is not None and selectionId is not None):
        print 'Calling placeOrder for marketId :' + marketId + ' with selection id :' + str(selectionId)
        place_order_Req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/placeOrders", "params": {"marketId":"' + marketId + '","instructions":'\
                                                                                                                              '[{"selectionId":"' + str(
            selectionId) + '","handicap":"0","side":"BACK","orderType":"LIMIT","limitOrder":{"size":"10.01","price":"1.50","persistenceType":"LAPSE"}}],"customerRef":"test12121212121"}, "id": 1}'

}],"customerRef":"test12121212121"}, "id": 1}'
        """
        print place_order_Req
        """
        place_order_Response = callAping(place_order_Req)
        place_order_load = json.loads(place_order_Response)
 place_order_Response)
        try:
            place_order_result = place_order_load['result']
       try:
     print 'Place order status is ' + place_order_result = place_order_load['resultstatus']
            """
            print 'Place order error status is ' + place_order_result['statuserrorCode']
            """
            print 'Reason for Place order failure is ' + place_order_result['instructionReports'][0]['errorCode']
        except:
            print  'Exception from API-NG' + str(marketplace_catalougeorder_reslutsresult['error'])


placeBet(marketid, runnerId)

Rescript

 

Code Block
languagepython
def placeBet(marketId, selectionId):
    if( marketId is not None and selectionId is not None):
        print 'Calling placeOrder for marketId :' + marketId + ' with selection id :' + str(selectionId)
        place_order_Req = '{"marketId":"' + marketId + '","instructions":'\
                                                       '[{"selectionId":"' + str(
            selectionId) + '","handicap":"0","side":"BACK","orderType":"LIMIT","limitOrder":{"size":"1.01","price":"1.50","persistenceType":"LAPSE"}}],"customerRef":"test12121212121"}'
        endPoint = 'https://beta-api.betfair.com/rest/v1.0/placeOrders/'

        place_order_Response = callAping(endPoint, place_order_Req)
        place_order_load = json.loads(place_order_Response)
        print 'Place order status is ' + place_order_load['status']

        print 'Reason for Place order failure is ' + place_order_load['instructionReports'][0]['errorCode']


placeBet(marketid, runnerId)

...