The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

WWW::betfair - interact with the betfair API using OO Perl

VERSION

Version 0.01

WARNING

This version of the WWW::betfair is beta - it has not been thoroughly tested nor is type checking performed on the arguments passed to betfair. Therefore be cautious and check all argument types and values before using the methods in this library. Ensure that you adequately test any method of WWW::betfair before using the method. As per the software license it is provided AS IS and no liability is accepted for any costs or penalties caused by using WWW::betfair.

To understand how to use the betfair API it is essential to read the betfair documentation before using WWW::betfair. The betfair documentation is an excellent reference which also explains some of the quirks and bugs with the current betfair API.

WHAT IS BETFAIR?

betfair is a sports betting services provider best known for hosting a sports betting exchange. The sports betting exchange works like a marketplace: betfair provides an anonymous platform for individuals to offer and take bets on sports events at a certain price and size; it is the ebay of betting. betfair provides an API for the sports betting exchange which enables users to search for sports events and markets, place and update bets and manage their account by depositing and withdrawing funds.

WHY USE THIS LIBRARY?

The betfair API communicates using verbose XML files which contain various bugs and quirks. WWW::betfair makes it easier to use the betfair API by providing a Perl interface which manages the befair session, serializing API calls to betfair into the required XML format and de-serializing and parsing the betfair responses back into Perl data structures.

SYNOPSIS

WWW::betfair provides an object oriented Perl interface for the betfair v6 API. This library communicates via HTTPS to the betfair servers using XML. To use the API you must have an active and funded account with betfair, and be accessing the API from a location where betfair permits use (e.g. USA based connections are refused, but UK connections are allowed). WWW::betfair provides methods to connect to the betfair exchange, search for market prices place and update bets and manage your betfair account.

