This repository has been archived by the owner on Apr 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util_pinnacle.py
408 lines (380 loc) · 20.3 KB
/
util_pinnacle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import requests
import utils
import proxy_worker
import exceptions
import datetime
import sys
import traceback
import time
import json
import sys
import traceback
list_matches_head = {
'accept': 'application/json',
'content-type': 'application/json',
# 'origin': 'https://www.pinnacle.com',
# 'referer': 'https://www.pinnacle.com',
# 'sec-fetch-mode': 'cors',
# 'sec-fetch-site': 'same-site',
'user-agent': 'Mozilla/5.0 (WindoWs nt 10.0; wiN64; X64) applewebkiT/537.36 (khTml, liKe gecko) chrome/78.0.3904.108 safari/537.36',
}
url_live = 'https://api.arcadia.pinnacle.com/0.1/sports/{}/matchups/live'
url_pre = 'https://api.arcadia.pinnacle.com/0.1/sports/{}/matchups'
head_odds = {
'accept': 'application/json',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'ru,en;q=0.9,mg;q=0.8,cy;q=0.7',
'cache-control': 'no-cache',
'content-type': 'application/json',
# 'origin': 'https://www.pinnacle.com',
# 'referer': 'https://www.pinnacle.com/en/',
# 'sec-fetch-mode': 'cors',
# 'sec-fetch-site': 'same-site',
'user-agent': 'Mozilla/5.0 (WindoWs nt 10.0; wiN64; X64) applewebkiT/537.36 (khTml, liKe gecko) chrome/78.0.3904.108 safari/537.36',
}
url_live_odds = 'https://api.arcadia.pinnacle.com/0.1/sports/{}/markets/live/straight?primaryOnly=false'
url_pre_odds = 'https://api.arcadia.pinnacle.com/0.1/sports/{}/markets/straight?primaryOnly=false'
x_device_uuid_temp = 'f46d6637-4581a07c-36898a69-87694cf6'
# x_session = '8rnHMqfFTy5osJ59q9vytaWgGytFiW0v'
# api_key = requests.get(
# url='https://www.pinnacle.com/config/app.json',
# verify=False,
# timeout=10,
# ).json()['api']['haywire']['apiKey']
def american_to_decimal(odd, status):
if status != 'open':
return 0
if odd:
if odd > 0:
return round((odd / 100) + 1, 3)
elif odd < 0:
return round(100 / abs(odd) + 1, 3)
else:
return 0
else:
return None
def straight_normalize(data):
def designations(d: str):
if d == 'over':
return 'Б'
elif d == 'under':
return 'М'
elif d == 'home':
return '1'
elif d == 'away':
return '2'
elif d == 'draw':
return 'Н'
else:
return ''
def periods(p: str):
try:
p = int(p)
return str(p)
except:
return ''
def types(t: str):
if 'total' in t:
return 'Т'
elif t == 'spread':
return 'Ф'
else:
return ''
def sides(s: str):
if s == 'home':
return '1'
elif s == 'away':
return '2'
else:
''
norm_designations = lambda x: x if x == 'Н' else 'П' + x
def norm_periods(p: str):
if p:
if str(p) == '0':
return ''
else:
return str(p)
else:
return ''
def norm_total(t: str):
if t in ('(-0.0)', '(0.0)'):
return '(0)'
else:
return t
unit = 'У' if data.get('units', '') == 'Corners' else ''
# print('period:{}, type:{}, designation:{}, side:{}, points:{}, unit:{}'.format(data.get('period', ''), data.get('type'), data.get('designation'), data.get('side'), data.get('points'), unit))
try:
if data.get('type', '') == 'team_total':
return {norm_periods(data.get('period', '')) + unit + types(data.get('type', '')) + designations(data.get('designation', '')) + sides(data.get('side')) + '({})'.format(data.get('points')).replace('+', ''): data}
if data.get('type', '') == 'total':
return {norm_periods(data.get('period', '')) + unit + types(data.get('type', '')) + designations(data.get('designation', '')) + '({})'.format(data.get('points')).replace('+', ''): data}
if data.get('type', '') == 'moneyline':
return {unit + norm_designations(designations(data.get('designation', ''))): data}
if data.get('type', '') == 'spread':
return {norm_periods(data.get('period', '')) + unit + types(data.get('type', '')) + designations(data.get('designation', '')) + '({})'.format(
str(data.get('points', '')) if data.get('points') >= 0 != '-' else data.get('points')).replace('+', ''): data}
else:
return {}
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
print('Error straight_normalize: ' + str(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) + '\ndata:' + str(data.get('bet', '')) + '\n\n')
return {'error': str(e)}
def get_matches(bk_name, proxy, timeout, api_key, x_session, x_device_uuid, proxy_list, session, place):
if bk_name == 'pinnacle':
head = list_matches_head
if api_key:
head.update({'x-api-key': api_key})
if x_device_uuid:
head.update({'x-device-uuid': x_device_uuid})
if x_session:
head.update({'x-session': x_session})
if 'live' == place:
url = url_live
else:
url = url_pre
proxies = {'https': proxy}
data = {}
resp = {}
for sport in utils.sport_list:
sport_id = sport.get('pinnacle')
sport_name = sport.get('name')
if utils.if_exists_by_sport(utils.sport_list, bk_name, sport_id, 'place', place):
if sport_id:
try:
if session:
sx = session.get
else:
sx = requests.get
# utils.prnts('session get_matches: ' + str(session))
resp = sx(
url.format(sport_id),
headers=head,
timeout=timeout,
verify=False,
proxies=proxies,
)
try:
res = resp.json()
check_data(res, sport_id, place, api_key)
# {'detail': 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.', 'status': 404, 'title': 'Not Found', 'type': 'about:blank'}
# print(json.dumps(res))
# print('---')
res_status = 200
if type(res) != list:
res_status = res.get('status', 404)
if res_status != 200:
err_str = bk_name + ' ' + url.format(sport_id) + ' ' + 'error, res_status: ' + str(res_status) + ', res: ' + str(res.text)
utils.prnts(err_str)
pass
else:
for l in filter(
lambda x: (
x.get('league', {}).get('sport', {}).get('name', '') != 'Hockey' and x.get('liveMode', '') == 'live_delay'
and x.get('units', '') == 'Regular' # разкомментить для удаления угловых
and (x.get('parent') if x.get('parent') else {}).get('participants', [{}])[0].get('name', '') == x.get('participants', [{}])[0].get('name', '')
# закомментить для добавления сетов и геймов
) or (x.get('league', {}).get('sport', {}).get('name', '') == 'Hockey'),
res):
if str(l.get('id')) in '1102576922':
print(json.dumps(l))
# if place == 'pre':
# print(l)
# {'ageLimit': 0, 'altTeaser': False, 'external': {}, 'hasLive': True, 'hasMarkets': True, 'id': 1094249412, 'isHighlighted': False, 'isLive': True, 'isPromoted': False,
# 'league': {'ageLimit': 0, 'external': {}, 'featureOrder': -1, 'group': 'World', 'id': 1863, 'isFeatured': False, 'isHidden': False, 'isPromoted': False, 'isSticky': False,
# 'matchupCount': 3, 'name': 'Club Friendlies', 'sport': {'featureOrder': 0, 'id': 29, 'isFeatured': True, 'isHidden': False, 'isSticky': False, 'matchupCount': 532,
# 'name': 'Soccer', 'primaryMarketType': 'moneyline'}}, 'liveMode': 'live_delay', 'parent': {'id': 1094249362, 'participants': [{'alignment': 'home', 'name': 'Club Sport Emelec', 'score': None},
# {'alignment': 'away', 'name': 'LDU de Portoviejo', 'score': None}], 'startTime': '2020-01-31T01:30:00+00:00'}, 'parentId': 1094249362, 'parlayRestriction': 'unique_matchups', 'participants':
# [{'alignment': 'home', 'name': 'Club Sport Emelec', 'order': 0, 'state': {'score': 2}}, {'alignment': 'away', 'name': 'LDU de Portoviejo', 'order': 1, 'state': {'score': 0}}],
# 'periods': [{'cutoffAt': '2020-01-31T04:14:42Z', 'period': 0, 'status': 'open'}, {'cutoffAt': None, 'period': 1, 'status': 'settled'}], 'rotation': 1301, 'startTime': '2020-01-31T01:30:00Z',
# 'state': {'minutes': 39, 'state': 3}, 'status': 'started', 'totalMarketCount': 2, 'type': 'matchup', 'units': 'Regular', 'version': 256440882}
participants = l.get('participants', [{}])
participant_0 = participants[0]
participant_1 = participants[1]
# TODO witout home/ away
# [{'alignment': 'neutral', 'id': 1103553309, 'name': 'Over', 'order': 0, 'rotation': 16}, {'alignment': 'neutral', 'id': 1103553310, 'name': 'Under', 'order': 0, 'rotation': 17}]
if participant_0.get('alignment') in ('home', 'away'):
if participant_0.get('alignment') == 'home':
team1 = participant_0.get('name')
team2 = participant_1.get('name')
score1 = participant_0.get('state', {}).get('score', participant_0.get('score', ''))
score2 = participant_1.get('state', {}).get('score', participant_1.get('score', ''))
elif participant_0.get('alignment') == 'away':
team2 = participant_0.get('name')
team1 = participant_1.get('name')
score2 = participant_0.get('state', {}).get('score', participant_0.get('score', ''))
score1 = participant_1.get('state', {}).get('score', participant_1.get('score', ''))
data[l.get('id')] = {
'time_req': round(time.time()),
'place': place,
'bk_name': bk_name,
'match_id': l.get('id'),
'league': l.get('league', {}).get('group') + '-' + l.get('league', {}).get('name'),
'team1': team1,
'team2': team2,
'name': team1 + '-' + team2,
'score': str(score1) + ':' + str(score2),
'state': l.get('state', {}).get('state'),
'minute': float(l.get('state', {}).get('minutes', 0)),
'sport_id': sport_id,
'sport_name': sport_name,
'start_time': int(datetime.datetime.strptime(l.get('startTime'), '%Y-%m-%dT%H:%M:%SZ').timestamp()),
'units': l.get('units'),
'liveMode': l.get('liveMode')
}
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
err_str = bk_name + ' ' + url.format(sport_id) + ' ' + 'error: ' + str(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
if resp:
err_str + '\ndata:' + resp.text
utils.prnts(err_str)
raise ValueError('Exception: ' + str(e))
if resp.status_code != 200:
err_str = res.get("error")
err_str = bk_name + ' ' + url.format(sport_id) + ' ' + 'error : ' + str(err_str)
utils.prnts(err_str)
raise ValueError(str(err_str))
except requests.exceptions.Timeout as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
err_str = bk_name + ' ' + url.format(sport_id) + ' ' + 'error: ' + str(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
utils.prnts(err_str)
proxies = proxy_worker.del_proxy(proxy, proxy_list)
raise exceptions.TimeOut(err_str)
except requests.exceptions.ConnectionError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
err_str = bk_name + ' ' + url.format(sport_id) + ' ' + 'error: ' + str(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
utils.prnts(err_str)
proxies = proxy_worker.del_proxy(proxy, proxy_list)
raise ValueError(err_str)
except requests.exceptions.RequestException as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
err_str = bk_name + ' ' + url.format(sport_id) + ' ' + 'error: ' + str(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
utils.prnts(err_str)
proxies = proxy_worker.del_proxy(proxy, proxy_list)
raise ValueError(err_str)
except ValueError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
err_str = bk_name + ' ' + url.format(sport_id) + ' ' + 'error1: ' + str(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
utils.prnts(err_str)
proxi_list = proxy_worker.del_proxy(proxy, proxy_list)
raise ValueError(err_str)
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
err_str = bk_name + ' ' + url.format(sport_id) + ' ' + 'error: ' + str(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
utils.prnts(err_str)
proxies = proxy_worker.del_proxy(proxy, proxy_list)
raise ValueError(err_str)
return data, resp.elapsed.total_seconds()
if not data:
return {}, 0
MAX_VERSION = {}
def check_data(data, sport_id, place, api_key):
if type(data) == dict and data.get('status'):
utils.prnts('data: ' + str(data))
title_err = data.get('title')
if title_err == 'BAD_APIKEY':
utils.prnts('api_key: ' + str(api_key))
elif title_err == 'AUTH_SUPERSEDED':
utils.prnts('Session expired! TODO: relogin')
else:
utils.prnts('error data: ' + place + ' ' + str(sport_id) + ' ' + str(data), hide=True)
def get_odds(bets, api_key, x_session, x_device_uuid, pair_mathes, sport_id, proxi_list, proxy, timeout, arr_matchs, session, place):
global MAX_VERSION
match_id_list = []
bk_mame = 'pinnacle'
for pair_math in pair_mathes:
bk_name1 = pair_math[-2]
match_id1 = pair_math[0]
bk_name2 = pair_math[-1]
match_id2 = pair_math[1]
if bk_name1 == bk_mame and match_id1 not in match_id_list:
match_id_list.append(match_id1)
elif bk_name2 == bk_mame and match_id2 not in match_id_list:
match_id_list.append(match_id2)
# print('match_id_list: ' + str(match_id_list))
# head = head_odds
head = list_matches_head
if api_key:
pass
head.update({'x-api-key': api_key})
if x_device_uuid:
pass
head.update({'x-device-uuid': x_device_uuid})
if x_session:
pass
head.update({'x-session': x_session})
if 'live' == place:
url = url_live_odds
else:
url = url_pre_odds
proxies = {'https': proxy}
data = {}
# print('get_odds head: ' + str(head))
if session:
xs = session.get
else:
xs = requests.get
# utils.prnts('session get_odds: ' + str(session))
resp = xs(
url.format(sport_id),
# 'http://192.168.1.143:8888/',
headers=head,
timeout=timeout,
verify=False,
proxies=proxies,
)
data = resp.json()
# {'detail': 'API key is not valid', 'status': 403, 'title': 'BAD_APIKEY', 'type': 'about:blank'}
# {'detail': 'Session superseded by a login on another device', 'status': 401, 'title': 'AUTH_SUPERSEDED', 'type': 'about:blank'} -- SESSION EXPIRED
# {"detail": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.", "status": 404, "title": "Not Found", "type": "about:blank"}
check_data(data, sport_id, place, api_key)
for match_id in match_id_list:
check_vertion = False # vershion check need by kof
res = {}
version = None
# print('match_id: ' + str(match_id))
for bet in filter(lambda x: str(x.get('matchupId')) == str(match_id), data):
version = bet.get('version', -1)
# if str(match_id) == '1096611547':
# print(json.dumps(bet))
if (check_vertion and version > MAX_VERSION.get(str(sport_id), 0)) or not check_vertion:
MAX_VERSION.update({str(sport_id): version})
for price in bet.get('prices', []):
status = bet.get('status')
# if status == 'open':
# v_kof = str(price.get('price')) + ' -> ' + str(american_to_decimal(price.get('price'), status))
v_kof = float(american_to_decimal(price.get('price'), status))
# else:
# v_kof = 0
res.update(straight_normalize({
'bk_name': 'pinnacle',
'time_req': round(time.time()),
'match_id': match_id,
# 'name': arr_matchs.get(match_id, {}).get('name', ''),
'type': bet.get('type'),
'status': status,
'side': bet.get('side'),
'period': bet.get('period'),
'designation': price.get('designation'),
'points': price.get('points'),
'value': v_kof,
'version': version,
'bet': bet
# 'units':res[match_id]['units'], Нужно для угловых - они отключены
# 'vector':'UP' if price.get('price') > 0 else 'DOWN'
}))
# print('res: ' + str(res))
if version and check_vertion:
if version < MAX_VERSION.get(str(sport_id), 0):
print('sport_id:{}, get version is old: {}, max:{}'.format(sport_id, version, MAX_VERSION.get(str(sport_id), 0)))
if not bets.get(str(match_id)):
bets[str(match_id)] = {}
# bets[str(match_id)]['time_req'] = round(time.time())
if res:
bets[str(match_id)]['kofs'] = res
if arr_matchs.get(match_id, {}):
bets[str(match_id)].update(arr_matchs.get(match_id, {}))
bets[str(match_id)]['kofs'] = res
# print(bets)
# time.sleep(5)
# print('----')
return resp.elapsed.total_seconds()