Перепрыгнеть в содержание


- - - - -

Пошаговый пример и пхп скрипт для подключения к рынкам Бетфайр через php


2 ответов в эту тему

#1 Гость_oOo_*


  • Не Местный

Добавлено 09 February 2012 - 03:53

Этот пример предполагает что у вас уже есть установленный сервер с поддержкой пхп

Это пример покажет как начать работать с бетфайр используя собственный веб сервер и пхп скрипты
Это пример покажет как зайти и выйти из бетфайр через php и получить информацию об активных рынках:
getActiveEventTypes, getAllMarkets, getMarket, getMarketPricesCompressed, placeBet, getBetLite, logout.

Шаг 1:
Создаем проект в www нашего веб сервера (например www/myproject/)

Шаг 2:
Загружаем Бетфайр API Фреймворк и распаковываем в наш проект. (например www/myproject/betfairapi)

Шаг 3:
Создаем файл football.php в папке нашего проекта (например www/myproject/)

Шаг 4:
Открываем файл football.php в любом редакторе например Блокноте и копируем код ниже в файл football.php

Шаг 5:
Изменяем графы имя и пароль а так же указываем правильный путь к
include_once(".\BetfairAPIFramework\betfair.php");

и сохраняем файл.

Шаг 6:
Идем в веб браузер и пишем путь к файлу (например: localhost/myproject/football.php )


