David Farrell

NAME

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

VERSION

Version 1.02

WHAT IS BETFAIR?

betfair is a sports betting services provider best known for hosting the largest sports betting exchange in the world. 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. Additionally WWW::betfair provides:

  • 100% of the free and paid methods of the betfair API

  • Documentation for every method with an example method call and reference to the original betfair documentation

  • Type-checking of arguments before they are sent to betfair

WARNING

Betting using a software program can have unintended consequences. 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 and risking money on it. 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.

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);

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

NON 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 - this is useful when a request fails. After a successful call API the value returned by getError is 'OK'.

Example

    my $error = $betfair->getError;

getXMLSent

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

Example

    my $xmlSent = $betfair->getXMLSent;

getXMLReceived

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

Example

    my $xmlReceived = $betfair->getXMLReceived;

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.

Example

    my $hashReceived = $betfair->getHashReceived;

GENERAL API 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 login 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 keepAlive 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 logout for details. Does not require any parameters.

Example

    $betfair->logout;

READ ONLY BETTING API METHODS

convertCurrency

Returns the betfair converted amount of currency see convertCurrency for details. Requires a hashref with the following parameters:

  • amount: this is the decimal amount of base currency to convert.

  • fromCurrency : this is the base currency to convert from.

  • toCurrency : this is the target currency to convert to.

Example

    $betfair->convertCurrency({ amount          => 5,
                                fromCurrency    => 'GBP',
                                toCurrency      => 'USD',
                              });

getActiveEventTypes

Returns an array of hashes of active event types or 0 on failure. See getActiveEventTypes for details. Does not require any parameters.

Example

    my $activeEventTypes = $betfair->getActiveEventTypes;

getAllCurrencies

Returns an arrayref of currency codes and the betfair GBP exchange rate. See getAllCurrencies. Requires no parameters.

Example

    $betfair->getAllCurrencies;

getAllCurrenciesV2

Returns an arrayref of currency codes, the betfair GBP exchange rate and staking sizes for the currency. See getAllCurrenciesV2. Requires no parameters.

Example

    $betfair->getAllCurrenciesV2;

getAllEventTypes

Returns an array of hashes of all event types or 0 on failure. See getAllEventTypes 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 getAllMarkets for details. Requires a hashref with the following parameters:

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $allMarkets = $betfair->getAllMarkets({exchangeId => 1});

getBet

Returns a hashref of betfair's bet response, including an array of all matches to a bet. See getBet for details. Requires a hashref with the following argument:

  • betId - the betId integer of the bet to retrieve data about.

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $bet = $betfair->getBet({betId       => 123456789
                                exchangeId  => 1,
                              });

getBetHistory

Returns an arrayref of hashrefs of bets. See getBetHistory for details. Requires a hashref with the following parameters:

  • betTypesIncluded : string of a valid BetStatusEnum type as defined by betfair (see betStatusEnum)

  • detailed : boolean string e.g. ('true' or 'false') indicating whether or not to include the details of all matches per bet.

  • eventTypeIds : an arrayref of integers that represent the betfair eventTypeIds. (e.g. [1, 6] would be football and boxing). This is not mandatory if the betTypesIncluded parameter equals 'M' or 'U'.

  • marketId : an integer representing the betfair marketId (optional).

  • marketTypesIncluded : arrayref of strings of the betfair marketTypesIncluded enum. See marketTypesIncludedEnum for details.

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

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

  • recordCount : integer representing the maximum number of records to retrieve (must be between 1 and 100).

  • sortBetsBy : string of a valid BetsOrderByEnum types as defined by betfair. see BetsOrderByEnum

  • 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

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $betHistory = $betfair->getBetHistory({
                            betTypesIncluded    => 'M',
                            detailed            => 'false',
                            eventTypeIds        => [6],
                            marketTypesIncluded => ['O', 'L', 'R'],
                            placedDateFrom      => '2013-01-01T00:00:00.000Z',         
                            placedDateTo        => '2013-06-16T00:00:00.000Z',         
                            recordCount         => 100,
                            sortBetsBy          => 'PLACED_DATE',
                            startRecord         => 0,
                            exchangeId          => 1,
                            });

getBetLite

Returns a hashref of bet information. See getBetLite for details. Requires a hashref with the following key pair/s:

  • betId : integer representing the betfair id for the bet to retrieve data about.

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $betData = $betfair->getBetLite({betId       => 123456789
                                        exchangeId  => 2,
                                       });

getBetMatchesLite

