/
BTCeAPIWrapper.cs
722 lines (579 loc) · 23.8 KB
/
BTCeAPIWrapper.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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
using log4net;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Timers;
using System.Web;
namespace BTCeAPI
{
#region Helper classes
/// <summary>
/// Helper class for converting from UnixTime to .NET DateTime object
/// </summary>
static class UnixTime
{
/// <summary>
/// Initial Reference Date for Unix Time conversions
/// </summary>
static DateTime unixEpoch;
#region Constructors
/// <summary>
/// Default Constrcutor - initialize referent Date - 1970-01-01
/// </summary>
static UnixTime()
{
unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
}
#endregion Constructors
/// <summary>
/// Returns current Unix Time
/// </summary>
public static UInt32 Now { get { return GetFromDateTime(DateTime.UtcNow); } }
/// <summary>
/// Returns Unix Time for passed Date
/// </summary>
/// <param name="d">Referent Date</param>
/// <returns>Total seconds</returns>
public static UInt32 GetFromDateTime(DateTime d) { return (UInt32)(d - unixEpoch).TotalSeconds; }
/// <summary>
/// Converts Unix Time to .NET DateTime object
/// </summary>
/// <param name="unixtime">Unix Time to convert</param>
/// <returns>.NET DateTime object</returns>
public static DateTime ConvertToDateTime(UInt32 unixtime) { return unixEpoch.AddSeconds(unixtime); }
}
#endregion Helper classes
/// <summary>
/// BTCe API Wrapper
/// </summary>
public class BTCeAPIWrapper
{
#region Constanrs
/// <summary>
/// Indicates Price Change event to be pushed always
/// </summary>
public const int PUSH_PRICE_CHANGE_ALWAYS = 0;
/// <summary>
/// Indicates Price Change event to be pushed when BUY price change
/// </summary>
public const int PUSH_PRICE_CHANGE_BUY = 1;
/// <summary>
/// Indicates Price Change event to be pushed when SELL price change
/// </summary>
public const int PUSH_PRICE_CHANGE_SELL = 2;
/// <summary>
/// Indicates Price Change event to be pushed when BUY price is greater then privious one
/// </summary>
public const int PUSH_PRICE_CHANGE_BUY_UP = 4;
/// <summary>
/// Indicates Price Change event to be pushed when BUY price is lower then privious one
/// </summary>
public const int PUSH_PRICE_CHANGE_BUY_DOWN = 8;
/// <summary>
/// Indicates Price Change event to be pushed when SELL price is greater then privious one
/// </summary>
public const int PUSH_PRICE_CHANGE_SELL_UP = 16;
/// <summary>
/// Indicates Price Change event to be pushed when SELL price is lower then privious one
/// </summary>
public const int PUSH_PRICE_CHANGE_SELL_DOWN = 32;
#endregion Constanrs
#region Static Members
private static ILog logger = log4net.LogManager.GetLogger("Console");
private static BTCeAPIWrapper instance;
private static object lockObject = new object();
private static string BTCeAPITickerURL = "https://btc-e.com/api/2/{0}/ticker";
private static string BTCeAPIFeeURL = "https://btc-e.com/api/2/{0}/fee";
private static string BTCeAPIPrivateURL = "https://btc-e.com/tapi";
private static UInt32 Nonce = UnixTime.Now;
private static UInt32 lastNonce = 0;
#endregion Static Members
#region Private members
private Timer Ticker = new Timer();
private Timer Fee = new Timer();
private Timer ActiveOrders = new Timer();
private Timer Info = new Timer();
private int tickerTimeout = 1;
private int feeTimeout = 1;
private int ordersTimeout = 5;
private int infoTimeout = 2;
private BTCePair currency = BTCePair.btc_usd;
private string key;
private HMACSHA512 hashMaker;
private bool startActiveOtrders = false;
private bool authenticated = false;
private TickerInfo latestTicker = null;
private int latestActiveOrdersCount = -1;
private decimal latestTotalAmount = -1;
private FeeInfo latestFee = null;
private AccountInfo latestAccountInfo = null;
#endregion Private members
#region Public Event Handlers
/// <summary>
/// Event Handler fired when new Price information is retrieved
/// </summary>
public EventHandler PriceChanged;
/// <summary>
/// Event Handler fired when new Fee information is received
/// </summary>
public EventHandler FeeChanged;
/// <summary>
/// Event Handler fired when new Account information is received
/// This event should be used after Authentication data is provided
/// see method Credential(string key, string secret)
/// </summary>
public EventHandler InfoReceived;
/// <summary>
/// Event Handler fired when new Active Orders information is received
/// This event should be used after Authentication data is provided
/// see method Credential(string key, string secret)
/// </summary>
public EventHandler ActiveOrdersReceived;
/// <summary>
/// Event Handler fired when new Active Orders count has changed
/// This event should be used after Authentication data is provided
/// see method Credential(string key, string secret)
/// </summary>
public EventHandler ActiveOrdersCountChanged;
/// <summary>
/// Event Handler fired when total Active Orders Amount has changed
/// This event should be used after Authentication data is provided
/// see method Credential(string key, string secret)
/// </summary>
public EventHandler ActiveOrdersTotalAmountChanged;
/// <summary>
/// Event Handler fired when specific Currency Amount has changed
/// This event should be used after Authentication data is provided
/// see method Credential(string key, string secret)
/// </summary>
public EventHandler CurrencyAmountChanged;
#endregion Public Event Handlers
#region Properties
/// <summary>
/// Sets Ticker/Price change retrieval period in seconds
/// Default period is 1 second
/// </summary>
public int TickerTimeout { private get { return tickerTimeout; } set { Ticker.Stop(); tickerTimeout = value; Ticker.Interval = tickerTimeout * 1000; Ticker.Start(); } }
/// <summary>
/// Sets Fee change retrieval period in seconds
/// Default period is 259200 seconds (3 hours)
/// </summary>
public int FeeTimeout { private get { return feeTimeout; } set { Fee.Stop(); feeTimeout = value; Fee.Interval = feeTimeout * 1000; Fee.Start(); } }
/// <summary>
/// Sets Active Orders change retrieval period in seconds
/// Default period is 5 seconds
/// </summary>
public int OrdersTimeout { private get { return ordersTimeout; } set { ActiveOrders.Stop(); ordersTimeout = value; ActiveOrders.Interval = ordersTimeout * 1000; if (startActiveOtrders) { ActiveOrders.Start(); } } }
/// <summary>
/// Sets active Pair (Currency) that will be used for Ticker/Price and Active Orders retrieval
/// DEfault value is btc_usd
/// </summary>
public BTCePair Currency { private get { return currency; } set { currency = value; Ticker.Stop(); Ticker.Start(); } }
/// <summary>
/// Gets Default Fee as default Fee rerieval period is every 3 hours and before next retrieval
/// Also this Default Fee can be used if there is API issues with retrieving onine Fee
/// </summary>
public FeeInfo DefaultFee { get { return FeeInfo.ReadFromJSON("{\"trade\":0.2}"); } }
/// <summary>
/// Indicates which Price Change should be monitored in order to push Price information
/// Use the following available constants (you can combine then using |):
/// PUSH_PRICE_CHANGE_ALWAYS - always send latest Price information (default value)
/// PUSH_PRICE_CHANGE_BUY - send Price infromation when there is change in BUY price
/// PUSH_PRICE_CHANGE_SELL - send Price infromation when there is change in SELL price
/// PUSH_PRICE_CHANGE_BUY_UP - send Price infromation when there is increase in BUY price
/// PUSH_PRICE_CHANGE_BUY_DOWN - send Price infromation when there is decrease in BUY price
/// PUSH_PRICE_CHANGE_SELL_UP - send Price infromation when there is increase in SELL price
/// PUSH_PRICE_CHANGE_SELL_DOWN - send Price infromation when there is decrease in SELL price
/// </summary>
public int PriceChangePushIndicator { private get; set; }
/// <summary>
/// Returns BTCeAPIWrapper object
/// </summary>
public static BTCeAPIWrapper Instance
{
get {
if (instance == null)
{
lock (lockObject)
{
instance = new BTCeAPIWrapper();
}
}
return instance;
}
}
#endregion Properties
#region Constructors
static BTCeAPIWrapper()
{
}
private BTCeAPIWrapper()
{
PriceChangePushIndicator = PUSH_PRICE_CHANGE_ALWAYS;
Ticker.Interval = TickerTimeout * 1000;
Ticker.Elapsed += CheckForNewPrice;
Ticker.Start();
logger.Info("Ticker Timer started ...");
Fee.Interval = FeeTimeout * 1000;
Fee.Elapsed += CheckForNewFee;
Fee.Start();
CheckForNewFee(null, null);
ActiveOrders.Interval = ordersTimeout * 1000;
ActiveOrders.Elapsed += GetActiveOrders;
Info.Interval = infoTimeout * 1000;
Info.Elapsed += GetAccountInfo;
}
#endregion Constructors
#region Private Static Methods
private static UInt32 GetNonce()
{
while (UnixTime.Now - lastNonce <= 1) ;
lastNonce = UnixTime.Now;
Nonce = lastNonce;
return Nonce;
}
/*
private static byte[] BuildPostData(Dictionary<string, string> d)
{
StringBuilder s = new StringBuilder();
foreach (var item in d)
{
s.AppendFormat("{0}={1}", item.Key, HttpUtility .UrlEncode(item.Value));
s.Append("&");
}
if (s.Length > 0)
{
s.Remove(s.Length - 1, 1);
}
return Encoding.ASCII.GetBytes(s.ToString());
}
* */
private static string BuildPostData(Dictionary<string, string> d)
{
StringBuilder s = new StringBuilder();
foreach (var item in d)
{
s.AppendFormat("{0}={1}", item.Key, HttpUtility.UrlEncode(item.Value));
s.Append("&");
}
if (s.Length > 0)
{
s.Remove(s.Length - 1, 1);
}
return s.ToString();
}
private static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", "");
}
#endregion Private Static Methods
#region Private Methods
private string Query(Dictionary<string, string> args)
{
var nonce = GetNonce().ToString();
args.Add("nonce", nonce);
var dataStr = BuildPostData(args);
var data = Encoding.ASCII.GetBytes(dataStr);
var headers = new WebHeaderCollection { { "Key", key }, { "Sign", ByteArrayToString(hashMaker.ComputeHash(data)).ToLower() } };
var request = WebRequest.Create(new Uri(BTCeAPIPrivateURL)) as HttpWebRequest;
if (request == null)
throw new Exception("Non HTTP WebRequest");
int TimeOut = 10;
request.Headers = headers;
request.Method = "POST";
request.Timeout = TimeOut * 1000;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
return (new StreamReader(request.GetResponse().GetResponseStream())).ReadToEnd();
}
private string DecimalToString(decimal d)
{
return d.ToString(CultureInfo.InvariantCulture);
}
#endregion Private Methods
#region Public Methods
/// <summary>
/// Sets Credetials that will be used for Authenticating against BTCe services
/// </summary>
/// <param name="key">BTCe API Key</param>
/// <param name="secret">BTCe API Sercet - it will be used once to create HMAC-SHA512 object for signing API requests </param>
public void Credential(string key, string secret)
{
Info.Stop();
ActiveOrders.Stop();
this.key = key;
hashMaker = new HMACSHA512(Encoding.ASCII.GetBytes(secret));
authenticated = false;
startActiveOtrders = false;
Info.Start();
}
/// <summary>
/// Place single trade with passed parameters
/// </summary>
/// <param name="pair">Trade Pair (currency)</param>
/// <param name="type">Trade Type</param>
/// <param name="rate">Trade Rate</param>
/// <param name="amount">Trade Amount</param>
/// <returns>On successful operation will return populated TradeAnswer, on error will throw BTCeException with original BTCe API error message</returns>
public TradeAnswer PlaceOrder(BTCePair pair, BTCeTradeType type, decimal rate, decimal amount)
{
if (!authenticated)
{
throw new BTCeAPIException("Not Authenticated");
}
var resultStr = Query(new Dictionary<string, string>()
{
{ "method", "Trade" },
{ "pair", BtcePairHelper.ToString(pair) },
{ "type", TradeTypeHelper.ToString(type) },
{ "rate", DecimalToString(rate) },
{ "amount", DecimalToString(amount) }
});
return TradeAnswer.ReadFromJSON(resultStr);
}
/// <summary>
/// Retrieves Order infromation for provided Order ID.
/// If no Order with provided ID is found - BTCeException is thrown
/// </summary>
/// <param name="orderId">Order ID</param>
/// <returns>Order information for supplied ID</returns>
public OrderInfo GetOrderInformation(int orderId)
{
if (!authenticated)
{
throw new BTCeAPIException("Not Authenticated");
}
var resultStr = Query(new Dictionary<string, string>()
{
{ "method", "OrderInfo" },
{ "order_id", orderId.ToString() }
});
return OrderInfo.ReadFromJSON(resultStr);
}
#endregion Public Methods
#region Timer Callbacks
private void CheckForNewFee(object sender, ElapsedEventArgs e)
{
Fee.Stop();
if (FeeChanged != null)
{
Fee.Interval = feeTimeout * 1000;
new System.Threading.Thread(CallBTCeAPIFee).Start();
return;
}
else
{
Fee.Interval = 1000;
}
Fee.Start();
}
private void CheckForNewPrice(object sender, ElapsedEventArgs e)
{
Ticker.Stop();
if (PriceChanged != null)
{
new System.Threading.Thread(CallBTCeAPITicker).Start();
return;
}
Ticker.Start();
}
private void GetAccountInfo(object sender, ElapsedEventArgs e)
{
Info.Stop();
if (InfoReceived != null)
{
new System.Threading.Thread(CallBTCeAPIAccountInfo).Start();
return;
}
Info.Start();
}
private void GetActiveOrders(object sender, ElapsedEventArgs e)
{
ActiveOrders.Stop();
if (ActiveOrdersReceived != null ||
ActiveOrdersCountChanged != null ||
ActiveOrdersTotalAmountChanged != null)
{
new System.Threading.Thread(CallBTCeAPIActiveOrders).Start();
return;
}
ActiveOrders.Start();
}
#endregion Timer Callbacks
#region Thread Called Methods
private void CallBTCeAPITicker()
{
int TimeOut = 10;
string queryStr = string.Format(BTCeAPITickerURL, BtcePairHelper.ToString(currency));
var request = (HttpWebRequest)WebRequest.Create(queryStr);
request.GetResponse();
request.Timeout = TimeOut * 1000;
if (request == null)
{
throw new Exception("Non HTTP WebRequest");
}
TickerInfo ticker = TickerInfo.ReadFromJSON(new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd());
if (PriceChanged != null)
{
if (
latestTicker == null ||
PriceChangePushIndicator == PUSH_PRICE_CHANGE_ALWAYS ||
((PriceChangePushIndicator & PUSH_PRICE_CHANGE_BUY) > 0 && latestTicker.Buy != ticker.Buy) ||
((PriceChangePushIndicator & PUSH_PRICE_CHANGE_SELL) > 0 && latestTicker.Sell != ticker.Sell) ||
((PriceChangePushIndicator & PUSH_PRICE_CHANGE_BUY_DOWN) > 0 && latestTicker.Buy > ticker.Buy) ||
((PriceChangePushIndicator & PUSH_PRICE_CHANGE_BUY_UP) > 0 && latestTicker.Buy < ticker.Buy) ||
((PriceChangePushIndicator & PUSH_PRICE_CHANGE_SELL_DOWN) > 0 && latestTicker.Sell > ticker.Sell) ||
((PriceChangePushIndicator & PUSH_PRICE_CHANGE_SELL_UP) > 0 && latestTicker.Sell < ticker.Sell)
)
{
PriceChanged(
ticker,
EventArgs.Empty);
}
latestTicker = ticker;
}
else
{
latestTicker = ticker;
}
Ticker.Start();
}
private void CallBTCeAPIFee()
{
int TimeOut = 10;
string queryStr = string.Format(BTCeAPIFeeURL, BtcePairHelper.ToString(currency));
var request = (HttpWebRequest)WebRequest.Create(queryStr);
request.GetResponse();
request.Timeout = TimeOut * 1000;
if (request == null)
{
throw new Exception("Non HTTP WebRequest");
}
if (FeeChanged != null)
{
FeeInfo currentFee = FeeInfo.ReadFromJSON(new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd());
if (latestFee == null ||
latestFee.Fee != currentFee.Fee)
{
FeeChanged(currentFee, EventArgs.Empty);
}
latestFee = currentFee;
}
Fee.Start();
}
private void CallBTCeAPIAccountInfo()
{
var resultStr = Query(new Dictionary<string, string>()
{
{ "method", "getInfo" }
});
try
{
AccountInfo info = AccountInfo.ReadFromJSON(resultStr);
if (InfoReceived != null)
{
InfoReceived(info, EventArgs.Empty);
authenticated = true;
if (!startActiveOtrders)
{
ActiveOrders.Start();
startActiveOtrders = true;
}
}
if (CurrencyAmountChanged != null)
{
if (latestAccountInfo != null)
{
List<BTCeCurrency> changedCurrencies = new List<BTCeAPI.BTCeCurrency>();
foreach (Currency c in info.Currencies)
{
if (c.Value != latestAccountInfo.CurrencyValue(c.Name))
{
changedCurrencies.Add(c.Name);
}
}
if (changedCurrencies.Count > 0)
{
CurrencyAmountChanged(info, new CurrencyEventArgs(changedCurrencies));
}
}
}
latestAccountInfo = info;
Info.Start();
}
catch (BTCeAPIException e)
{
InfoReceived(e, EventArgs.Empty);
}
catch (Exception ex)
{
InfoReceived(ex, EventArgs.Empty);
Info.Start();
}
}
private void CallBTCeAPIActiveOrders()
{
var resultStr = Query(new Dictionary<string, string>()
{
{ "method", "ActiveOrders" },
{ "pair", BtcePairHelper.ToString(currency) }
});
if (ActiveOrdersReceived != null ||
ActiveOrdersCountChanged != null ||
ActiveOrdersTotalAmountChanged != null)
{
try
{
OrdersList orders = OrdersList.ReadFromJSON(resultStr);
var totalAmount = orders.List.Sum(x => x.Value.Amount);
if (ActiveOrdersReceived != null)
{
ActiveOrdersReceived(orders, EventArgs.Empty);
}
if (ActiveOrdersCountChanged != null)
{
if (latestActiveOrdersCount > -1 &&
latestActiveOrdersCount != orders.List.Count)
{
ActiveOrdersCountChanged(orders, new DecimalEventArgs(latestActiveOrdersCount));
}
}
if (ActiveOrdersTotalAmountChanged != null)
{
if (latestTotalAmount > -1 &&
latestTotalAmount != totalAmount)
{
ActiveOrdersTotalAmountChanged(orders, new DecimalEventArgs(latestTotalAmount));
}
}
if (latestActiveOrdersCount != orders.List.Count)
{
latestActiveOrdersCount = orders.List.Count;
}
if (latestTotalAmount != totalAmount)
{
latestTotalAmount = totalAmount;
}
ActiveOrders.Start();
}
catch (BTCeAPIException e)
{
ActiveOrdersReceived(e, EventArgs.Empty);
}
catch (Exception ex)
{
ActiveOrdersReceived(ex, EventArgs.Empty);
}
}
}
#endregion Thread Called Methods
}
}