forked from MatheusGrijo/BotStableArbitrageBINANCE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExchangeBinance.cs
594 lines (477 loc) · 19.6 KB
/
ExchangeBinance.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
using Binance.Net;
using Binance.Net.Objects;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
public class ExchangeBinance
{
public static int volumeDay = 800;
static JContainer exchangeInfo = null;
public ExchangeBinance()
{
try
{
String json = Http.get("https://api.binance.com/api/v1/exchangeInfo");
exchangeInfo = (JContainer)JsonConvert.DeserializeObject(json, (typeof(JContainer)));
}
catch
{
}
}
public class KLine
{
public string symbol;
public BinanceStreamKlineData kline;
}
public static List<KLine> lstKline = new List<KLine>();
public class Ticker
{
public string symbol;
public BinanceStreamTick tick;
}
public static List<Ticker> lstTicker = new List<Ticker>();
public decimal getLastPriceCACHE(string pair,string cache)
{
String jsonTicker = cache;
JContainer jCointanerTicker = (JContainer)JsonConvert.DeserializeObject(jsonTicker, (typeof(JContainer)));
foreach (var itemTicker in jCointanerTicker)
if (pair == itemTicker["symbol"].ToString())
{
Console.WriteLine(pair + ":" + decimal.Parse(itemTicker["lastPrice"].ToString().ToString().Replace(".", ",")));
return decimal.Parse(itemTicker["lastPrice"].ToString().ToString().Replace(".", ","));
}
return 0;
}
public decimal getLastPrice(string pair)
{
System.Threading.Thread.Sleep(1000);
String jsonTicker = Http.get("https://api.binance.com/api/v1/ticker/24hr");
JContainer jCointanerTicker = (JContainer)JsonConvert.DeserializeObject(jsonTicker, (typeof(JContainer)));
foreach (var itemTicker in jCointanerTicker)
if (pair == itemTicker["symbol"].ToString())
return decimal.Parse(itemTicker["lastPrice"].ToString().ToString().Replace(".", ","));
return 0;
}
public string getName()
{
return "BINANCE";
}
public void loadBalances()
{
throw new NotImplementedException();
}
Object objLock = new Object();
public string post(String url, String parameters, Method method = Method.POST)
{
try
{
lock (objLock)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient("https://api.binance.com");
HMACSHA256 encryptor = new HMACSHA256();
encryptor.Key = Encoding.ASCII.GetBytes(Key.getSecret());
String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", "");
parameters += "&signature=" + sign;
var request = new RestRequest("/api/v3/order?" + parameters, method);
request.AddHeader("X-MBX-APIKEY", Key.getKey());
var response = client.Execute(request);
Logger.log(response.Content);
return response.Content.ToString();
}
}
catch (Exception ex)
{
return null;
}
finally
{
}
}
public string httppost(String url, String parameters, String key, String secret)
{
try
{
// lock (objLock)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient("https://api.binance.com");
HMACSHA256 encryptor = new HMACSHA256();
encryptor.Key = Encoding.ASCII.GetBytes(Key.getSecret());
String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", "");
parameters += "&signature=" + sign;
var request = new RestRequest(url + "?" + parameters, Method.POST);
request.AddHeader("X-MBX-APIKEY", Key.getKey());
var response = client.Execute(request);
Console.WriteLine(response.Content);
return response.Content.ToString();
}
}
catch (Exception ex)
{
return null;
}
finally
{
}
}
public string order(string type, string pair, decimal amount, decimal price, bool lockQuantity = true, string timeInForce = "GTC")
{
amount = Math.Round(amount / getQuantity(pair)) * getQuantity(pair);
amount = Math.Round(amount, getQuotePrecision(pair));
amount -= getQuantity(pair);
price = Math.Round(price / getPriceFilter(pair)) * getPriceFilter(pair);
price = Math.Round(price, getPrecision(pair));
price = Math.Round(price, 8);
amount = Math.Round(amount, 8);
int countTry = 0;
string ret = post("https://api.binance.com/api/v3/order", "symbol=" + pair.ToUpper() + "&side=" + type.ToUpper() + "&type=LIMIT&timeInForce=" + timeInForce + "&quantity=" + amount.ToString().Replace(",", ".") + "&price=" + price.ToString().Replace(",", ".") + "×tamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()), Method.POST);
while (ret.IndexOf("insufficient balance") >= 0)
{
for (int i = 0; i < 100; i++)
{
amount -= 1;
}
ret = post("https://api.binance.com/api/v3/order", "symbol=" + pair.ToUpper() + "&side=" + type.ToUpper() + "&type=LIMIT&timeInForce=" + timeInForce + "&quantity=" + amount.ToString().Replace(",", ".") + "&price=" + price.ToString().Replace(",", ".") + "×tamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()), Method.POST);
countTry++;
if (countTry > 100)
{
amount = Math.Round(amount / getQuantity(pair)) * getQuantity(pair);
amount = Math.Round(amount, getQuotePrecision(pair));
amount -= getQuantity(pair);
amount = Math.Round(amount, 8);
ret = post("https://api.binance.com/api/v3/order", "symbol=" + pair.ToUpper() + "&side=" + type.ToUpper() + "&type=LIMIT&timeInForce=" + timeInForce + "&quantity=" + amount.ToString().Replace(",", ".") + "&price=" + price.ToString().Replace(",", ".") + "×tamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()), Method.POST);
return ret;
}
System.Threading.Thread.Sleep(new Random().Next(300, 500));
}
return ret;
}
public string orderMarket(string type, string pair, decimal amount)
{
amount = Math.Round(amount / getQuantity(pair)) * getQuantity(pair);
amount = Math.Round(amount, getQuotePrecision(pair));
int countTry = 0;
string ret = post("https://api.binance.com/api/v3/order", "symbol=" + pair.ToUpper() + "&side=" + type.ToUpper() + "&type=MARKET&quantity=" + amount.ToString().Replace(",", ".") + "×tamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()), Method.POST);
decimal amountDecrease = 3;
while (ret.IndexOf("insufficient balance") >= 0 || ret.IndexOf("many new orders") >= 0 || ret.IndexOf("LOT_SIZE") >= 0)
{
for (int i = 0; i < 2; i++)
amount -= getQuantity(pair);
amountDecrease++;
ret = post("https://api.binance.com/api/v3/order", "symbol=" + pair.ToUpper() + "&side=" + type.ToUpper() + "&type=MARKET&quantity=" + amount.ToString().Replace(",", ".") + "×tamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()), Method.POST);
countTry++;
if (countTry > 900)
{
amount = Math.Round(amount / getQuantity(pair)) * getQuantity(pair);
amount = Math.Round(amount, getQuotePrecision(pair));
amount -= getQuantity(pair);
amount = Math.Round(amount, getQuotePrecision(pair));
ret = post("https://api.binance.com/api/v3/order", "symbol=" + pair.ToUpper() + "&side=" + type.ToUpper() + "&type=MARKET&quantity=" + amount.ToString().Replace(",", ".") + "×tamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()), Method.POST);
return ret;
}
}
return ret;
}
public static decimal getQuantity(String coin)
{
foreach (var item in exchangeInfo["symbols"])
{
if (item["symbol"].ToString().Trim().ToUpper() == coin.Trim().ToUpper())
{
return decimal.Parse(item["filters"][2]["stepSize"].ToString().Replace(".", ","));
}
}
return 1;
}
public static decimal getPriceFilter(String coin)
{
foreach (var item in exchangeInfo["symbols"])
{
if (item["symbol"].ToString().Trim().ToUpper() == coin.Trim().ToUpper())
{
return decimal.Parse(item["filters"][0]["tickSize"].ToString().Replace(".", ","));
}
}
return 1;
}
public static int getPrecision(String coin)
{
foreach (var item in exchangeInfo["symbols"])
{
if (item["symbol"].ToString().Trim().ToUpper() == coin.Trim().ToUpper())
{
return int.Parse(item["baseAssetPrecision"].ToString().Replace(".", ","));
}
}
return 1;
}
public static int getQuotePrecision(String coin)
{
foreach (var item in exchangeInfo["symbols"])
{
if (item["symbol"].ToString().Trim().ToUpper() == coin.Trim().ToUpper())
{
return int.Parse(item["quotePrecision"].ToString().Replace(".", ","));
}
}
return 1;
}
public string getBalancesJSON()
{
try
{
var client = new RestClient("https://api.binance.com");
String parameters = "timestamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()).Split(',')[0];
HMACSHA256 encryptor = new HMACSHA256();
encryptor.Key = Encoding.ASCII.GetBytes(Key.getSecret());
String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", "");
parameters += "&signature=" + sign;
var request = new RestRequest("/api/v3/account?" + parameters, Method.GET);
request.AddHeader("X-MBX-APIKEY", Key.getKey());
var response = client.Execute(request);
//Console.WriteLine(response.Content);
return response.Content.ToString();
}
catch (Exception ex)
{
return "";
}
finally
{
}
}
public decimal getBalances(string _coin, string json)
{
try
{
JContainer dt = (JContainer)JsonConvert.DeserializeObject(json, (typeof(JContainer)));
foreach (var item in dt["balances"])
{
String coin = item["asset"].ToString();
decimal value = decimal.Parse(item["free"].ToString().Replace(".", ","));
if (value > 0)
{
if (coin.ToString().ToUpper() == _coin.ToUpper())
return value;
}
}
return 0;
}
catch (Exception ex)
{
return 0;
}
finally
{
}
}
public string getDetailOrder(String _coin, string orderId)
{
try
{
var client = new RestClient("https://api.binance.com");
String parameters = "timestamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()).Split(',')[0] + "&symbol=" + _coin + "&orderId=" + orderId;
HMACSHA256 encryptor = new HMACSHA256();
encryptor.Key = Encoding.ASCII.GetBytes(Key.getSecret());
String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", "");
parameters += "&signature=" + sign;
var request = new RestRequest("/api/v3/order?" + parameters, Method.GET);
request.AddHeader("X-MBX-APIKEY", Key.getKey());
var response = client.Execute(request);
Console.WriteLine(response.Content);
String json = response.Content.ToString();
JContainer dt = (JContainer)JsonConvert.DeserializeObject(json, (typeof(JContainer)));
return json;
}
catch (Exception ex)
{
return "";
}
finally
{
}
}
public bool withdrawal(string address, decimal amount)
{
try
{
var client = new RestClient("https://api.binance.com");
String parameters = "timestamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()).Split(',')[0] + "&asset=BTC&address=" + address + "&amount=" + amount.ToString().Replace(",", ".");
HMACSHA256 encryptor = new HMACSHA256();
encryptor.Key = Encoding.ASCII.GetBytes(Key.getSecret());
String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", "");
parameters += "&signature=" + sign;
var request = new RestRequest("/wapi/v3/withdraw.html?" + parameters, Method.POST);
request.AddHeader("X-MBX-APIKEY", Key.getKey());
var response = client.Execute(request);
Console.WriteLine(response.Content);
String json = response.Content.ToString();
JContainer dt = (JContainer)JsonConvert.DeserializeObject(json, (typeof(JContainer)));
if (dt["success"].ToString().ToUpper() == "TRUE")
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
finally
{
}
}
public string getAllOrders()
{
try
{
var client = new RestClient("https://api.binance.com");
String parameters = "timestamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime());
HMACSHA256 encryptor = new HMACSHA256();
encryptor.Key = Encoding.ASCII.GetBytes(Key.getSecret());
String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", "");
parameters += "&signature=" + sign;
var request = new RestRequest("/api/v3/openOrders?" + parameters, Method.GET);
request.AddHeader("X-MBX-APIKEY", Key.getKey());
var response = client.Execute(request);
Console.WriteLine(response.Content);
String json = response.Content.ToString();
return json;
}
catch (Exception ex)
{
return null;
}
finally
{
}
}
public string getDeposits()
{
try
{
var client = new RestClient("https://api.binance.com");
String parameters = "timestamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime());
HMACSHA256 encryptor = new HMACSHA256();
encryptor.Key = Encoding.ASCII.GetBytes(Key.getSecret());
String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", "");
parameters += "&signature=" + sign;
var request = new RestRequest("/wapi/v3/depositHistory.html?" + parameters, Method.GET);
request.AddHeader("X-MBX-APIKEY", Key.getKey());
var response = client.Execute(request);
Console.WriteLine(response.Content);
String json = response.Content.ToString();
return json;
}
catch (Exception ex)
{
return null;
}
finally
{
}
}
public string getAddress(String asset)
{
try
{
var client = new RestClient("https://api.binance.com");
String parameters = "timestamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()) + "&status=true&asset=" + asset;
HMACSHA256 encryptor = new HMACSHA256();
encryptor.Key = Encoding.ASCII.GetBytes(Key.getSecret());
String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", "");
parameters += "&signature=" + sign;
var request = new RestRequest("/wapi/v3/depositAddress.html?" + parameters, Method.GET);
request.AddHeader("X-MBX-APIKEY", Key.getKey());
var response = client.Execute(request);
Console.WriteLine(response.Content);
String json = response.Content.ToString();
return json;
}
catch (Exception ex)
{
return null;
}
finally
{
}
}
public string cancelOrder(String pair, String id)
{
try
{
return post("https://api.binance.com/api/v3/order", "symbol=" + pair.ToUpper() + "&orderId=" + id + "×tamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()), Method.DELETE);
}
catch (Exception ex)
{
return null;
}
finally
{
}
}
public static decimal getVolumeBTC(string pair)
{
try
{
String jsonTicker = Http.get("https://api.binance.com/api/v1/ticker/24hr");
JContainer jCointanerTicker = (JContainer)JsonConvert.DeserializeObject(jsonTicker, (typeof(JContainer)));
foreach (var item in jCointanerTicker)
{
if (item["symbol"].ToString().Trim().ToUpper() == pair.Trim().ToUpper())
{
decimal volume = decimal.Parse(item["quoteVolume"].ToString().Replace(".", ","));
return volume;
}
}
}
catch { return 0; }
return 0;
}
public static decimal getPriceChangePercentCache(string pair,string cache)
{
try
{
String jsonTicker = cache;
JContainer jCointanerTicker = (JContainer)JsonConvert.DeserializeObject(jsonTicker, (typeof(JContainer)));
foreach (var item in jCointanerTicker)
{
if (item["symbol"].ToString().Trim().ToUpper() == pair.Trim().ToUpper())
{
decimal priceChange = decimal.Parse(item["priceChangePercent"].ToString().Replace(".", ","));
return priceChange;
}
}
}
catch { return 0; }
return 0;
}
public static decimal getPriceChangePercent(string pair)
{
try
{
String jsonTicker = Http.get("https://api.binance.com/api/v1/ticker/24hr");
JContainer jCointanerTicker = (JContainer)JsonConvert.DeserializeObject(jsonTicker, (typeof(JContainer)));
foreach (var item in jCointanerTicker)
{
if (item["symbol"].ToString().Trim().ToUpper() == pair.Trim().ToUpper())
{
decimal priceChange = decimal.Parse(item["priceChangePercent"].ToString().Replace(".", ","));
return priceChange;
}
}
}
catch { return 0; }
return 0;
}
}