Returns an arrayref of hashrefs of matched bet information. See getBetMatchesLite for details. Requires a hashref with the following key pair/s:

  • betId : integer representing the betfair id for the bet to retrieve data about.

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $betData = $betfair->getBetMatchesLite({ betId       => 123456789
                                                exchangeId  => 1,
                                               });

getCompleteMarketPricesCompressed

Returns a hashref of market data including an arrayhashref of individual selection prices data. See getCompleteMarketPricesCompressed for details. Note that this method de-serializes the compressed string returned by the betfair method into a Perl data structure. Requires:

  • marketId : integer representing the betfair market id.

  • currencyCode : string representing the three letter ISO currency code. Only certain currencies are accepted by betfair GBP, USD, EUR, NOK, SGD, SEK, AUD, CAD, HKD, DKK (optional)

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $marketPriceData = $betfair->getCompleteMarketPricesCompressed({ marketId    => 123456789,
                                                                        exchangeId  => 2,
                                                                      }); 

getCurrentBets

Returns an arrayref of hashrefs of current bets or 0 on failure. See getCurrentBets for details. Requires a hashref with the following parameters:

  • betStatus : string of a valid BetStatus enum type as defined by betfair see betStatusEnum for details.

  • detailed : string of either true or false

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

  • 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)

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

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

getCurrentBetsLite

Returns an arrayref of hashrefs of current bets for a single market or the entire exchange. See getCurrentBetsLite for details. Requires a hashref with the following parameters:

  • betStatus : string of a valid BetStatus enum type as defined by betfair see betStatusEnum for details.

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

  • 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' to return a total record count

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

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

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

getDetailAvailableMktDepth

Returns an arrayref of current back and lay offers in a market for a specific selection. See getAvailableMktDepth for details. Requires a hashref with the following arguments:

  • marketId : integer representing the betfair market id to return the market prices for.

  • selectionId : integer representing the betfair selection id to return market prices for.

  • asianLineId : integer representing the betfair asian line id of the market - only required if the market is an asian line market (optional).

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

  • currencyCode : string representing the three letter ISO currency code. Only certain currencies are accepted by betfair GBP, USD, EUR, NOK, SGD, SEK, AUD, CAD, HKD, DKK (optional)

Example

    my $selectionPrices = $betfair->getDetailAvailableMktDepth({marketId    => 123456789,
                                                                selectionId => 987654321,
                                                                exchangeId  => 1,
                                                               });

getEvents

Returns an array of hashes of events / markets or 0 on failure. See getEvents 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});

getInPlayMarkets

Returns an arrayref of hashrefs of market data or 0 on failure. See getInPlayMarkets for details. Requires the following parameter:

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $inPlayMarkets = $betfair->getInPlayMarkets({exchangeId => 1});

getMarket

Returns a hash of market data or 0 on failure. See getMarket for details. Requires:

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

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

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

getMarketInfo

Returns a hash of market data or 0 on failure. See getMarketInfo for details. Requires a hashref with the following parameters:

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

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $marketData = $betfair->getMarketInfo({  marketId    => 108690258,
                                                exchangeId  => 1,
                                             });

getMarketPrices

Returns a hashref of market data or 0 on failure. See getMarketPrices for details. Requires:

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

  • currencyCode : string representing the three letter ISO currency code. Only certain currencies are accepted by betfair GBP, USD, EUR, NOK, SGD, SEK, AUD, CAD, HKD, DKK (optional)

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $marketPrices = $betfair->getMarketPrices({  marketId    => 108690258
                                                    exchangeId  => 2,
                                                 });

getMarketPricesCompressed

Returns a hashref of market data including an arrayhashref of individual selection prices data. See getMarketPricesCompressed for details. Note that this method de-serializes the compressed string returned by the betfair method into a Perl data structure. Requires:

  • marketId : integer representing the betfair market id.

  • currencyCode : string representing the three letter ISO currency code. Only certain currencies are accepted by betfair GBP, USD, EUR, NOK, SGD, SEK, AUD, CAD, HKD, DKK (optional)

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $marketPriceData = $betfair->getMarketPricesCompressed({marketId => 123456789}); 

getMUBets

Returns an arrayref of hashes of bets or 0 on failure. See getMUBets 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#i1028849i1028849

  • orderBy : string of a valid BetsOrderByEnum types as defined by betfair. see BetsOrderByEnum

  • 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)

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

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

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

getMUBetsLite

