forked from joelpob/betfairng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BetfairClient.cs
485 lines (427 loc) · 21.4 KB
/
BetfairClient.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
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BetfairNG.Data;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
namespace BetfairNG
{
/// <summary>
/// Task Parallel Library version of BetfairClient API.
/// </summary>
public class BetfairClient
{
private Network networkClient;
private string appKey;
private string sessionToken;
private Action preNetworkRequest;
private WebProxy proxy;
private static TraceSource trace = new TraceSource("BetfairClient");
private static readonly string LIST_COMPETITIONS_METHOD = "SportsAPING/v1.0/listCompetitions";
private static readonly string LIST_COUNTRIES_METHOD = "SportsAPING/v1.0/listCountries";
private static readonly string LIST_CURRENT_ORDERS_METHOD = "SportsAPING/v1.0/listCurrentOrders";
private static readonly string LIST_CLEARED_ORDERS_METHOD = "SportsAPING/v1.0/listClearedOrders";
private static readonly string LIST_EVENT_TYPES_METHOD = "SportsAPING/v1.0/listEventTypes";
private static readonly string LIST_EVENTS_METHOD = "SportsAPING/v1.0/listEvents";
private static readonly string LIST_MARKET_CATALOGUE_METHOD = "SportsAPING/v1.0/listMarketCatalogue";
private static readonly string LIST_MARKET_BOOK_METHOD = "SportsAPING/v1.0/listMarketBook";
private static readonly string LIST_MARKET_PROFIT_AND_LOSS = "SportsAPING/v1.0/listMarketProfitAndLoss";
private static readonly string LIST_MARKET_TYPES = "SportsAPING/v1.0/listMarketTypes";
private static readonly string LIST_TIME_RANGES = "SportsAPING/v1.0/listTimeRanges";
private static readonly string LIST_VENUES = "SportsAPING/v1.0/listVenues";
private static readonly string PLACE_ORDERS_METHOD = "SportsAPING/v1.0/placeOrders";
private static readonly string CANCEL_ORDERS_METHOD = "SportsAPING/v1.0/cancelOrders";
private static readonly string REPLACE_ORDERS_METHOD = "SportsAPING/v1.0/replaceOrders";
private static readonly string UPDATE_ORDERS_METHOD = "SportsAPING/v1.0/updateOrders";
private static readonly string GET_ACCOUNT_DETAILS = "AccountAPING/v1.0/getAccountDetails";
private static readonly string GET_ACCOUNT_FUNDS = "AccountAPING/v1.0/getAccountFunds";
private static readonly string GET_ACCOUNT_STATEMENT = "AccountAPING/v1.0/getAccountStatement";
private static readonly string LIST_CURRENCY_RATES = "AccountAPING/v1.0/listCurrencyRates";
private static readonly string TRANSFER_FUNDS = "AccountAPING/v1.0/transferFunds";
private static readonly string LIST_RACE_DETAILS = "ScoresAPING/v1.0/listRaceDetails";
private static readonly string FILTER = "filter";
private static readonly string BET_IDS = "betIds";
private static readonly string RUNNER_IDS = "runnerIds";
private static readonly string SIDE = "side";
private static readonly string SETTLED_DATE_RANGE = "settledDateRange";
private static readonly string EVENT_TYPE_IDS = "eventTypeIds";
private static readonly string EVENT_IDS = "eventIds";
private static readonly string BET_STATUS = "betStatus";
private static readonly string PLACED_DATE_RANGE = "placedDateRange";
private static readonly string DATE_RANGE = "dateRange";
private static readonly string ORDER_BY = "orderBy";
private static readonly string GROUP_BY = "groupBy";
private static readonly string SORT_DIR = "sortDir";
private static readonly string FROM_RECORD = "fromRecord";
private static readonly string RECORD_COUNT = "recordCount";
private static readonly string GRANULARITY = "granularity";
private static readonly string MARKET_PROJECTION = "marketProjection";
private static readonly string MATCH_PROJECTION = "matchProjection";
private static readonly string ORDER_PROJECTION = "orderProjection";
private static readonly string PRICE_PROJECTION = "priceProjection";
private static readonly string SORT = "sort";
private static readonly string MAX_RESULTS = "maxResults";
private static readonly string MARKET_IDS = "marketIds";
private static readonly string MARKET_ID = "marketId";
private static readonly string INSTRUCTIONS = "instructions";
private static readonly string CUSTOMER_REFERENCE = "customerRef";
private static readonly string INCLUDE_SETTLED_BETS = "includeSettledBets";
private static readonly string INCLUDE_BSP_BETS = "includeBspBets";
private static readonly string INCLUDE_ITEM_DESCRIPTION = "includeItemDescription";
private static readonly string NET_OF_COMMISSION = "netOfCommission";
private static readonly string FROM_CURRENCY = "fromCurrency";
private static readonly string FROM = "from";
private static readonly string TO = "to";
private static readonly string AMOUNT = "amount";
private static readonly string WALLET = "wallet";
private static readonly string MARKET_VERSION = "marketVersion";
private static readonly string MEETINGIDS = "meetingIds";
private static readonly string RACEIDS = "raceIds";
public BetfairClient(string appKey, Action preNetworkRequest = null, WebProxy proxy = null)
{
if (string.IsNullOrWhiteSpace(appKey)) throw new ArgumentException("appKey");
this.appKey = appKey;
this.preNetworkRequest = preNetworkRequest;
this.proxy = proxy;
}
public BetfairClient(string appKey,
string sessionToken,
Action preNetworkRequest = null,
WebProxy proxy = null)
{
if (string.IsNullOrWhiteSpace(appKey)) throw new ArgumentException("appKey");
if (string.IsNullOrWhiteSpace(sessionToken)) throw new ArgumentException("sessionToken");
this.appKey = appKey;
this.sessionToken = sessionToken;
this.preNetworkRequest = preNetworkRequest;
this.proxy = proxy;
this.networkClient = new Network(this.appKey, this.sessionToken, this.preNetworkRequest, true, this.proxy);
}
public bool Login(string p12CertificateLocation,
string p12CertificatePassword,
string username,
string password,
string loginUrl="https://identitysso-cert.betfair.com/api/certlogin")
{
if (string.IsNullOrWhiteSpace(p12CertificateLocation)) throw new ArgumentException("p12CertificateLocation");
if (string.IsNullOrWhiteSpace(p12CertificatePassword)) throw new ArgumentException("p12CertificatePassword");
if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("username");
if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("password");
if (!File.Exists(p12CertificateLocation)) throw new ArgumentException("p12CertificateLocation not found");
if (preNetworkRequest != null)
preNetworkRequest();
string postData = string.Format("username={0}&password={1}", username, password);
X509Certificate2 x509certificate = new X509Certificate2(p12CertificateLocation, p12CertificatePassword);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
request.UseDefaultCredentials = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-Application", appKey);
request.ClientCertificates.Add(x509certificate);
request.Accept = "*/*";
if (this.proxy != null)
request.Proxy = this.proxy;
using (Stream stream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(stream, Encoding.Default))
{
writer.Write(postData);
}
using (Stream stream = ((HttpWebResponse)request.GetResponse()).GetResponseStream())
using (StreamReader reader = new StreamReader(stream, Encoding.Default))
{
var jsonResponse = JsonConvert.Deserialize<LoginResponse>(reader.ReadToEnd());
if (jsonResponse.LoginStatus == "SUCCESS")
{
this.sessionToken = jsonResponse.SessionToken;
this.networkClient = new Network(appKey, this.sessionToken, this.preNetworkRequest);
return true;
}
else
return false;
}
}
public BetfairServerResponse<KeepAliveResponse> KeepAlive()
{
return networkClient.KeepAliveSynchronous();
}
public Task<BetfairServerResponse<List<CompetitionResult>>> ListCompetitions(MarketFilter marketFilter)
{
var args = new Dictionary<string, object>();
args[FILTER] = marketFilter;
return networkClient.Invoke<List<CompetitionResult>>(Endpoint.Betting, LIST_COMPETITIONS_METHOD, args);
}
public Task<BetfairServerResponse<List<CountryCodeResult>>> ListCountries(MarketFilter marketFilter)
{
var args = new Dictionary<string, object>();
args[FILTER] = marketFilter;
return networkClient.Invoke<List<CountryCodeResult>>(Endpoint.Betting, LIST_COUNTRIES_METHOD, args);
}
public Task<BetfairServerResponse<CurrentOrderSummaryReport>> ListCurrentOrders(
ISet<string> betIds = null,
ISet<string> marketIds = null,
OrderProjection? orderProjection = null,
TimeRange placedDateRange = null,
TimeRange dateRange = null,
OrderBy? orderBy = null,
SortDir? sortDir = null,
int? fromRecord = null,
int? recordCount = null)
{
var args = new Dictionary<string, object>();
args[BET_IDS] = betIds;
args[MARKET_IDS] = marketIds;
args[ORDER_PROJECTION] = orderProjection;
args[PLACED_DATE_RANGE] = placedDateRange;
args[DATE_RANGE] = dateRange;
args[ORDER_BY] = orderBy;
args[SORT_DIR] = sortDir;
args[FROM_RECORD] = fromRecord;
args[RECORD_COUNT] = recordCount;
return networkClient.Invoke<CurrentOrderSummaryReport>(Endpoint.Betting, LIST_CURRENT_ORDERS_METHOD, args);
}
public Task<BetfairServerResponse<ClearedOrderSummaryReport>> ListClearedOrders(
BetStatus betStatus,
ISet<string> eventTypeIds = null,
ISet<string> eventIds = null,
ISet<string> marketIds = null,
ISet<RunnerId> runnerIds = null,
ISet<string> betIds = null,
Side? side = null,
TimeRange settledDateRange = null,
GroupBy? groupBy = null,
bool? includeItemDescription = null,
int? fromRecord = null,
int? recordCount = null)
{
var args = new Dictionary<string, object>();
args[BET_STATUS] = betStatus;
args[EVENT_TYPE_IDS] = eventTypeIds;
args[EVENT_IDS] = eventIds;
args[MARKET_IDS] = marketIds;
args[RUNNER_IDS] = runnerIds;
args[BET_IDS] = betIds;
args[SIDE] = side;
args[SETTLED_DATE_RANGE] = settledDateRange;
args[GROUP_BY] = groupBy;
args[INCLUDE_ITEM_DESCRIPTION] = includeItemDescription;
args[FROM_RECORD] = fromRecord;
args[RECORD_COUNT] = recordCount;
return networkClient.Invoke<ClearedOrderSummaryReport>(Endpoint.Betting, LIST_CLEARED_ORDERS_METHOD, args);
}
public Task<BetfairServerResponse<List<EventResult>>> ListEvents(MarketFilter marketFilter)
{
var args = new Dictionary<string, object>();
args[FILTER] = marketFilter;
return networkClient.Invoke<List<EventResult>>(Endpoint.Betting, LIST_EVENTS_METHOD, args);
}
public Task<BetfairServerResponse<List<EventTypeResult>>> ListEventTypes(MarketFilter marketFilter)
{
var args = new Dictionary<string, object>();
args[FILTER] = marketFilter;
return networkClient.Invoke<List<EventTypeResult>>(Endpoint.Betting, LIST_EVENT_TYPES_METHOD, args);
}
public Task<BetfairServerResponse<List<MarketBook>>> ListMarketBook(
IEnumerable<string> marketIds,
PriceProjection priceProjection = null,
OrderProjection? orderProjection = null,
MatchProjection? matchProjection = null)
{
var args = new Dictionary<string, object>();
args[MARKET_IDS] = marketIds;
args[PRICE_PROJECTION] = priceProjection;
args[ORDER_PROJECTION] = orderProjection;
args[MATCH_PROJECTION] = matchProjection;
return networkClient.Invoke<List<MarketBook>>(Endpoint.Betting, LIST_MARKET_BOOK_METHOD, args);
}
public Task<BetfairServerResponse<List<MarketCatalogue>>> ListMarketCatalogue(
MarketFilter marketFilter,
ISet<MarketProjection> marketProjections = null,
MarketSort? sort = null,
int maxResult = 1)
{
var args = new Dictionary<string, object>();
args[FILTER] = marketFilter;
args[MARKET_PROJECTION] = marketProjections;
args[SORT] = sort;
args[MAX_RESULTS] = maxResult;
return networkClient.Invoke<List<MarketCatalogue>>(Endpoint.Betting, LIST_MARKET_CATALOGUE_METHOD, args);
}
public Task<BetfairServerResponse<List<MarketProfitAndLoss>>> ListMarketProfitAndLoss(
ISet<string> marketIds,
bool includeSettledBets,
bool includeBsbBets,
bool netOfCommission)
{
var args = new Dictionary<string, object>();
args[MARKET_IDS] = marketIds;
args[INCLUDE_SETTLED_BETS] = includeSettledBets;
args[INCLUDE_BSP_BETS] = includeBsbBets;
args[NET_OF_COMMISSION] = netOfCommission;
return networkClient.Invoke<List<MarketProfitAndLoss>>(Endpoint.Betting, LIST_MARKET_PROFIT_AND_LOSS, args);
}
public Task<BetfairServerResponse<List<MarketTypeResult>>> ListMarketTypes(MarketFilter marketFilter)
{
var args = new Dictionary<string, object>();
args[FILTER] = marketFilter;
return networkClient.Invoke<List<MarketTypeResult>>(Endpoint.Betting, LIST_MARKET_TYPES, args);
}
public Task<BetfairServerResponse<List<TimeRangeResult>>> ListTimeRanges(MarketFilter marketFilter, TimeGranularity timeGranularity)
{
var args = new Dictionary<string, object>();
args[FILTER] = marketFilter;
args[GRANULARITY] = timeGranularity;
return networkClient.Invoke<List<TimeRangeResult>>(Endpoint.Betting, LIST_TIME_RANGES, args);
}
public Task<BetfairServerResponse<List<VenueResult>>> ListVenues(MarketFilter marketFilter)
{
var args = new Dictionary<string, object>();
args[FILTER] = marketFilter;
return networkClient.Invoke<List<VenueResult>>(Endpoint.Betting, LIST_VENUES, args);
}
public Task<BetfairServerResponse<PlaceExecutionReport>> PlaceOrders(
string marketId,
IList<PlaceInstruction> placeInstructions,
string customerRef = null,
MarketVersion marketVersion = null)
{
var args = new Dictionary<string, object>();
args[MARKET_ID] = marketId;
args[INSTRUCTIONS] = placeInstructions;
args[CUSTOMER_REFERENCE] = customerRef;
args[MARKET_VERSION] = marketVersion;
return networkClient.Invoke<PlaceExecutionReport>(Endpoint.Betting, PLACE_ORDERS_METHOD, args);
}
public Task<BetfairServerResponse<CancelExecutionReport>> CancelOrders(
string marketId = null,
IList<CancelInstruction> instructions = null,
string customerRef = null)
{
var args = new Dictionary<string, object>();
args[INSTRUCTIONS] = instructions;
args[MARKET_ID] = marketId;
args[CUSTOMER_REFERENCE] = customerRef;
return networkClient.Invoke<CancelExecutionReport>(Endpoint.Betting, CANCEL_ORDERS_METHOD, args);
}
public Task<BetfairServerResponse<ReplaceExecutionReport>> ReplaceOrders(
string marketId,
IList<ReplaceInstruction> instructions,
string customerRef = null,
MarketVersion marketVersion = null)
{
var args = new Dictionary<string, object>();
args[MARKET_ID] = marketId;
args[INSTRUCTIONS] = instructions;
args[CUSTOMER_REFERENCE] = customerRef;
args[MARKET_VERSION] = marketVersion;
return networkClient.Invoke<ReplaceExecutionReport>(Endpoint.Betting, REPLACE_ORDERS_METHOD, args);
}
public Task<BetfairServerResponse<UpdateExecutionReport>> UpdateOrders(
string marketId,
IList<UpdateInstruction> instructions,
string customerRef = null)
{
var args = new Dictionary<string, object>();
args[MARKET_ID] = marketId;
args[INSTRUCTIONS] = instructions;
args[CUSTOMER_REFERENCE] = customerRef;
return networkClient.Invoke<UpdateExecutionReport>(Endpoint.Betting, UPDATE_ORDERS_METHOD, args);
}
public Task<BetfairServerResponse<AccountDetailsResponse>> GetAccountDetails()
{
var args = new Dictionary<string, object>();
return networkClient.Invoke<AccountDetailsResponse>(Endpoint.Account, GET_ACCOUNT_DETAILS, args);
}
public Task<BetfairServerResponse<AccountFundsResponse>> GetAccountFunds(Wallet wallet)
{
var args = new Dictionary<string, object>();
args[WALLET] = wallet;
return networkClient.Invoke<AccountFundsResponse>(Endpoint.Account, GET_ACCOUNT_FUNDS, args);
}
public Task<BetfairServerResponse<AccountStatementReport>> GetAccountStatement(
int? fromRecord = null,
int? recordCount = null,
TimeRange itemDateRange = null,
IncludeItem? includeItem = null,
Wallet? wallet = null)
{
var args = new Dictionary<string, object>();
return networkClient.Invoke<AccountStatementReport>(Endpoint.Account, GET_ACCOUNT_STATEMENT, args);
}
public Task<BetfairServerResponse<List<CurrencyRate>>> ListCurrencyRates(string fromCurrency)
{
var args = new Dictionary<string, object>();
args[FROM_CURRENCY] = fromCurrency;
return networkClient.Invoke<List<CurrencyRate>>(Endpoint.Account, LIST_CURRENCY_RATES, args);
}
public Task<BetfairServerResponse<TransferResponse>> TransferFunds(Wallet from, Wallet to, double amount)
{
var args = new Dictionary<string, object>();
args[FROM] = from;
args[TO] = to;
args[AMOUNT] = amount;
return networkClient.Invoke<TransferResponse>(Endpoint.Account, TRANSFER_FUNDS, args);
}
public Task<BetfairServerResponse<List<RaceDetails>>> ListRaceDetails(
ISet<string> meetingIds = null,
ISet<string> raceIds = null)
{
var args = new Dictionary<string, object>();
args[MEETINGIDS] = meetingIds;
args[RACEIDS] = raceIds;
return networkClient.Invoke<List<RaceDetails>>(Endpoint.Scores, LIST_RACE_DETAILS, args);
}
}
public enum Endpoint
{
Betting,
Account,
Scores,
}
public class LoginResponse
{
[JsonProperty(PropertyName = "sessionToken")]
public string SessionToken { get; set; }
[JsonProperty(PropertyName = "loginStatus")]
public string LoginStatus { get; set; }
}
public class KeepAliveResponse
{
[JsonProperty(PropertyName = "token")]
public string SessionToken { get; set; }
[JsonProperty(PropertyName = "product")]
public string Product { get; set; }
[JsonProperty(PropertyName = "status")]
public string Status { get; set; }
[JsonProperty(PropertyName = "error")]
public string Error { get; set; }
}
public class BetfairServerResponse<T>
{
public T Response { get; set; }
public DateTime LastByte { get; set; }
public DateTime RequestStart { get; set; }
public long LatencyMS { get; set; }
public bool HasError { get; set; }
public BetfairServerException Error { get; set; }
}
public class BetfairServerException : System.Exception
{
public JObject ServerData { get; set; }
public JObject ServerDetail { get; set; }
public static BetfairServerException ToClientException(Data.Exceptions.Exception ex)
{
if (ex == null)
return null;
var exception = new BetfairServerException();
exception.ServerData = ex.Data;
exception.ServerDetail = ex.Detail;
return exception;
}
}
}