<?php
// Load frame work
include_once(".\BetfairAPIFramework\betfair.php");
$betfairlibrary = new Betfair("phpprojects\bfautomation\");
error_reporting(E_ALL);
ini_set('display_errors', 0);

/*******************************
			Login
/*******************************/
/*Login with account credentials and get the session. If error returned/no session, terminate. Otherwise print
login ok and return session token.*/
$session = Login('username', 'password', 82);
if(!isset($session)) {
  
	print "Неверный логин!";
	return;
}
print "Логин: OK (".$session.") \n";

/*******************************
		Get Event ID
*******************************/
/*Using the SearchForEvent function, look for 'Soccer' to determine the parent eventId. If nothing is found,
then terminate. Otherwise print the parent eventId. */
$eventId = SearchForEvent($session,"Soccer");
if(!isset($eventId)) {
  
	print "Event ID retrieval failed, terminating script!";
	return;
}
print "Get Event ID: OK (".$eventId.") \n";

/*******************************
	Get Match Odds Markets
*******************************/
/*Using the GetMatchOddsMarkets function, return markets within the next 24 hours. If nothing is found,
then terminate. Otherwise print the number of markets found. Markets found within the function will be sent
back here to the markets variable*/
$fromDate = time(); // Now
$toDate = time() + (1 * 24 * 60 * 60);
$markets = GetMatchOddsMarkets ($session, $fromDate, $toDate,$eventId);
if(!isset($markets)) {
  
	print "Match Odds Markets retrieval failed, terminating script!";
	return;
}
print "************************************************************************\n";
print "Get Match Odds Markets: OK (Found ".count($markets)." markets) \n";
print "************************************************************************\n";
/*********************************************
  Get Match Odds Market Prices and place bets
/*********************************************/
/*Set up an array called bets. For each of the markets found above, get the market prices for each. First, for
clarity, print the path of each of the markets for which we will return prices. Then, using the SelectionPrices
function (which uses a library utility), send the Id to the function and return prices for each market.
Iterate through each runner, placing a bet on each. Here bets at placed at odds of 1000 for testing
purposes. Normally bets are placed at the best price. Results are added to the bets array. */
$bets = array();
foreach ($markets as $market) {
  
	print "Getting prices for market: ".$market->menuPath."\\".$market->name."(".$market->marketId.") \n";
  
	$prices = SelectionPrices($session, $market->marketId);
		  
	foreach ($prices[0]["runnerInfo"] as $p ){
	  
		print "Placing back bet @ ".$p["priceToBack"][0]["price"]."\n";
		$bet = PlaceBet($session, $market->marketId, $p["selectionId"], 1000);
		$bets[] = $bet;
		break;	  
	}
}
if(count($bets) == 0) {
print "\n************************************************\n";
print "No bets struck: Terminating session and closing!\n";
print "************************************************\n";
die;
}

/************************************************
  Check if bets are matched and cancel unmatched
/************************************************/
/* Loop up to three times, checking at the end how many times we have looped. Wait, to ensure time for the bets to
be matched.
Loop through each bet, using the IsBetMatched function to check (and print for clarity) the status of the bet. If
any bet remains unmatched after three loops (six seconds) then cancel the bets using the CancelBet function. Then
check (and print for clarity) the status of the remaining bets (which should be none or all matched).

*/
$count = 1;
while ($count <=3) {
  
	print "Going to sleep for 2 seconds.\n";
	sleep(2);
	foreach ($bets as $bet) {
	  
		foreach ($bet->Result->betResults as $B)/> {
		  
			$status = IsBetMatched ($session, $b->betId);		  
			print "Bet status for bet id ".$b->betId." is ".$status->Result->betLite->betStatus.".\n";
		  
			if($status->Result->betLite->betStatus == "U" && $count == 3) {
			  
				print "Bet not matched in 6 seconds cancelling bet id ".$b->betId.".\n";
				$cancelBetResult = CancelBet ($session, $status->Result->betLite->betId);
			  
				$status = IsBetMatched ($session, $b->betId);
				print "Bet status for bet id ".$b->betId." is ".$status->Result->betLite->betStatus.".\n";
			}
		}
	}
  
	$count += 1;
}

/*********************
		 Logout
/*********************/
print "*************************************\n";
print "Terminating session and closing!\n";
print "*************************************\n";
$betfairlibrary->betfair_global_api->betfair_api_logout ($session);

/**
* Log-in, create a session token or returns NULL if log-in fails.
*
* Using the framework, call API log-in service and return the response. Using the GetApiResponse function,
* determine whether login request was successful. If not, print reason and terminate.
*
* @param unknown_type $username
* @param unknown_type $password
* @param unknown_type $productId
* @param unknown_type $softwareId
*/
function Login ($username, $password, $productId, $softwareId=0) {
	global $betfairlibrary;
  
	$response = $betfairlibrary->betfair_global_api->betfair_api_login($username,$password,$productId, $softwareId);
	$loginResponseError = GetApiResponse($response,'login response');
  
	if($loginResponseError[0]==='' && $loginResponseError[1] != ''){
  
		return $loginResponseError[1];
	}
	else {
	  
		//Print reason
		print "Login failed: ".$loginResponseError[0]."\n";
		die;
	}
	return NULL;
}
/**
* Using the Framework, call getActiveEventTypes and return the response. For each item, search for a sting
* 'as specified in the logic'. Return the id for this eventType. *
*/
function SearchForEvent ($session, $searchString) {
	global $betfairlibrary;
  
	$response = $betfairlibrary->betfair_global_api->betfair_get_active_event_types($session);
		  
	foreach ($response->Result->eventTypeItems->EventType as $e) {
			  
		if($searchString === $e->name) {
			return $e->id;
		}
	}
  
	return;
}

/**
* Get all GB Match Odds markets for the next 24 hours for specified event ID.
* Using the Framework, call getAllMarkets API service and return the response as an array (using the library
* utility).  For each array (market) item, search for a market name of 'match odds'. If
* something is found, and the country code is GBR and the market is active, then get the market info by
* calling getMarket API service for each. For each of these, send the marketId to the results array in the logic.
* To work around the Free Access API throttling for getMarket, let the script sleep if a EXCEEDED_THROTTLE error
* is returned.
*
* @param unknown_type $session
*/
function GetMatchOddsMarkets ($session, $fromDate, $toDate, $eventTypeId, $countries='GBR', $locale='en') {
	global $betfairlibrary;
  
	$eventTypeIds[] = intval( $eventTypeId );
	  
	$response = $betfairlibrary->betfair_exchange_api->betfair_get_all_markets($session, $eventTypeIds, $countries, $locale, $fromDate, $toDate);
  
	if(!isset($response)) {
		return ;
	}
  
	$allMarketsArray = $betfairlibrary->betfair_utilities->gen_all_markets_array($response->Result->marketData);
  
	$resultArray = array();
	foreach ($allMarketsArray as $item)
	{
		if	 (
				$item["marketName"] === "Match Odds" &&
				$item["countryCode"] === $countries &&
				$item["marketStatus"] === "ACTIVE"
			)
		{
			print $item["marketName"]." ".$item["countryCode"]." ".$item["marketStatus"]."\n";
		  
			$status = "WORKING";
			while ($status != "OK") {
			  
				$market = $betfairlibrary->betfair_exchange_api->betfair_get_market($session,$item["marketId"]);
				print "Get market header->errorCode: ".$market->Result->header->errorCode."\n";
			  
				$status = $market->Result->header->errorCode;
			  
				if($market->Result->header->errorCode == "OK") {
					$resultArray[] = $market->Result->market;
				}
				else {
				  
					print "Throttling, sleep for 3 seconds\n";
					sleep(3);				  
				}			  
			}
		}
	}
  
	return $resultArray;
}
/**
* Get the prices for the specified market.
* Using the Framework, call getMarketPricesCompressed API service for each market (using id from above) and
* return the array of prices (using the library utility). Send these prices back to results array in the logic.
*
* @param unknown_type $session
* @param unknown_type $marketId
* @param unknown_type $currency
* @param unknown_type $exchangeId
*/
function SelectionPrices ($session, $marketId, $currency='GBP', $exchangeId=1){
	global $betfairlibrary;
  
	$response = $betfairlibrary->betfair_exchange_api->betfair_get_market_prices_compressed($session, $marketId, $currency, $exchangeId);
  
	$marketPricesArray = $betfairlibrary->betfair_utilities->gen_market_prices_array($response->Result->marketPrices);
  
	return $marketPricesArray;
}
/**
* Place bet on selection.
* Using the Framework, call placebets API service and place bets on selections as identified in the logic
* at a size of 2.
*
* @param unknown_type $session
* @param unknown_type $marketId
* @param unknown_type $selectionId
* @param unknown_type $price
* @param unknown_type $size
* @param unknown_type $asianLineId
* @param unknown_type $betCategory
* @param unknown_type $betPersistence
* @param unknown_type $betType
* @param unknown_type $bspLiability
* @return unknown
*/
function PlaceBet ($session, $marketId, $selectionId, $price, $size=2, $asianLineId=0, $betCategory='E', $betPersistence='NONE', $betType='B', $bspLiability=0){
	global $betfairlibrary;
  
	$bet =  array(
		array(	
					'asianLineId' => $asianLineId,
					'betCategoryType' => $betCategory,
					'betPersistenceType' => $betPersistence,
					'betType' => $betType,
					'bspLiability' => $bspLiability,
					'marketId' => $marketId,
					'price' => $price,
					'selectionId' => $selectionId,
					'size' => $size
					)
				);
			  
	return  $betfairlibrary->betfair_exchange_api-> betfair_place_bets ($session, $bet);	
}

/**
* Check the placed bet has been matched.
*
* Using the Framework, call getBetLite API service using the betId as identified in the logic and return the
* response.
*
* @param unknown_type $session
* @param unknown_type $marketId
* @param unknown_type $betId
* @return unknown
*/
function IsBetMatched ($session, $betId){
	global $betfairlibrary;
  
	$response = $betfairlibrary->betfair_exchange_api->betfair_get_bet_lite ($session, $betId);
	return $response;
}
/**
* Cancel the bet.
*
* Using the Framework, call cancelBets API service using the betId as identified in the logic and return the
* response as an array.
*
* @param unknown_type $session
* @param unknown_type $marketId
* @param unknown_type $betId
* @return unknown
*/
function CancelBet ($session, $betId){
	global $betfairlibrary;
  
	$bets['CancelBets'] = array(
		'betId'	=> $betId
	);
  
	$response = $betfairlibrary->betfair_exchange_api->betfair_cancel_bets ($session, $bets);
	return array();
}
/**
* Return the different API calls' response with error message, session token, and relevant variables
*
* @param array $resp
* @param string $resp_name
* @return array(error, sessionToken, ...)
*/
function GetApiResponse($resp, $resp_name='')
{															
				foreach ($resp as $r)
				{
								$error1 = (string)@$r->header->errorCode;													  
								$error2 = (string)@$r->errorCode;
				}
			  
				if($resp_name=='logout'){
								$sessionToken = '';
				}else {
								$sessionToken = (string)@$r->header->sessionToken;
				}
			  
				if($error1=='OK'&&$error2=='OK'){
								$error = '';
				}else{
								if($error1!="OK"){
												$error = $error1;
								}else{
												$error = $error2;
								}
				}
			  
				return array($error, $sessionToken);
}
?>


#2 OFFLINE   VVladimirr

    Новичок


  • Участник
  • Пип
  • 7 сообщения
0

Добавлено 09 February 2012 - 07:00

А как Вы оформили рынок цен и коф? И как его лучше сделать?

#3 OFFLINE   SylBal

    Новичок


  • Участник
  • Пип
  • 1 сообщения
0

Добавлено 14 November 2012 - 00:06

сделал все по инструкции. но браузер выдал вот это:
Parse error: syntax error, unexpected T_STRING in X:\home\localhost\www\syldys\football.php on line 16
как быть?