forked from n0mad01/node.bittrex.api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.bittrex.api.js
326 lines (298 loc) · 10.3 KB
/
node.bittrex.api.js
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
/* ============================================================
* node.bittrex.api
* https://github.com/n0mad01/node.bittrex.api
*
* ============================================================
* Copyright 2014-2017, Adrian Soluch - http://soluch.us/
* Released under the MIT License
* ============================================================ */
var NodeBittrexApi = function() {
'use strict';
var request = require('request'),
assign = require('object-assign'),
hmac_sha512 = require('./hmac-sha512.js'),
JSONStream = require('JSONStream'),
es = require('event-stream'),
jsonic = require('jsonic'),
signalR = require('signalr-client'),
wsclient;
var default_request_options = {
method: 'GET',
agent: false,
headers: {
'User-Agent': 'Mozilla/4.0 (compatible; Node Bittrex API)',
'Content-type': 'application/x-www-form-urlencoded'
}
};
var opts = {
baseUrl: 'https://bittrex.com/api/v1.1',
baseUrlv2: 'https://bittrex.com/Api/v2.0',
websockets_baseurl: 'wss://socket.bittrex.com/signalr',
websockets_hubs: ['CoreHub'],
apikey: 'APIKEY',
apisecret: 'APISECRET',
verbose: false,
cleartext: false,
stream: false,
inverse_callback_arguments: false,
};
var getNonce = function() {
return Math.floor(new Date().getTime() / 1000);
};
var extractOptions = function(options) {
var o = Object.keys(options),
i;
for (i = 0; i < o.length; i++) {
opts[o[i]] = options[o[i]];
}
};
var apiCredentials = function(uri) {
var options = {
apikey: opts.apikey,
nonce: getNonce()
};
return setRequestUriGetParams(uri, options);
};
var setRequestUriGetParams = function(uri, options) {
var op;
if (typeof(uri) === 'object') {
op = uri;
uri = op.uri;
} else {
op = assign({}, default_request_options);
}
var o = Object.keys(options),
i;
for (i = 0; i < o.length; i++) {
uri = updateQueryStringParameter(uri, o[i], options[o[i]]);
}
op.headers.apisign = hmac_sha512.HmacSHA512(uri, opts.apisecret); // setting the HMAC hash `apisign` http header
op.uri = uri;
return op;
};
var updateQueryStringParameter = function(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
uri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
uri = uri + separator + key + "=" + value;
}
return uri;
};
var sendRequestCallback = function(callback, op) {
var start = Date.now();
switch (opts.stream) {
case true:
request(op)
.pipe(JSONStream.parse('*'))
.pipe(es.mapSync(function(data) {
callback(data);
((opts.verbose) ? console.log("streamed from " + op.uri + " in: %ds", (Date.now() - start) / 1000) : '');
}));
break;
case false:
request(op, function(error, result, body) {
((opts.verbose) ? console.log("requested from " + op.uri + " in: %ds", (Date.now() - start) / 1000) : '');
if (!body || !result || result.statusCode != 200) {
var errorObj = {
success: false,
message: 'URL request error',
error: error,
result: result,
};
return ((opts.inverse_callback_arguments) ?
callback(errorObj, null) :
callback(null, errorObj));
} else {
result = JSON.parse(body);
if (!result.success) {
// error returned by bittrex API - forward the result as an error
return ((opts.inverse_callback_arguments) ?
callback(result, null) :
callback(null, result));
}
return ((opts.inverse_callback_arguments) ?
callback(null, ((opts.cleartext) ? body : result)) :
callback(((opts.cleartext) ? body : result), null));
}
});
break;
}
};
var publicApiCall = function(url, callback, options) {
var op = assign({}, default_request_options);
if (!options) {
op.uri = url;
}
sendRequestCallback(callback, (!options) ? op : setRequestUriGetParams(url, options));
};
var credentialApiCall = function(url, callback, options) {
if (options) {
options = setRequestUriGetParams(apiCredentials(url), options);
}
sendRequestCallback(callback, options);
};
var connectws = function(callback) {
wsclient = new signalR.client(
opts.websockets_baseurl,
opts.websockets_hubs
);
wsclient.serviceHandlers = {
bound: function() {
((opts.verbose) ? console.log('Websocket bound') : '');
},
connectFailed: function(error) {
((opts.verbose) ? console.log('Websocket connectFailed: ', error) : '');
},
disconnected: function() {
((opts.verbose) ? console.log('Websocket disconnected') : '');
},
onerror: function(error) {
((opts.verbose) ? console.log('Websocket onerror: ', error) : '');
},
bindingError: function(error) {
((opts.verbose) ? console.log('Websocket bindingError: ', error) : '');
},
connectionLost: function(error) {
((opts.verbose) ? console.log('Connection Lost: ', error) : '');
},
reconnecting: function(retry) {
((opts.verbose) ? console.log('Websocket Retrying: ', retry) : '');
// change to true to stop retrying
return false;
}
};
return wsclient;
};
var setMessageReceivedWs = function(callback) {
wsclient.serviceHandlers.messageReceived = function(message) {
try {
var data = jsonic(message.utf8Data);
if (data && data.M) {
data.M.forEach(function(M) {
callback(M);
});
} else {
// ((opts.verbose) ? console.log('Unhandled data', data) : '');
callback({'unhandled_data' : data});
}
} catch (e) {
((opts.verbose) ? console.error(e) : '');
}
return false;
};
};
var setConnectedWs = function(markets) {
wsclient.serviceHandlers.connected = function(connection) {
markets.forEach(function(market) {
wsclient.call('CoreHub', 'SubscribeToExchangeDeltas', market).done(function(err, result) {
if (err) {
return console.error(err);
}
if (result === true) {
((opts.verbose) ? console.log('Subscribed to ' + market) : '');
}
});
});
((opts.verbose) ? console.log('Websocket connected') : '');
};
};
return {
options: function(options) {
extractOptions(options);
},
websockets: {
client: function(callback) {
return connectws();
},
listen: function(callback) {
var client = connectws();
setMessageReceivedWs(callback);
return client;
},
subscribe: function(markets, callback) {
var client = connectws();
setConnectedWs(markets);
setMessageReceivedWs(callback);
return client;
}
},
sendCustomRequest: function(request_string, callback, credentials) {
var op;
if (credentials === true) {
op = apiCredentials(request_string);
} else {
op = assign({}, default_request_options, { uri: request_string });
}
sendRequestCallback(callback, op);
},
getmarkets: function(callback) {
publicApiCall(opts.baseUrl + '/public/getmarkets', callback, null);
},
getcurrencies: function(callback) {
publicApiCall(opts.baseUrl + '/public/getcurrencies', callback, null);
},
getticker: function(options, callback) {
publicApiCall(opts.baseUrl + '/public/getticker', callback, options);
},
getmarketsummaries: function(callback) {
publicApiCall(opts.baseUrl + '/public/getmarketsummaries', callback, null);
},
getmarketsummary: function(options, callback) {
publicApiCall(opts.baseUrl + '/public/getmarketsummary', callback, options);
},
getorderbook: function(options, callback) {
publicApiCall(opts.baseUrl + '/public/getorderbook', callback, options);
},
getmarkethistory: function(options, callback) {
publicApiCall(opts.baseUrl + '/public/getmarkethistory', callback, options);
},
getcandles: function(options, callback) {
publicApiCall(opts.baseUrlv2 + '/pub/market/GetTicks', callback, options);
},
buylimit: function(options, callback) {
credentialApiCall(opts.baseUrl + '/market/buylimit', callback, options);
},
buymarket: function(options, callback) {
credentialApiCall(opts.baseUrl + '/market/buymarket', callback, options);
},
selllimit: function(options, callback) {
credentialApiCall(opts.baseUrl + '/market/selllimit', callback, options);
},
sellmarket: function(options, callback) {
credentialApiCall(opts.baseUrl + '/market/sellmarket', callback, options);
},
cancel: function(options, callback) {
credentialApiCall(opts.baseUrl + '/market/cancel', callback, options);
},
getopenorders: function(options, callback) {
credentialApiCall(opts.baseUrl + '/market/getopenorders', callback, options);
},
getbalances: function(callback) {
credentialApiCall(opts.baseUrl + '/account/getbalances', callback, {});
},
getbalance: function(options, callback) {
credentialApiCall(opts.baseUrl + '/account/getbalance', callback, options);
},
getwithdrawalhistory: function(options, callback) {
credentialApiCall(opts.baseUrl + '/account/getwithdrawalhistory', callback, options);
},
getdepositaddress: function(options, callback) {
credentialApiCall(opts.baseUrl + '/account/getdepositaddress', callback, options);
},
getdeposithistory: function(options, callback) {
credentialApiCall(opts.baseUrl + '/account/getdeposithistory', callback, options);
},
getorderhistory: function(options, callback) {
credentialApiCall(opts.baseUrl + '/account/getorderhistory', callback, options || {});
},
getorder: function(options, callback) {
credentialApiCall(opts.baseUrl + '/account/getorder', callback, options);
},
withdraw: function(options, callback) {
credentialApiCall(opts.baseUrl + '/account/withdraw', callback, options);
}
};
}();
module.exports = NodeBittrexApi;