Example

    use WWW::betfair;
    use Data::Dumper;

    my $betfair = WWW::betfair->new;
    
    # login is required before performing any other services
    if ($betfair->login({username => 'sillymoos', password => 'password123'}) {
        
        # check account balance
        print Dumper($betfair->getAccountFunds);

        # get a list of all active event types (categories of sporting events e.g. football, tennis, boxing).
        print Dumper($betfair->getActiveEventTypes);

    }
    # if login failed print the error message returned by betfair
    else {
        print Dumper($betfair->getError);
    }

TO DO

  • Add argument type checking to all methods

  • Enable use of Australian exchange server - currently this is not supported

  • Add remaining betfair API methods

  • Add more helper methods that enable easier use of the betfair API

METHODS

new

Returns a new WWW::betfair object. Does not require any parameters.

Example

    my $betfair = WWW::betfair->new;

getError

Returns the error message from the betfair API response. Upon a successful call API the value returned by getError is usually 'OK'.

getXMLSent

Returns a string of the XML message sent to betfair. This can be useful to inspect if de-bugging a failed API call.

getXMLReceived

Returns a string of the XML message received from betfair. This can be useful to inspect if de-bugging a failed API call.

getHashReceived

Returns a Perl data structure consisting of the entire de-serialized betfair XML response. This can be useful to inspect if de-bugging a failed API call and easier to read than the raw XML message, especially if used in conjunction with Data::Dumper.

GENERAL API SERVICES METHODS

login

Authenticates the user and starts a session with betfair. This is required before any other methods can be used. Returns 1 on success and 0 on failure. If login fails and you are sure that you are using the correct the credentials, check the $betfair->{error} attribute. A common reason for failure on login is not having a funded betfair account. To resolve this, simply make a deposit into your betfair account and the login should work. See http://bdp.betfair.com/docs/Login.html for details. Required arguments:

  • username: string of your betfair username

  • password: string of your betfair password

  • productID: integer that indicates the API product to be used (optional). This defaults to 82 (the free personal API). Provide this argument if using a commercial version of the betfair API.

Example

    $betfair->login({
                username => 'sillymoos',
                password => 'password123',
              });

keepAlive

Refreshes the current session with betfair. Returns 1 on success and 0 on failure. See http://bdp.betfair.com/docs/keepAlive.html for details. Does not require any parameters. This method is not normally required as a session expires after 24 hours of inactivity.

Example

    $betfair->keepAlive;

logout

Closes the current session with betfair. Returns 1 on success and 0 on failure. See http://bdp.betfair.com/docs/Logout.html for details. Does not require any parameters.

Example

    $betfair->logout;

READ ONLY BETTING API SERVICES

getActiveEventTypes

Returns an array of hashes of active event types or 0 on failure. See http://bdp.betfair.com/docs/GetActiveEventTypes.html for details. Does not require any parameters.

Example

    my $activeEventTypes = $betfair->getActiveEventTypes;

getAllEventTypes

Returns an array of hashes of all event types or 0 on failure. See http://bdp.betfair.com/docs/GetAllEventTypes.html for details. Does not require any parameters.

Example

    my $allEventTypes = $betfair->getAllEventTypes;

getAllMarkets

Returns an array of hashes of all markets or 0 on failure. See http://bdp.betfair.com/docs/GetAllMarkets.html for details. Does not require any parameters.

Example

    my $allMarkets = $betfair->getAllMarkets;

getCurrentBets

Returns an array of hashrefs of current bets or 0 on failure. See http://bdp.betfair.com/docs/GetCurrentBets.html for details. Requires a hashref with the following parameters:

  • betStatus : string of a valid BetStatusEnum type as defined by betfair (see http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html)

  • detailed : string of either true or false

  • orderBy : string of a valid BetsOrderByEnum types as defined by betfair (see http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html)

  • recordCount : integer of the maximum number of records to return

  • startRecord : integer of the index of the first record to retrieve. The index is zero-based so 0 would indicate the first record in the resultset

  • noTotalRecordCount : string of either true or false

  • marketId : integer of the betfair market id for which current bets are required (optional)

Example

    my $bets = $betfair->getCurrentBets({
                            betStatus           => 'M',
                            detailed            => 'false',
                            orderBy             => 'PLACED_DATE',
                            recordCount         => 100,
                            startRecord         => 0,
                            noTotalRecordCount  => 'true',
                            });

getEvents

Returns an array of hashes of events / markets or 0 on failure. See http://bdp.betfair.com/docs/GetEvents.html for details. Requires:

  • eventParentId : an integer which is the betfair event id of the parent event

Example

    # betfair event id of tennis is 14
    my $tennisEvents = $betfair->getEvents({eventParentId => 14});

getMarket

Returns a hash of market data or 0 on failure. See http://bdp.betfair.com/docs/GetMarket.html for details. Requires:

  • marketId : integer which is the betfair id of the market

Example

    my $marketData = $betfair->getMarket({marketId => 108690258});

getCompleteMarketPrices

Returns a hashref of market data including an arrayhashref of individual runners prices or 0 on failure. See http://bdp.betfair.com/docs/GetCompleteMarketPricesCompressed.html for details. Note that this method de-serializes the compressed string returned by the betfair method into a Perl data structure. Requires:

  • marketId : integer of the betfair market id,

  • currencyCode : string of the three letter ISO 4217 currency code (optional). If this is not provided, the users home currency is used

Example

    my $marketPriceData = $betfair->getCompleteMarketPrices({marketId => 123456789, currencyCode => 'GBP'}); 

getMUBets

Returns an arrayref of hashes of bets or 0 on failure. See http://bdp.betfair.com/docs/GetMUBets.html for details. Requires:

  • betStatus : string of betfair betStatusEnum type, must be either matched, unmatched or both (M, U, MU). See http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html

  • orderBy : string of a valid BetsOrderByEnum types as defined by betfair. see http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html

  • recordCount : integer of the maximum number of records to return

  • startRecord : integer of the index of the first record to retrieve. The index is zero-based so 0 would indicate the first record in the resultset

  • noTotalRecordCount : string of either true or false

  • marketId : integer of the betfair market id for which current bets are required (optional)

  • betId : an array of betIds (optional). If included, betStatus must be 'MU'.

Example

    my $muBets = $betfair->getMUBets({
                            betStatus           => 'MU',
                            recordCount         => 1000,
                            startRecord         => 0,
                            noTotalRecordCount  => 'true',
                            marketId            => 123456789,
                 });

cancelBets

Cancels up to 40 unmatched and active bets on betfair. Returns an arrayref of hashes of cancelled bets. See http://bdp.betfair.com/docs/CancelBets.html for details. Requires:

  • betIds : an arrayref of integers of betIds that should be cancelled, up to 40 betIds are permitted by betfair.

Example

    my $cancelledBetsResults = $betfair->cancelBets({betIds => [123456789, 987654321]});

placeBets

Places up to 60 bets on betfair and returns an array of results or zero on failure. See http://bdp.betfair.com/docs/PlaceBets.html for details. Requires:

  • bets : an arrayref of hashes of bets. Up to 60 hashes are permitted by betfair. Every bet hash should contain:

    • asianLineId : integer of the ID of the asian handicap market, usually 0 unless betting on an asian handicap market

    • betCategoryType : a string of the betCategoryTypeEnum, usually 'E' for exchange, see http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html for details.

    • betPersistenceType : a string of the betPersistenceTypeEnum, usually 'NONE' for standard exchange bets. See http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html for details.

    • betType : a string of the betTypeEnum. Either 'B' to back or 'L' to lay.

    • bspLiability : a number of the maximum amount to risk for a bsp bet. For a back / lay bet this is equivalent to the whole stake amount.

    • marketId : integer of the marketId for which the bet should be placed.

    • price : number of the decimal odds for the bet.

    • selectionId : integer of the betfair id of the runner (selection option) that the bet should be placed on.

    • size : number for the stake amount for this bet.

Example

    # place one bet to back selection 99 on market 123456789 at 5-to-1 for 10 
    $myBetPlacedResults = $betfair->placeBets({
                                        bets => [{ 
                                                asianLineId         => 0,
                                                betCategoryType     => 'E',
                                                betPersistenceType  => 'NONE',
                                                betType             => 'B',
                                                bspliability        => 2,
                                                marketId            => 123456789,
                                                price               => 5,
                                                selectionId         => 99,
                                                size                => 10,
                                            },
                                        ],
                                    });

updateBets

Updates existing unmatched bets on betfair: the size, price and persistence can be updated. Note that only the size or the price can be updated in one request, if both parameters are provided betfair ignores the new size value. Returns an arrayref of hashes of updated bet results. See http://bdp.betfair.com/docs/UpdateBets.html for details. Requires:

  • bets : an arrayref of hashes of bets to be updated. Each hash represents one bet and must contain the following key / value pairs:

    • betId : integer of the betId to be updated

    • newBetPersistenceType : string of the betfair betPersistenceTypeEnum to be updated to see http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html for more details.

    • newPrice : number for the new price of the bet

    • newSize : number for the new size of the bet

    • oldBetPersistenceType : string of the current bet's betfair betPersistenceTypeEnum see http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html for more details.

    • oldPrice : number for the old price of the bet

    • oldSize : number for the old size of the bet

Example

    my $updateBetDetails = $betfair->updateBets({
                                        bets => [{
                                                betId                   => 12345,
                                                newBetPersistenceType   => 'NONE',
                                                newPrice                => 5,
                                                newSize                 => 10,
                                                oldBetPersistenceType   => 'NONE',
                                                oldPrice                => 2,
                                                oldSize                 => 10,
                                        }],
                                    });

ACCOUNT MANAGEMENT API SERVICES

addPaymentCard

Adds a payment card to your betfair account. Returns an arrayref of hashes of payment card responses or 0 on failure. See http://bdp.betfair.com/docs/AddPaymentCard.html. Requires:

  • cardNumber : string of the card number

  • cardType : string of a valid betfair cardTypeEnum (e.g. 'VISA'). See http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html

  • cardStatus : string of a valid betfair paymentCardStatusEnum, either 'LOCKED' or 'UNLOCKED'

  • startDate : string of the card start date, optional depending on type of card

  • expiryDate : string of the card expiry date

  • issueNumber : string of the issue number or NULL if the cardType is not Solo or Switch

  • billingName : name of person on the billing account for the card

  • nickName : string of the card nickname must be less than 9 characters

  • password : string of the betfair account password

  • address1 : string of the first line of the address for the payment card

  • address2 : string of the second line of the address for the payment card

  • address3 : string of the third line of the address for the payment card (optional)

  • address4 : string of the fourth line of the address for the payment card (optional)

  • town : string of the town for the payment card

  • county : string of the county for the payment card

  • zipCode : string of the zip / postal code for the payment card

  • country : string of the country for the payment card

Example

    my $addPaymentCardResponse = $betfair->addPaymentCard({
                                            cardNumber  => '1234123412341234',
                                            cardType    => 'VISA',
                                            cardStatus  => 'UNLOCKED',
                                            startDate   => '0113',
                                            expiryDate  => '0116',
                                            issueNumber => 'NULL',
                                            billingName => 'The Sillymoose',
                                            nickName    => 'democard',
                                            password    => 'password123',
                                            address1    => 'Mountain Plains',
                                            town        => 'Hoofton',
                                            zipCode     => 'MO13FR',
                                            country     => 'UK',
                                 });

depositFromPaymentCard

Deposits money in your betfair account using a payment card. See http://bdp.betfair.com/docs/DepositFromPaymentCard.html for further details. Returns the betfair response as a hashref or 0 on failure. Requires:

  • amount : number which represents the amount of money to deposit

  • cardIdentifier : string of the nickname for the payment card

  • cv2 : string of the CV2 digits from the payment card (also known as the security digits)

  • password : string of the betfair account password

Example

    # deposit £10 in my account
    my $depositResponse = $betfair->depositFromPaymentCard({
                                            amount          => 10,
                                            cardIdentifier  => 'checking',
                                            cv2             => '999',
                                            password        => 'password123',
                                    });

getAccountFunds

Returns a hashref of the account funds betfair response. See http://bdp.betfair.com/docs/GetAccountFunds.html for details. No parameters are required.

Example

    my $funds = $betfair->getAccountFunds;

getAccountStatement

Returns an arrayref of hashes of account statement entries or 0 on failure. See http://bdp.betfair.com/docs/GetAccountStatement.html for further details. Requires:

  • startRecord : integer indicating the first record number to return. Record indexes are zero-based, hence 0 is the first record

  • recordCount : integer of the maximum number of records to return

  • startDate : date for which to return records on or after this date (a string in the XML datetime format see example)

  • endDate : date for which to return records on or before this date (a string in the XML datetime format see example)

  • itemsIncluded : string of the betfair AccountStatementIncludeEnum see l<http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html> for details

Example

    # return an account statement for all activity starting at record 1 up to 1000 records between 1st January 2013 and 16th June 2013
    my $statement = $betfair->getAccountStatement({
                                    startRecord     => 0,
                                    recordCount     => 1000,
                                    startDate       => '2013-01-01T00:00:00.000Z',         
                                    endDate         => '2013-06-16T00:00:00.000Z',         
                                    itemsIncluded   => 'ALL',
                              });

getPaymentCard

Returns an arrayref of hashes of payment card or 0 on failure. See http://bdp.betfair.com/docs/GetPaymentCard.html for details. Does not require any parameters.

Example

    my $cardDetails = $betfair->getPaymentCard;

getSubscriptionInfo

Returns an arrayref of hashes of subscription or 0 on failure. Does not require any parameters. See http://bdp.betfair.com/docs/GetSubscriptionInfo.html for details. Note that if you are using the personal free betfair API, this service will return no data.

Example

    my $subscriptionData = $betfair->getSubscriptionInfo;

withdrawToPaymentCard

Withdraws money from your betfair account to the payment card specified. Returns a hashref of the withdraw response from betfair or 0 on failure. See http://bdp.betfair.com/docs/WithdrawToPaymentCard.html for details. Requires:

  • amount : number representing the amount of money to withdraw

  • cardIdentifier : string of the nickname of the payment card

  • password : string of your betfair password

Example

    my $withdrawalResult = $betfair->withdrawToPaymentCard({
                                        amount          => 10,
                                        cardIdentifier  => 'checking',
                                        password        => 'password123',
                                    }); 

HELPER METHODS

getMarketPricesCombined

This is a helper method not provided by the betfair API. It returns a combined structure of the results of getMarket and getCompleteMarketPrices so that detailed runner and market information is combined with the complete betfair price data. Requires:

  • marketId : integer of the betfair market id

Example

    # call getMarket and getCompleteMarketPrices and combine them into a single structure
    my $completeMarketData = $betfair->getMarketPricesCombined({marketId => 123456789});

INTERNAL METHODS

_do_request

Processes requests to and from the betfair API.

_getServerURI

Returns the URI for the target betfair server depending on whether it is an exchange server (1 and 2) or the global server.

_sort_array_ref

Returns a sorted arrayref based on price.

_add_payment_card_line

Pushes a hashref of payment card key / value pairs into an arrayref and returns the result.

_force_array

Receives a reference variable and if the data is not an array, returns a single-element arrayref. Else returns the data as received.

AUTHOR

David Farrell, <davidnmfarrell at gmail.com>

BUGS

Please report any bugs or feature requests to bug-www-betfair at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WWW-betfair. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc WWW::betfair

You can also look for information at:

ACKNOWLEDGEMENTS

This project was inspired by the betfair free Perl project. Although WWW::betfair uses a different approach, the betfair free project was a useful point of reference at inception. Thanks guys!

Thanks to betfair for creating the exchange and API.

LICENSE AND COPYRIGHT

Copyright 2013 David Farrell.

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.

1 POD Error

The following errors were encountered while parsing the POD:

Around line 1064:

Non-ASCII character seen before =encoding in '£10'. Assuming UTF-8