Returns an arrayref of hashes of bets or 0 on failure. See getMUBetsLite 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#i1028849i1028849

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

  • excludeLastSecond : boolean string value ('true' or 'false'). If true then excludes bets matched in the past second (optional)

  • matchedSince : a string datetime for which to only return bets matched since this datetime. Must be a valid XML datetime format, see example below (optional)

  • orderBy : string of a valid BetsOrderByEnum types as defined by betfair. see BetsOrderByEnum

  • 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

  • sortOrder : string of the betfair sortOrder enumerated type (either 'ASC' or 'DESC'). See sortOrderEnum for details.

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

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $muBets = $betfair->getMUBetsLite({
                            betStatus           => 'MU',
                            orderBy             => 'PLACED_DATE',
                            excludeLastSecond   => 'false',
                            recordCount         => 100,
                            startRecord         => 0,
                            matchedSince        => '2013-06-01T00:00:00.000Z',
                            sortOrder           => 'ASC',
                            marketId            => 123456789,
                            exchangeId          => 1,
                 });

getMarketProfitAndLoss

Returns a hashref containing the profit and loss for a particular market. See getMarketProfitAndLoss for details. Requires:

  • marketId : integer representing the betfair market id to return the market traded volume for

  • includeSettledBets : string boolean ('true' or 'false') to include settled bets in the P&L calculation (optional)

  • includeBspBets : string boolean ('true' or 'false') to include BSP bets in the P&L calculation

  • netOfCommission : string boolean ('true' or 'false') to include commission in P&L calculation (optional)

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $marketProfitAndLoss = $betfair->getMarketProfitAndLoss({marketId        => 923456791,
                                                                includeBspBets  => 'false',
                                                                exchangeId      => 1,
                                                                });

getMarketTradedVolume

Returns an arrayref of hashrefs containing the traded volume for a particular market and selection. See getMarketTradedVolume for details. Requires:

  • marketId : integer representing the betfair market id to return the market traded volume for.

  • selectionId : integer representing the betfair selection id of the selection to return matched volume for.

  • asianLineId : integer representing the betfair asian line id - this is optional unless the request is for an asian line market.

  • currencyCode : string representing the three letter ISO currency code. Only certain currencies are accepted by betfair GBP, USD, EUR, NOK, SGD, SEK, AUD, CAD, HKD, DKK (optional)

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $marketVolume = $betfair->getMarketTradedVolume({marketId    => 923456791,
                                                        selectionId => 30571,
                                                        exchangeId  => 2,
                                                       });

getMarketTradedVolumeCompressed

Returns an arrayref of selections with their total matched amounts plus an array of all traded volume with the trade size and amount. See getMarketTradedVolumeCompressed for details. Note that this service de-serializes the compressed string return by betfair into a Perl data structure. Requires:

  • marketId : integer representing the betfair market id to return the market traded volume for.

  • currencyCode : string representing the three letter ISO currency code. Only certain currencies are accepted by betfair GBP, USD, EUR, NOK, SGD, SEK, AUD, CAD, HKD, DKK (optional)

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $marketVolume = $betfair->getMarketTradedVolumeCompressed({  marketId    => 923456791,
                                                                    exchangeId  => 2,
                                                                 });

getPrivateMarkets

Returns an arrayref of private markets - see getPrivateMarkets for details. Requires a hashref with the following arguments:

  • eventTypeId : integer representing the betfair id of the event type to return private markets for.

  • marketType : string of the betfair marketType enum see marketTypeEnum.

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $privateMarkets = $betfair->getPrivateMarkets({  eventTypeId => 1,
                                                        marketType  => 'O',
                                                        exchangeId  => 1,
                                                    });

getSilks

This method is not available on the free betfair API.

Returns an arrayref of market racing silks data or 0 on failure. See getSilksV2 for details. Requires the following parameters:

  • markets : an arrayref of integers representing betfair market ids

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $silks = $betfair->getSilksV2({  markets     => [123456,9273649],
                                        exchangeId  => 1, 
                                     });

getSilksV2

This method is not available on the free betfair API.

Returns an arrayref of market racing silks data or 0 on failure. See getSilksV2 for details. Requires the following parameters:

  • markets : an arrayref of integers representing betfair market ids

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $silks = $betfair->getSilksV2({  markets     => [123456,9273649],
                                        exchangeId  => 1, 
                                     });

BET PLACEMENT API METHODS

cancelBets

Cancels up to 40 unmatched and active bets on betfair. Returns an arrayref of hashes of cancelled bets. See cancelBets for details. Requires a hashref with the following parameters:

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

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

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

cancelBetsByMarket

