Football scores to Guardian programatically - Script & Sample BAF

Football, Soccer - whatever you call it. It is the beautiful game.
zippus
Posts: 181
Joined: Thu Jun 13, 2019 3:19 pm

Cheers sniffer66. Yeah it really has helped. Great that you are continually improving. I have no idea how you progammers do this sort of stuff, so it's very good of you to share.
PlantPots472
Posts: 2
Joined: Sun Jun 30, 2019 10:42 pm

Noticed in the CSV format that Market Time can be used in matching, might be of use if there are similarly named teams but kick off times are different.

NOTE: Guardian appears to use the time the match went in play as the start time.
So if a game kicked off at 15:02, this would no longer match the data from SofaScore which would have 15:00.
Seems to be little value in having this matching option then?
You can adjust the start time in Guardian to be the right time and it starts matching again. Seconds need to be 00 too :(


Updated script to add Kick Off time to 2nd column:

Code: Select all

1
*,12:30,*Manchester*,1,S,Score,0
*,12:30,*Leeds*,2,S,Score,0
*,12:30,*Peterborough*,1,S,Score,0
*,12:30,*Derby*,2,S,Score,0
Left the original code in so just comment/uncomment whichever format you want to use

Football.au3:

Code: Select all

#include <Inet.au3>
#include <json.au3>
#include <Array.au3>
#include <String.au3>
#include <File.au3>
#include <UnixTime.au3>

$TitleString = "Team|Score"


;File to connect Guardian to. Will save in same location as script
$File = "score.csv"


While 1

	$URL = "https://api.sofascore.com/api/v1/sport/football/events/live"
	$data = _INetGetSource($URL)
	$object = json_decode($data)

	Local $Count = Json_Get($object, '.events')

	FileDelete($File)
	FileOpen($File)

	$z = 0

	Local $NameArray[1]

	For $i = 0 To UBound($Count) - 1

		;Writing "1" to first line of the CSV. Required by Guardian
		If $z = 0 Then
			FileWriteLine($File, "1")
		EndIf
		$z = 1

		$HomeTeam = _StringReplaceAccent(Strip(Json_Get($object, '.events' & '[' & $i & '].homeTeam.name')))
		$AwayTeam = _StringReplaceAccent(Strip(Json_Get($object, '.events' & '[' & $i & '].awayTeam.name')))

                ; Get kick off time and format to HH:MM
		$StartTimestamp = Json_Get($object, '.events' & '[' & $i & '].startTimestamp')
		$MarketTime = _StringFormatTime("%H:%M", $StartTimestamp)

		;$HomeString = "*,*," & "*" & $HomeTeam & "*,1,"
		;$AwayString = "*,*," & "*" & $AwayTeam & "*,2,"

		$HomeString = "*," & $MarketTime & ",*" & $HomeTeam & "*,1,"
		$AwayString = "*," & $MarketTime & ",*" & $AwayTeam & "*,2,"

		$HomeString = $HomeString & "S,Score," & Json_Get($object, '.events' & '[' & $i & '].homeScore.current')
		$AwayString = $AwayString & "S,Score," & Json_Get($object, '.events' & '[' & $i & '].awayScore.current')

		;$URL = "https://api.sofascore.com/api/v1/event/" & Json_Get($object, '.events' & '[' & $i & '].id') & "/statistics"
		;MsgBox("", "", $URL)
		;$data1 = _INetGetSource($URL)

		;If $data1 <> "" Then
			;Json_Dump($data1)
			;MsgBox("", "", $data1)
		;EndIf

                ; Available data
		;If $data <> "" Then
		;	Json_Dump($data)
		;	MsgBox("", "", $data)
		;EndIf

		;MsgBox($MB_SYSTEMMODAL, "Score", $HomeString & @CRLF & $AwayString)
		FileWriteLine($File, $HomeString)
		FileWriteLine($File, $AwayString)

		;_ArrayAdd($NameArray, $HomeTeam)
		;_ArrayAdd($NameArray, $AwayTeam)
		;_ArrayDisplay($NameArray)


	Next

	FileClose($File)

	;Wait time between score refresh in milliseconds
	;#######DO NOT SET SHORTER THAN 10S AS YOUR IP MAY BE BLOCKED#####

	Sleep(30000) ;30 seconds


WEnd

Func Strip($Param)
	$f = "NotFound"
	$e = StringSplit($Param, " ")
	;_ArrayDisplay($e)
	For $z = 1 To UBound($e) - 1
		_ArraySearch($NameArray, $e[$z])
		If @error Then
			If StringLen($e[$z]) > 3 Then
				$f = $e[$z]
				ExitLoop
			EndIf
		EndIf
	Next
	;MsgBox($MB_SYSTEMMODAL, "Result", $f )
	Return $f
EndFunc   ;==>Strip


Func _StringReplaceAccent($sString)
	Local $exp, $rep
	Local $Pattern[28][2] = [ _
			["[ÀÁÂÃÅÆ]", "A"], ["[àáâãåa]", "a"], ["Ä", "Ae"], ["[æä]", "ae"], _
			["Þ", "B"], ["þ", "b"], _
			["ÇC", "C"], ["[çcc]", "c"], _
			["[ÈÉÊË]", "E"], ["[èéêë]", "e"], _
			["[ÌÍÎÏ]", "I"], ["[ìíîï]", "i"], _
			["Ñ", "N"], ["ñ", "n"], _
			["[ÒÓÔÕÖØ]", "O"], ["[ðòóôõöø]", "o"], _
			["r", "r"], _
			["[ŠS]", "S"], ["[š]", "s"], _
			["ß", "Ss"], _
			["[ÙÚÛ]", "U"], ["[ùúû]", "u"], ["Ü", "Ue"], ["ü", "ue"], _
			["Ý", "Y"], ["[ýýÿ]", "y"], _
			["Ž", "Z"], ["ž", "z"]]

	For $i = 0 To (UBound($Pattern) - 1)
		$exp = $Pattern[$i][0]
		If $exp = "" Then ContinueLoop
		$rep = $Pattern[$i][1]

		$sString = StringRegExpReplace($sString, $exp, $rep)
		If @error == 0 And @extended > 0 Then
			;ConsoleWrite($sString & @LF & "--> " & $exp & @LF)
		EndIf
	Next

	Return $sString
EndFunc   ;==>_StringReplaceAccent

You'll need to add UnixTime.au3 to the include directory.
Originally it called functions in CrtDll.dll which didn't exist so changed to use msvcrt.dll

UnixTime.au3:

Code: Select all

#include-once

;===============================================================================
;
; AutoIt Version: 3.2.3.0
; Language:       English
; Description:    Dll wrapper functions for dealing with Unix timestamps.
; Requirement(s): msvcrt.dll
; Notes:          If msvcrt.dll is not available then functions will return false
;                 and set @error = 99.
;
;===============================================================================


;===============================================================================
;
; Description:      _TimeGetStamp - Get current time as Unix timestamp value.
; Parameter(s):     None
; Return Value(s):  On Success - Returns Unix timestamp
;                   On Failure - Returns False, sets @error = 99
; Author(s):        Rob Saunders ([email protected])
; User Calltip:		_TimeGetStamp() - Get current time as Unix timestamp value. (required: <_UnixTime.au3>)
;
;===============================================================================

Func _TimeGetStamp()
	Local $av_Time
	$av_Time = DllCall('msvcrt.dll', 'long:cdecl', 'time', 'ptr', 0)
	If @error Then
		SetError(99)
		Return False
	EndIf
	Return $av_Time[0]
EndFunc

;===============================================================================
;
; Description:		_TimeMakeStamp - Create Unix timestamp from input values.
; Syntax:			_TimeMakeStamp( [ second [, minute [, hour [, day [, month [, year [, isDST ]]]]]]] )
; Parameter(s):     Second - Second for timestamp (0 - 59)
;					Minute - Minute for timestamp (0 - 59)
;					Hour   - Hour for timestamp (0 - 23)
;					Day    - Day for timestamp (1 - 31)
;					Month  - Month for timestamp (1 - 12)
;					Year   - Year for timestamp (1970 - 2038)
;					* All the above values default to the 'Default' keyword, where the current
;					  time/date value will be used.
;					IsDST  - Set to 1 during Daylight Saving Time (DST)
;						   - Set to 0 not during DST
;						   - Set to -1 if unknown, function will try to figure it out
;						   - Default is -1
; Return Value(s):  On Success - Returns Unix timestamp
;		   			On Failure - Parameter error, returns -1
;			      			   - Dll error, returns False, sets @error = 99
; Notes:			The function will try and calculate dates for numbers outside of the
;					usual range.
;					For example: _TimeMakeStamp(0, 0, 0, 32, 1, 1995)
;					32nd day of January? Obviously that's not a valid date, but the function
;					automatically calculates this to be February 1st. A date of 0 will return
;					the last day of the previous month.
; User CallTip:		_TimeMakeStamp($i_Sec = Default, $i_Min = Default, $i_Hour = Default, $i_Day = Default, $i_Mon = Default, $i_Year = Default, $i_IsDST = -1) - Create a UNIX timestamp from input values. (required: <_UnixTime.au3>)
; Author(s):		Rob Saunders ([email protected])
;
;===============================================================================
Func _TimeMakeStamp($i_Sec = Default, $i_Min = Default, $i_Hour = Default, $i_Day = Default, $i_Mon = Default, $i_Year = Default, $i_IsDST = -1)
	Local $struct_Time, $ptr_Time, $av_Time
	$struct_Time = DllStructCreate('uint;uint;uint;uint;uint;uint;uint;uint;uint')

	Select
		Case $i_Sec = Default
			$i_Sec = @SEC
			ContinueCase
		Case $i_Min = Default
			$i_Min = @MIN
			ContinueCase
		Case $i_Hour = Default
			$i_Hour = @HOUR
			ContinueCase
		Case $i_Day = Default
			$i_Day = @MDAY
			ContinueCase
		Case $i_IsDST = Default
			$i_IsDST = -1
	EndSelect
	; The following is done because the mktime function demands
	; that the month be in 0-11 (Jan = 0) format instead of 1-12.
	Select
		Case $i_Mon = Default
			$i_Mon = (@MON - 1)
		Case $i_Mon <> Default
			$i_Mon -= 1
	EndSelect
	; The following is done because the mktime function expects the year in format
	; (full year - 1900), thus 99 = 1999 and 100 = 2005. The function will try
	; to figure out what year the user is trying to use. Thus if the function recieves
	; 70, it's untouched, but if the user gives 1970, 1900 is subtracted automatically.
	; Any year above 99 has 1900 automatically subtracted.
	Select
		Case $i_Year = Default
			$i_Year = (@YEAR - 1900)
		Case $i_Year < 70
			$i_Year += 100
		Case $i_Year > 99
			$i_Year -= 1900
	EndSelect

	DllStructSetData($struct_Time, 1, $i_Sec)
	DllStructSetData($struct_Time, 2, $i_Min)
	DllStructSetData($struct_Time, 3, $i_Hour)
	DllStructSetData($struct_Time, 4, $i_Day)
	DllStructSetData($struct_Time, 5, $i_Mon)
	DllStructSetData($struct_Time, 6, $i_Year)
	DllStructSetData($struct_Time, 9, $i_IsDST)

	$ptr_Time = DllStructGetPtr($struct_Time)
	$av_Time = DllCall('msvcrt.dll', 'long:cdecl', 'mktime', 'ptr', $ptr_Time)
	If @error Then
		SetError(99)
		Return False
	EndIf

	Return $av_Time[0]
EndFunc

;===============================================================================
;
; Description:      _StringFormatTime - Get a string representation of a timestamp
;					according to the format string given to the function.
; Syntax:			_StringFormatTime( "format" [, timestamp [, max length ]] )
; Parameter(s):     Format String - A format string to convert the timestamp to.
; 									See notes for some of the values that can be
; 									used in this string.
; 					Timestamp     - A timestamp to format, possibly returned from
; 									_TimeMakeStamp. If left empty, default, or less
;									than 0, the current time is used. (default is -1)
; 					Max Length    - Maximum length of the string to be returned.
; 									Default is 255.
; Return Value(s):  On Success - Returns string formatted timestamp.
;		   			On Failure - Returns False, sets @error = 99
; Requirement(s):	_TimeGetStamp
; Notes:			The date/time specifiers for the Format String:
; 						%a	- Abbreviated weekday name (Fri)
; 						%A	- Full weekday name (Friday)
; 						%b	- Abbreviated month name (Jul)
; 						%B	- Full month name (July)
; 						%c	- Date and time representation (MM/DD/YY hh:mm:ss)
; 						%d	- Day of the month (01-31)
; 						%H	- Hour in 24hr format (00-23)
; 						%I	- Hour in 12hr format (01-12)
; 						%j	- Day of the year (001-366)
; 						%m	- Month number (01-12)
; 						%M	- Minute (00-59)
; 						%p	- Ante meridiem or Post Meridiem (AM / PM)
; 						%S	- Second (00-59)
; 						%U	- Week of the year, with Sunday as the first day of the week (00 - 53)
; 						%w	- Day of the week as a number (0-6; Sunday = 0)
; 						%W	- Week of the year, with Monday as the first day of the week (00 - 53)
; 						%x	- Date representation (MM/DD/YY)
; 						%X	- Time representation (hh:mm:ss)
; 						%y	- 2 digit year (99)
; 						%Y	- 4 digit year (1999)
; 						%z, %Z	- Either the time-zone name or time zone abbreviation, depending on registry settings; no characters if time zone is unknown
; 						%%	- Literal percent character
;	 				The # character can be used as a flag to specify extra settings:
; 						%#c	- Long date and time representation appropriate for current locale. (ex: "Tuesday, March 14, 1995, 12:41:29")
; 						%#x	- Long date representation, appropriate to current locale. (ex: "Tuesday, March 14, 1995")
; 						%#d, %#H, %#I, %#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y	- Remove leading zeros (if any).
;
; User CallTip:		_StringFormatTime($s_Format, $i_Timestamp = -1, $i_MaxLen = 255) - Get a string representation of a timestamp according to the format string given to the function. (required: <_UnixTime.au3>)
; Author(s):        Rob Saunders ([email protected])
;
;===============================================================================
Func _StringFormatTime($s_Format, $i_Timestamp = -1, $i_MaxLen = 255)
	Local $struct_Time, $ptr_Time, $av_Time, $av_StrfTime

	If $i_Timestamp = default OR $i_Timestamp < 0 Then
		$i_Timestamp = _TimeGetStamp()
	EndIf
	$ptr_Time = DllCall('msvcrt.dll', 'ptr:cdecl', 'localtime', 'long*', $i_Timestamp)
	If @error Then
		SetError(99)
		Return False
	EndIf

	$av_StrfTime = DllCall('msvcrt.dll', 'int:cdecl', 'strftime', _
		'str', '', _
		'int', $i_MaxLen, _
		'str', $s_Format, _
		'ptr', $ptr_Time[0])
	Return $av_StrfTime[1]
EndFunc
sniffer66
Posts: 1679
Joined: Thu May 02, 2019 8:37 am

Nice one PlantPots - good to have your input. I did briefly consider start times and not sure why I discarded it originally

Will butt in nicely with the other improvements I'll post this week. It's testing out well and havent seen an incorrect match returned yet

Edit: Just seen your note. Maybe thats why I did it ;)
PlantPots472
Posts: 2
Joined: Sun Jun 30, 2019 10:42 pm

