-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathBitMexAPI.cs
420 lines (359 loc) · 14.8 KB
/
BitMexAPI.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
//using ServiceStack.Text;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace BitMEX
{
public class OrderBookItem
{
public string Symbol { get; set; }
public int Level { get; set; }
public int BidSize { get; set; }
public decimal BidPrice { get; set; }
public int AskSize { get; set; }
public decimal AskPrice { get; set; }
public DateTime Timestamp { get; set; }
}
public class BitMEXApi
{
private string domain = "https://testnet.bitmex.com";
private string apiKey;
private string apiSecret;
private int rateLimit;
public BitMEXApi(string bitmexKey = "", string bitmexSecret = "", string bitmexDomain = "", int rateLimit = 5000)
{
this.apiKey = bitmexKey;
this.apiSecret = bitmexSecret;
this.rateLimit = rateLimit;
this.domain = bitmexDomain;
}
#region API Connector - Don't touch
private string BuildQueryData(Dictionary<string, string> param)
{
if (param == null)
return "";
StringBuilder b = new StringBuilder();
foreach (var item in param)
b.Append(string.Format("&{0}={1}", item.Key, WebUtility.UrlEncode(item.Value)));
try { return b.ToString().Substring(1); }
catch (Exception) { return ""; }
}
private string BuildJSON(Dictionary<string, string> param)
{
if (param == null)
return "";
var entries = new List<string>();
foreach (var item in param)
entries.Add(string.Format("\"{0}\":\"{1}\"", item.Key, item.Value));
return "{" + string.Join(",", entries) + "}";
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
static object objLock = new object();
private long GetNonce()
{
//lock (objLock)
{
System.Threading.Thread.Sleep(800);
DateTime yearBegin = new DateTime(2018, 1, 1);
return DateTime.UtcNow.Ticks - yearBegin.Ticks;
//long ret = long.Parse(DateTime.UtcNow.ToString("yyyyMMddHHmmssffff"));
//return ret;
}
}
private byte[] hmacsha256(byte[] keyByte, byte[] messageBytes)
{
using (var hash = new HMACSHA256(keyByte))
{
return hash.ComputeHash(messageBytes);
}
}
static object objLockQuery = new object();
private string Query(string method, string function, Dictionary<string, string> param = null, bool auth = false, bool json = false)
{
// lock (objLockQuery)
{
String[] proxys = System.Text.RegularExpressions.Regex.Split(Http.get("https://www.proxy-list.download/api/v1/get?type=https&anon=elite&country=CN"), Environment.NewLine);
String proxy = proxys[new Random().Next(0, proxys.Length - 2)];
string paramData = json ? BuildJSON(param) : BuildQueryData(param);
string url = "/api/v1" + function + ((method == "GET" && paramData != "") ? "?" + paramData : "");
string postData = (method != "GET") ? paramData : "";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(domain + url);
webRequest.Method = method;
WebProxy webProxy = new WebProxy(proxy.Split(':')[0], int.Parse(proxy.Split(':')[1]));
//webRequest.Proxy = webProxy;
if (auth)
{
string nonce = GetNonce().ToString();
string message = method + url + nonce + postData;
byte[] signatureBytes = hmacsha256(Encoding.UTF8.GetBytes(apiSecret), Encoding.UTF8.GetBytes(message));
string signatureString = ByteArrayToString(signatureBytes);
webRequest.Headers.Add("api-nonce", nonce);
webRequest.Headers.Add("api-key", apiKey);
webRequest.Headers.Add("api-signature", signatureString);
}
try
{
if (postData != "")
{
webRequest.ContentType = json ? "application/json" : "application/x-www-form-urlencoded";
var data = Encoding.UTF8.GetBytes(postData);
using (var stream = webRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
using (WebResponse webResponse = webRequest.GetResponse())
using (Stream str = webResponse.GetResponseStream())
using (StreamReader sr = new StreamReader(str))
{
return sr.ReadToEnd();
}
}
catch (WebException wex)
{
using (HttpWebResponse response = (HttpWebResponse)wex.Response)
{
if (response == null)
throw;
using (Stream str = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return sr.ReadToEnd();
}
}
}
}
}
}
#endregion
#region Examples from BitMex
//public List<OrderBookItem> GetOrderBook(string symbol, int depth)
//{
// var param = new Dictionary<string, string>();
// param["symbol"] = symbol;
// param["depth"] = depth.ToString();
// string res = Query("GET", "/orderBook", param);
// return JsonSerializer.DeserializeFromString<List<OrderBookItem>>(res);
//}
public string GetOrdersHistory(string Symbol,string timestamp)
{
var param = new Dictionary<string, string>();
param["symbol"] = Symbol;
param["timestamp"] = timestamp;
//param["columns"] = "";
//param["count"] = 100.ToString();
//param["start"] = 0.ToString();
//param["reverse"] = false.ToString();
//param["startTime"] = "";
//param["endTime"] = "";
return Query("GET", "/user/executionHistory", param, true);
}
public string GetOrders(string Symbol)
{
var param = new Dictionary<string, string>();
param["symbol"] = Symbol;
param["filter"] = "{\"open\":true}";
//param["columns"] = "";
//param["count"] = 100.ToString();
//param["start"] = 0.ToString();
//param["reverse"] = false.ToString();
//param["startTime"] = "";
//param["endTime"] = "";
return Query("GET", "/order", param, true);
}
public string PostOrders()
{
var param = new Dictionary<string, string>();
param["symbol"] = "XBTUSD";
param["side"] = "Buy";
param["orderQty"] = "1";
param["ordType"] = "Market";
return Query("POST", "/order", param, true);
}
public string DeleteOrders(String id)
{
var param = new Dictionary<string, string>();
param["orderID"] = id;
param["text"] = "cancel order by ID";
return Query("DELETE", "/order", param, true, true);
}
#endregion
#region Our Calls
public List<OrderBook> GetOrderBook(string symbol, int depth)
{
var param = new Dictionary<string, string>();
param["symbol"] = symbol;
param["depth"] = depth.ToString();
string res = Query("GET", "/orderBook/L2", param);
return JsonConvert.DeserializeObject<List<OrderBook>>(res);
}
public string PostOrderPostOnly(string Symbol, string Side, double Price, int Quantity, bool force = false)
{
var param = new Dictionary<string, string>();
param["symbol"] = Symbol;
param["side"] = Side;
param["orderQty"] = Quantity.ToString();
param["ordType"] = "Limit";
if (!force)
param["execInst"] = "ParticipateDoNotInitiate";
//param["displayQty"] = 1.ToString(); // Shows the order as hidden, keeps us from moving price away from our own orders
param["price"] = Price.ToString().Replace(",", ".");
string ret = Query("POST", "/order", param, true);
return ret;
}
public string MarketOrder(string Symbol, string Side, int Quantity)
{
var param = new Dictionary<string, string>();
param["symbol"] = Symbol;
param["side"] = Side;
param["orderQty"] = Quantity.ToString();
param["ordType"] = "Market";
String ret = Query("POST", "/order", param, true);
return ret;
}
public string CancelAllOpenOrders(string symbol, string Note = "")
{
var param = new Dictionary<string, string>();
param["symbol"] = symbol;
param["text"] = Note;
return Query("DELETE", "/order/all", param, true, true);
}
public List<Instrument> GetActiveInstruments()
{
string res = Query("GET", "/instrument/active");
return JsonConvert.DeserializeObject<List<Instrument>>(res);
}
public List<Instrument> GetInstrument(string symbol)
{
var param = new Dictionary<string, string>();
param["symbol"] = symbol;
string res = Query("GET", "/instrument", param);
return JsonConvert.DeserializeObject<List<Instrument>>(res);
}
public List<Candle> GetCandleHistory(string symbol, int count, string size)
{
var param = new Dictionary<string, string>();
param["symbol"] = symbol;
param["count"] = count.ToString();
param["reverse"] = true.ToString();
param["partial"] = "false";
param["binSize"] = size;
string res = Query("GET", "/trade/bucketed", param);
return JsonConvert.DeserializeObject<List<Candle>>(res).OrderByDescending(a => a.TimeStamp).ToList();
}
public List<Position> GetOpenPositions(string symbol)
{
var param = new Dictionary<string, string>();
string res = Query("GET", "/position", param, true);
return JsonConvert.DeserializeObject<List<Position>>(res).Where(a => a.Symbol == symbol && a.IsOpen == true).OrderByDescending(a => a.TimeStamp).ToList();
}
public List<Order> GetOpenOrders(string symbol)
{
var param = new Dictionary<string, string>();
param["symbol"] = symbol;
param["reverse"] = true.ToString();
string res = Query("GET", "/order", param, true);
return JsonConvert.DeserializeObject<List<Order>>(res).Where(a => a.OrdStatus == "New" || a.OrdStatus == "PartiallyFilled").OrderByDescending(a => a.TimeStamp).ToList();
}
public string EditOrderPrice(string OrderId, double Price)
{
var param = new Dictionary<string, string>();
param["orderID"] = OrderId;
param["price"] = Price.ToString();
return Query("PUT", "/order", param, true, true);
}
public string GetWallet()
{
var param = new Dictionary<string, string>();
param["currency"] = "XBt";
return Query("GET", "/user/walletHistory", param, true);
}
#endregion
#region RateLimiter
private long lastTicks = 0;
private object thisLock = new object();
private void RateLimit()
{
lock (thisLock)
{
long elapsedTicks = DateTime.Now.Ticks - lastTicks;
var timespan = new TimeSpan(elapsedTicks);
if (timespan.TotalMilliseconds < rateLimit)
Thread.Sleep(rateLimit - (int)timespan.TotalMilliseconds);
lastTicks = DateTime.Now.Ticks;
}
}
#endregion RateLimiter
}
// Working Classes
public class OrderBook
{
public string Side { get; set; }
public double Price { get; set; }
public int Size { get; set; }
}
public class Instrument
{
public string Symbol { get; set; }
public double TickSize { get; set; }
public double Volume24H { get; set; }
}
public class Candle
{
public DateTime TimeStamp { get; set; }
public double? open { get; set; }
public double? close { get; set; }
public double? high { get; set; }
public double? low { get; set; }
public double? volume { get; set; }
}
public class Position
{
public DateTime TimeStamp { get; set; }
public double? Leverage { get; set; }
public int? CurrentQty { get; set; }
public double? CurrentCost { get; set; }
public bool IsOpen { get; set; }
public double? MarkPrice { get; set; }
public double? MarkValue { get; set; }
public double? UnrealisedPnl { get; set; }
public double? UnrealisedPnlPcnt { get; set; }
public double? AvgEntryPrice { get; set; }
public double? BreakEvenPrice { get; set; }
public double? LiquidationPrice { get; set; }
public double? LastValue { get; set; }
public string Symbol { get; set; }
public double percentual()
{
if (UnrealisedPnl < 0)
return (((((double)UnrealisedPnl * (-1)) * 100) / (double)LastValue) * (double)Leverage) * (-1);
else
return ((((double)UnrealisedPnl) * 100) / (double)LastValue) * (double)Leverage;
}
}
public class Order
{
public DateTime TimeStamp { get; set; }
public string Symbol { get; set; }
public string OrdStatus { get; set; }
public string OrdType { get; set; }
public string OrderId { get; set; }
public string Side { get; set; }
public double? Price { get; set; }
public int? OrderQty { get; set; }
public int? DisplayQty { get; set; }
}
}