Receives an arrayref of marketIds and cancels all unmatched bets on those markets. Returns an arrayref of hashrefs of market ids and results. See cancelBetsByMarket for details. Requires a hashref with the following parameters:

  • markets : arrayref of integers representing market ids.

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $cancelledBets = $betfair->cancelBetsByMarket({markets       => [123456789, 432596611],
                                                      exchangeId    => 1,
                                                     });

placeBets

Places up to 60 bets on betfair and returns an array of results or zero on failure. See placeBetshttp://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#d83e452 for details.

    • betPersistenceType : a string of the betPersistenceTypeEnum, usually 'NONE' for standard exchange bets. See http://bdp.betfair.com/docs/BetfairSimpleDataTypes.html#d83e531 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.

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    $myBetPlacedResults = $betfair->placeBets({
                                        bets        => [{   asianLineId         => 0,
                                                            betCategoryType     => 'E',
                                                            betPersistenceType  => 'NONE',
                                                            betType             => 'B',
                                                            bspLiability        => 2,
                                                            marketId            => 123456789,
                                                            price               => 5,
                                                            selectionId         => 99,
                                                            size                => 10,
                                                        }],
                                         exchangeId => 1,
                                    });

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:

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

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

ACCOUNT MANAGEMENT API METHODS

addPaymentCard

Adds a payment card to your betfair account. Returns an arrayref of hashes of payment card responses or 0 on failure. See addPaymentCard. 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#i1028865i1028865

  • 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    => 'Tasty bush',
                                            address2    => 'Mountain Plains',
                                            town        => 'Hoofton',
                                            zipCode     => 'MO13FR',
                                            county      => 'Mooshire',
                                            country     => 'UK',
                                 });

deletePaymentCard

Deletes a registered payment card from your betfair account. See deletePaymentCard for further details. Returns the betfair response as a hashref or 0 on failure. Requires:

  • nickName : string of the card nickname to be deleted (must be less than 9 characters)

  • password : string of the betfair account password

Example

    my $deleteCardResponse = $betfair->deletePaymentCard({
                                            nickName  => 'checking',
                                            password  => 'password123',
                                    });

depositFromPaymentCard

Deposits money in your betfair account using a payment card. See depositFromPaymentCard 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

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

forgotPassword

NB. This service is largely redundant as it requires an authenticated session to work, however it is included for the sake of completeness.

Resets the betfair account password via a 2 stage process. See forgotPassword and the example below for details. Returns the betfair response as a hashref for stage 1, 1 on a successful passwprd reset or 0 on failure. Note that this service can be difficult to succeed with - user the getError method to inspect the response message from betfair. Requires:

  • username : string of the betfair username for the account to reset the password for

  • emailAddress : string of the betfair account email address

  • countryOfResidence : string of the country of residence the betfair account is registered to

  • forgottenPasswordAnswer1 : string of the answer to question1 as returned by this service on the first request (optional)

  • forgottenPasswordAnswer2 : string of the answer to question2 as returned by this service on the first request (optional)

  • newPassword : string of the new account password (optional)

  • newPasswordRepeat : string of the new account password (optional)

Example

    use Data::Dumper;

    my $securityQuestions = $betfair->forgotPassword({
                                            username            => 'sillymoose',
                                            emailAddress        => 'sillymoos@cpan.org',
                                            countryOfResidence  => 'United Kingdom',
                                    });
    print Dumper($securityQuestions);

    # now call service again with answers to security questions and new password parameters
    my $resetPasswordResponse =  $betfair->forgotPassword({
                                            username                    => 'sillymoose',
                                            emailAddress                => 'sillymoos@cpan.org',
                                            countryOfResidence          => 'United Kingdom',
                                            forgottenPasswordAnswer1    => 'dasher',
                                            forgottenPasswordAnswer2    => 'hoofs',
                                            newPassword                 => 'moojolicious',
                                            newPasswordRepeat           => 'moojolocious',
                                    });

getAccountFunds

Returns a hashref of the account funds betfair response. See getAccountFunds for details. Requires a hashref with the following parameters:

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

Example

    my $funds = $betfair->getAccountFunds({exchangeId => 1});

getAccountStatement

Returns an arrayref of hashes of account statement entries or 0 on failure. See getAccountStatement 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 AccountStatementIncludeEnum for details

  • exchangeId : integer representing the exchange id to connect to, either 1 (UK and rest of the world) or 2 (Australia)

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',
                                    exchangeId      => 2,
                              });

getPaymentCard