Might need further investigating.
Seems to be if you add a market to guardian that is already in play that you can get odd start times.
Those added before they go in play have been fine so far today
sniffer66
Posts: 1679
Joined: Thu May 02, 2019 8:37 am

I've some updated code for the original script that I've been using on another API, but is there any interest in me creating an update to this script that uses the SofaScore API to pass current home\away score, SOT's , SOFT's, corners, possession, passes, Big chances etc, and also get the 5m Avg, 10m and match avg from the SofaScore momentum graph ? Then pass all that to Guardian as Event SV's.

I've made some big changes on the team name matching and user based filtering of leagues and match types (Under 17's, women etc)

Will only take a little work so let me know if there is any interest and will try and do it over the Xmas break.
User avatar
Euler
Posts: 24804
Joined: Wed Nov 10, 2010 1:39 pm
Location: Bet Angel HQ

I've got a lot of value out of your scripting. It opened up a little avenue I hadn't explored. So please update as and when.
Wonkymuffin
Posts: 6
Joined: Wed Nov 09, 2016 8:46 am

I am still interested in pursuing this route for using live data to assist in automation decision making so would be interested in your updates when possible.
sniffer66
Posts: 1679
Joined: Thu May 02, 2019 8:37 am

Cheers pater/Wonky. Will get on it as soon as I get a chance - just been diagnosed with Covid though so may be a little while yet.
Post Reply

Return to “Football trading”