forked from harveysburger/pinnaclewrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPinnacleClient.cs
357 lines (275 loc) · 13.7 KB
/
PinnacleClient.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PinnacleWrapper.Data;
using PinnacleWrapper.Enums;
namespace PinnacleWrapper
{
public class PinnacleClient
{
private HttpClient _httpClient;
private string _clientId;
private string _password;
public string CurrencyCode { get; private set; }
public OddsFormat OddsFormat { get; private set; }
private const int MinimumFeedRefreshWithLast = 5; // minimum time in seconds between calls when supplying the last timestamp parameter
private const int MinimumFeedRefresh = 60; // minimum time in seconds between calls without last timestamp parameter
private DateTime? _lastFeedRequest;
private const string BaseAddress = "https://api.pinnaclesports.com/v1/";
public PinnacleClient(string clientId, string password, string currencyCode, OddsFormat oddsFormat)
{
_clientId = clientId;
_password = password;
CurrencyCode = currencyCode;
OddsFormat = oddsFormat;
_httpClient = new HttpClient {BaseAddress = new Uri(BaseAddress)};
// put auth header into httpclient
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
Encoding.ASCII.GetBytes(string.Format("{0}:{1}", _clientId, _password))));
}
protected async Task<T> GetXmlAsync<T>(string requestType, params object[] values)
where T : XmlResponse
{
var response = await _httpClient.GetAsync(string.Format(requestType, values)).ConfigureAwait(false);
//var str = _httpClient.GetStringAsync(string.Format(requestType, values)).Result;
response.EnsureSuccessStatusCode(); // throw if web request failed
var xmlFormatter = new XmlMediaTypeFormatter { UseXmlSerializer = true };
var apiResponse = await response.Content.ReadAsAsync<T>(new[] {xmlFormatter});
if (apiResponse.IsValid)
{
return apiResponse;
}
throw new Exception("Pinnacle Sports API error: " + apiResponse.Error.Message);
}
public async Task<List<Sport>> GetSports()
{
return (await GetXmlAsync<SportsResponse>("sports")).Sports;
}
public async Task<List<League>> GetLeagues(int sportId)
{
return (await GetXmlAsync<LeaguesResponse>("leagues?sportid={0}", sportId)).Leagues;
}
public async Task<List<Currency>> GetCurrencies()
{
return (await GetXmlAsync<CurrenciesResponse>("currencies")).Currencies;
}
#region GetFeed
protected string GetFeedRequestUri(int sportId, int[] leagueId, OddsFormat format, string currency, long lastTimestamp, int isLive)
{
var sb = new StringBuilder();
sb.AppendFormat("feed?sportid={0}", sportId);
if (leagueId.Length > 0)
sb.AppendFormat("&leagueid={0}", string.Join("-", leagueId));
sb.AppendFormat("&oddsformat={0}", (int)format);
sb.AppendFormat("¤cycode={0}", currency);
if (lastTimestamp > 0)
{
sb.AppendFormat("&last={0}", lastTimestamp);
}
if (isLive == 0 || isLive == 1)
{
sb.AppendFormat("&islive={0}", isLive);
}
return sb.ToString();
}
protected bool IsFairFeedRequest(long lastTimestamp)
{
if (_lastFeedRequest.HasValue)
{
var minRequestInterval = (lastTimestamp > 0 ? MinimumFeedRefreshWithLast : MinimumFeedRefresh);
var interval = DateTime.Now - _lastFeedRequest.Value;
if (interval.TotalSeconds < minRequestInterval)
{
return false;
}
}
return true;
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
protected async Task<Feed> GetFeed(int sportId, int[] leagueIds, OddsFormat format, string currency, long lastTimestamp, int isLive)
{
//if (!IsFairFeedRequest(lastTimestamp))
// throw new Exception(
// string.Format(
// "Too many feed requests. Minimum interval time between request is {0} seconds or {1} seconds when specifying the last parameter",
// MinimumFeedRefresh,
// MinimumFeedRefreshWithLast));
_lastFeedRequest = DateTime.Now;
var uri = GetFeedRequestUri(sportId, leagueIds, format, currency, lastTimestamp, isLive);
return (await GetXmlAsync<FeedResponse>(uri)).Feed;
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
public async Task<Feed> GetFeed(int sportId)
{
return await GetFeed(sportId, new int[]{}, OddsFormat, CurrencyCode, -1, -1);
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
public async Task<Feed> GetFeed(int sportId, long lastTimestamp)
{
return await GetFeed(sportId, new int[] { }, OddsFormat, CurrencyCode, lastTimestamp);
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
public async Task<Feed> GetFeed(int sportId, int[] leagueIds)
{
return await GetFeed(sportId, leagueIds, OddsFormat, CurrencyCode, -1, -1);
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
public async Task<Feed> GetFeed(int sportId, int[] leagueIds, long lastTimestamp)
{
return await GetFeed(sportId, leagueIds, OddsFormat, CurrencyCode, lastTimestamp, -1);
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
public async Task<Feed> GetFeed(int sportId, int[] leagueIds, OddsFormat format, string currency)
{
return await GetFeed(sportId, leagueIds, format, currency, -1, -1);
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
public async Task<Feed> GetFeed(int sportId, int[] leagueIds, OddsFormat format, string currency, bool isLive)
{
return await GetFeed(sportId, leagueIds, format, currency, -1, isLive ? 1 : 0);
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
public async Task<Feed> GetFeed(int sportId, int[] leagueIds, OddsFormat format, string currency, long lastTimestamp)
{
return await GetFeed(sportId, leagueIds, format, currency, lastTimestamp, -1);
}
[Obsolete("GetFeed is Deprecated, please use GetOdds and GetFixtures")]
public async Task<Feed> GetFeed(int sportId, int[] leagueIds, OddsFormat format, string currency, long lastTimestamp, bool isLive)
{
return await GetFeed(sportId, leagueIds, format, currency, lastTimestamp, isLive ? 1 : 0);
}
#endregion
protected async Task<T> GetJsonAsync<T>(string requestType, params object[] values)
{
var response = await _httpClient.GetAsync(string.Format(requestType, values)).ConfigureAwait(false);
response.EnsureSuccessStatusCode(); // throw if web request failed
var json = await response.Content.ReadAsStringAsync();
// deserialise json async
return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(json));
}
// ToDo: replace requestData object type with "IJsonSerialisable"
protected async Task<T> PostJsonAsync<T>(string requestType, object requestData)
{
var requestPostData = JsonConvert.SerializeObject(requestData);
var response = await _httpClient.PostAsync(requestType,
new StringContent(requestPostData, Encoding.UTF8, "application/json")).ConfigureAwait(false);
response.EnsureSuccessStatusCode(); // throw if web request failed
var json = await response.Content.ReadAsStringAsync();
// deserialise async
return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(json));
}
public Task<ClientBalance> GetClientBalance()
{
const string uri = "client/balance";
return GetJsonAsync<ClientBalance>(uri);
}
public Task<GetBetsResponse> GetBets(BetListType type, DateTime startDate, DateTime endDate)
{
// get request uri
var sb = new StringBuilder();
sb.AppendFormat("bets?betlist={0}", type.ToString().ToLower());
sb.AppendFormat("&fromDate={0}", startDate.ToString("yyyy-MM-dd"));
sb.AppendFormat("&toDate={0}", endDate.ToString("yyyy-MM-dd"));
var uri = sb.ToString();
return GetJsonAsync<GetBetsResponse>(uri);
}
public Task<GetBetsResponse> GetBets(List<int> betIds)
{
// get request uri
var sb = new StringBuilder();
sb.AppendFormat("bets?betids={0}", string.Join(",", betIds));
var uri = sb.ToString();
return GetJsonAsync<GetBetsResponse>(uri);
}
public Task<PlaceBetResponse> PlaceBet(PlaceBetRequest placeBetRequest)
{
return PostJsonAsync<PlaceBetResponse>("bets/place", placeBetRequest);
}
/// <summary>
///
/// </summary>
/// <param name="sportId"></param>
/// <param name="leagueId"></param>
/// <param name="eventId"></param>
/// <param name="periodNumber">0 for sports other than soccer, soccer: 0 = Game, 1 = 1st Half, 2 = 2nd Half</param>
/// <param name="betType"></param>
/// <param name="oddsFormat"></param>
/// <param name="team"></param>
/// <param name="side"></param>
/// <param name="handicap"></param>
/// <returns></returns>
public Task<GetLineResponse> GetLine(int sportId, int leagueId, long eventId, int periodNumber, BetType betType, OddsFormat oddsFormat,
TeamType? team = null, SideType? side = null, decimal? handicap = null)
{
if (team == null)
{
if (betType == BetType.MoneyLine || betType == BetType.Spread || betType == BetType.TeamTotalPoints)
throw new Exception(string.Format("TeamType is required for {0} Bets!", betType));
}
if (side == null)
{
if (betType == BetType.TotalPoints || betType == BetType.TeamTotalPoints)
throw new Exception(string.Format("SideType is required for {0} Bets!", betType));
}
if (handicap == null)
{
if (betType == BetType.Spread || betType == BetType.TotalPoints || betType == BetType.TeamTotalPoints)
throw new Exception(string.Format("Handicap is required for {0} Bets!", betType));
}
// get request uri
var sb = new StringBuilder();
sb.AppendFormat("line?sportId={0}", sportId);
sb.AppendFormat("&leagueId={0}", leagueId);
sb.AppendFormat("&eventId={0}", eventId);
sb.AppendFormat("&betType={0}", betType.ToString().ToUpper());
sb.AppendFormat("&oddsFormat={0}", oddsFormat.ToString().ToUpper());
sb.AppendFormat("&periodNumber={0}", periodNumber); // i.e. for soccer: 0 = Game, 1 = 1st Half, 2 = 2nd Half
if (team != null)
sb.AppendFormat("&team={0}", team.ToString().ToUpper());
if (side != null)
sb.AppendFormat("&side={0}", side.ToString().ToUpper());
if (handicap != null)
sb.AppendFormat("&handicap={0}", handicap.ToString().ToUpper());
var uri = sb.ToString();
return GetJsonAsync<GetLineResponse>(uri);
}
public Task<GetInRunningResponse> GetInRunning()
{
const string uri = "inrunning";
return GetJsonAsync<GetInRunningResponse>(uri);
}
public Task<GetFixturesResponse> GetFixtures(GetFixturesRequest request)
{
var sb = new StringBuilder();
sb.AppendFormat("fixtures?sportId={0}", request.SportId);
if (request.LeagueIds != null && request.LeagueIds.Any())
sb.AppendFormat("&leagueIds={0}", string.Join(",", request.LeagueIds));
if (request.Since > 0)
sb.AppendFormat("&since={0}", request.Since);
if (request.IsLive)
sb.AppendFormat("&IsLive={0}", 1);
return GetJsonAsync<GetFixturesResponse>(sb.ToString());
}
public Task<GetOddsResponse> GetOdds(GetOddsRequest request)
{
var sb = new StringBuilder();
sb.AppendFormat("odds?sportId={0}", request.SportId);
if (request.LeagueIds != null && request.LeagueIds.Any())
sb.AppendFormat("&leagueIds={0}", string.Join(",", request.LeagueIds));
if (request.Since > 0)
sb.AppendFormat("&since={0}", request.Since);
if (request.IsLive)
sb.AppendFormat("&IsLive={0}", 1);
sb.AppendFormat("&oddsFormat={0}", OddsFormat);
sb.AppendFormat("¤cycode={0}", CurrencyCode);
return GetJsonAsync<GetOddsResponse>(sb.ToString());
}
}
}