Returns an arrayref of hashes of payment card or 0 on failure. See getPaymentCard for details. Does not require any parameters.

Example

    my $cardDetails = $betfair->getPaymentCard;

getSubscriptionInfo

This service is not available with the free betfair API.

Returns an arrayref of hashes of subscription or 0 on failure. See getSubscriptionInfo for details. Does not require any parameters.

Example

    my $subscriptionData = $betfair->getSubscriptionInfo;

modifyPassword

Changes the betfair account password. See modifyPassword for details. Returns the betfair response as a hashref or 0 on failure. Requires:

  • password : string of the current account password

  • newPassword : string of the new account password

  • newPasswordRepeat : string of the new account password

Example

    my $response = $betfair->modifyPassword({
                                        password            => 'itsasecret',
                                        newPassword         => 'moojolicious',
                                        newPasswordRepeat   => 'moojolicious',
                                    });

modifyProfile

Modifies the account profile details of the betfair account. See modifyProfile for details. Returns 1 on success or 0 on failure. Requires a hashref with the following parameters:

  • password : string of the password for the betfair account

  • address1 : string of address line 1 (optional)

  • address2 : string of address line 2 (optional)

  • address3 : string of address line 3 (optional)

  • townCity : string of the town/city (optional)

  • countyState : string of the county or state - note for Australian accounts this must be a valid state (optional)

  • postCode : string of the postcode (aka zipcode). (optional)

  • countryOfResidence : string of the country of residence (optional)

  • homeTelephone : string of the home telephone number (optional)

  • workTelephone : string of the work telephone number (optional)

  • mobileTelephone : string of the mobile telephone number (optional)

  • emailAddress : string of the email address (optional)

  • timeZone : string of the timezone (optional)

  • depositLimit : integer of the deposite limit to set (optional)

  • depositLimitFrequency : string of the betfair GamcareLimitFreq enumerated type. See gamcareLimitFreqEnum for details (optional)

  • lossLimit : integer of the Gamcare loss limit for the account (optional)

  • lossLimitFrequency : string of the betfair GamcareLimitFreq enumerated type. See gamcareLimitFreqEnum for details (optional)

  • nationalIdentifier : string of the national identifier (optional)

Example

    # update mobile number
    my $response = $betfair->modifyProfile({
                                    password        => 'itsasecret',
                                    mobileTelephone => '07777777777',
                                });

retrieveLIMBMessage

This service is not available with the betfair free API.

Returns a hashref of the betfair response. See retrieveLIMBMessage for details. No parameters are required.

Example

    my $limbMsg = $betfair->retrieveLimbMessage;

selfExclude

WARNING - using this method will deactivate your betfair account for a minimum of 6 months. See selfExclude for details. Returns 1 on success or 0 on failure. Requires the following parameters in a hashref:

  • selfExclude : string boolean response (should be 'true' to succeed)

  • password : string of the betfair account password

Example

    $excludeResult = $betfair->selfExclude({
                                selfExclude => 'true',
                                password    => 'itsasecret',
                            });

setChatName

This service is not available with the free betfair API, nor with the paid personal betfair API.

Sets the chat name of the betfair account. See setChatName for details. Returns 1 on success or 0 on failure. Requires the following parameters in a hashref:

  • chatName : string of the desired chatname

  • password : string of the betfair account password

Example

    $excludeResult = $betfair->setChatName({
                                chatName => 'sillymoose',
                                password => 'itsasecret',
                            });

submitLIMBMessage

This service is not available with the betfair free API.

Submits a LIMB message to the betfair API. See submitLIMBMessage for details. Returns 1 on success or 0 on failure. betfair returns additional validation error information on failure, so be sure to check the error message using the getError method. Requires a hashref with the following parameters:

  • password : string of the betfair account password

  • submitPersonalMessage : a hashref containing the following key / pair values (optional):

    • messageId : integer of the message Id

    • acknowledgement : string 'Y'

  • submitTCPrivacyPolicyChangeMessage : a hashref containing the following key / value pairs (optional):

    • messageId : integer of the message Id

    • tCPrivacyPolicyChangeAcceptance : string 'Y'

  • submitPasswordChangeMessage : a hashref containing the following key / value pairs (optional):

    • messageId : integer of the message Id

    • newPassword : string of the new password

    • newPasswordRepeat : string of the new password

  • submitBirthDateCheckMessage : a hashref containing the following key / value pairs (optional):

    • messageId : integer of the message Id

    • detailsCorrect : string of either 'Y' or 'N'

    • correctBirthDate : string of the correct birthdate - should be a valid XML datetime format

  • submitAddressCheckMessage : a hashref containing the following key / value pairs (optional):

    • messageId : integer of the message Id

    • detailsCorrect : string of either 'Y' or 'N'

    • newAddress1 : string of the first line of the address

    • newAddress2 : string of the second line of the address

    • newAddress3 : string of the third line of the address

    • newTown: string of the town of the address

    • newZipCode: string of the postal code of the address

    • newCountry: string of the the Country of the address

    submitContactDetailsCheckMessage: a hashref containing the following key / value pairs (optional):

    • messageId : integer of the message Id

    • detailsCorrect : string of either 'Y' or 'N'

    • newHomeTelephone : string of the new home telephone number

    • newWorkTelephone : string of the new work telephone number

    • newMobileTelephone : string of the new mobile telephone number

    • newEmailAddress : string of the new email address

  • submitChatNameChangeMessage : a hashref containing the following key / value pairs (optional):

    • messageId : integer of the message Id

    • newChatName : string of the new chat name

  • submitCardBillingAddressCheckItems : an arrayref of hashrefs containing the following key / value pairs (optional):

    • messageId : integer of the message Id

    • detailsCorrect : string of either 'Y' or 'N'

    • nickName : string of the card nick name (8 characters or less)

    • newAddress1 : string of the first line of the address

    • newAddress2 : string of the second line of the address

    • newAddress3 : string of the third line of the address

    • newTown: string of the town of the address

    • newZipCode: string of the postal code of the address

    • newCountry: string of the the Country of the address

Example

    my $limbMsg = $betfair->submitLimbMessage({
                                        password                => 'itsasecret',
                                        submitPersonalMessage   => { messageId      => 123456789,
                                                                     acknowledgement=> 'Y',
                                                                   },
                                        });

transferFunds

Transfers funds between the UK and Australian wallets. See transferFunds for details. Returns a hashref of the betfair response or 0 on failure. Requires the following parameters in a hashref:

  • sourceWalletId : integer either: 1 for UK wallet or 2 for the Australian wallet

  • targetWalletId : integer either: 1 for UK wallet or 2 for the Australian wallet

  • amount : number representing the amount of money to transfer between wallets

Example

    # transfer 15 from the UK wallet to the Australian wallet
    $excludeResult = $betfair->transferFunds({
                                sourceWalletId  => 1,
                                targetWalletId  => 2,
                                amount          => 15.0,
                            });

updatePaymentCard

Updates a payment card on your betfair account. Returns a hashref betfair response or 0 on failure. See updatePaymentCard. Requires:

  • 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

  • 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 $updatePaymentCardResponse = $betfair->updatePaymentCard({
                                            cardStatus  => 'UNLOCKED',
                                            startDate   => '0113',
                                            expiryDate  => '0116',
                                            issueNumber => 'NULL',
                                            billingName => 'The Sillymoose',
                                            nickName    => 'democard',
                                            password    => 'password123',
                                            address1    => 'Tasty bush',
                                            address2    => 'Mountain Plains',
                                            town        => 'Hoofton',
                                            zipCode     => 'MO13FR',
                                            county      => 'Mooshire',
                                            country     => 'UK',
                                 });

viewProfile

Returns a hashref betfair response or 0 on failure. See viewProfile. Requires no parameters.

Example

    my $profile = $betfair->viewProfile;

viewProfileV2

Returns a hashref betfair response or 0 on failure. See viewProfileV2. Requires no parameters.

Example

    my $profile = $betfair->viewProfileV2;

viewReferAndEarn

Returns a hashref containing the betfair account's refer and earn code or 0 on failure. See viewReferAndEarn for details. Requires no parameters.

Example

    my $referAndEarnCode = $betfair->viewReferAndEarn;

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 withdrawToPaymentCard 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',
                                    }); 

INTERNAL METHODS

_doRequest

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.

_sortArrayRef

Returns a sorted arrayref based on price.

_addPaymentCardLine

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

_forceArray

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

_checkParams

Receives an hashref of parameter types and a hashref of arguments. Checks that all mandatory arguments are present using _checkParam and that no additional parameters exist in the hashref.

_checkParam

Checks the parameter using the TypeCheck.pm object, returns 1 on success and 0 on failure.

_clearData

Sets all message related object attributes to null - this is so that the error message from the previous API call is not mis-read as relevant to the current call.

AUTHOR

David Farrell, <davidnmfarrell at gmail.com>, perltricks.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.