-
Notifications
You must be signed in to change notification settings - Fork 0
/
binance_rest.js
389 lines (345 loc) · 12.8 KB
/
binance_rest.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
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
"use strict"
// binanceRequest is used to get an axios instance with default url and default header
let binanceRequest = require('./request');
const { format, checkEnum, print } = require('./utils');
const axios = require("axios");
const getSignature = require('./signature');
const fs = require('fs');
const debug = true;
class Binance {
constructor(config = {}) {
this.api = this.checkKey(config.api) // check of the apikey format
this.secret = this.checkKey(config.secret) // check of the secret key format
this.request = binanceRequest(config);
}
getRequest() {
return this.request;
}
checkKey(key) {
if (key && typeof key === "string" && key.length === 64) {
return key;
} else if (key){
throw new SyntaxError(["Bad key format", key].join(" "));
} else {
return null;
}
}
checkParams(data, required){
if (!data || typeof data !== "object") {
throw new SyntaxError("data args is required and should be an object")
}
if (!required || !Array.isArray(required)) {
throw new SyntaxError("required args is required and should be an array")
}
// we iterate on the required params array
required.map((req)=>{
if (!data[req]) {// if the param is not provided in the data object provided to the function
throw new SyntaxError(req+" parameters is required for this method") // we throw an error
}
})
for (let key in data) {
let value = data[key]
switch (key){
case 'symbol':
case 'newClientOrderId':
case 'origClientOrderId':
case 'listenKey':
if (typeof value !== "string") {
throw new TypeError(key+" should be a string")
}
break;
//check for the enum type
case 'side':
checkEnum(["BUY", "SELL"], value, key)
break;
case 'type':
checkEnum(["LIMIT", "MARKET"], value, key)
break;
case 'timeInForce':
checkEnum(["GTC", "IOC"], value, key)
break;
case 'quantity':
case 'price':
//TODO validate float as string
break;
case 'orderId':
case 'stopPrice':
case 'icebergQty':
case 'recvWindow':
case 'fromId':
if (typeof value !== "number") {
throw new TypeError(key+" should be a number")
}
break;
}
}
return null
}
async get_ticker(symbol) {
try {
const url = 'api/v1/ticker/24hr';
const { data } = await this.request.get(url, { params : { symbol: symbol }});
return data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async get_order_book(symbol, limit = 50) {
try {
const url = 'api/v1/depth';
const { data } = await this.request.get(url, { params : { symbol: symbol, limit: limit} });
return data;
} catch (err) {
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async get_exchange_info(symbol) {
try {
const url = 'api/v1/exchangeInfo';
const { data } = await this.request.get(url);
return data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async buy_limit(market, quantity, rate){
try {
let params = {}
params.symbol = market;
params.side = "BUY";
params.type = "LIMIT";
params.timeInForce = "GTC"
params.quantity = format(quantity)
params.price = format(rate)
this.signedMethod() // secret and api key required for this method
this.checkParams(params, ["symbol", "side", "type", "timeInForce", "quantity", "price"]) // data required in the params object
const url = "api/v3/order"
let query = this.makeQuery(url, params);
//console.log(query);
const resp = await this.request.post(query);
return resp.data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async query_order(symbol, orderId){
try {
this.signedMethod() // secret and api key required for this method
let params = {}
params.symbol = symbol;
params.orderId = orderId;
this.checkParams(params, ["symbol", "orderId"]) // data required in the params object
const url = 'api/v3/order';
let query = this.makeQuery(url, params);
//console.log(query);
const resp = await this.request.get(query);
return resp.data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async allOrders(params = {}){
try {
this.signedMethod() // secret and api key required for this method
this.checkParams(params, ["symbol"]) // data required in the params object
const url = "api/v3/allOrders"
let query = this.makeQuery(url, params);
const resp = await this.request.get(query);
return resp.data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async openOrders(params = {}){
try {
this.signedMethod() // secret and api key required for this method
const url = "api/v3/openOrders"
let query = this.makeQuery(url, params);
const resp = await this.request.get(query);
return resp.data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
apiRequired(){
if (!this.api) {
throw new SyntaxError("API key is required for this method")
}
}
signedMethod(){ //function word because we need to bind "this" context
this.apiRequired()
if (!this.secret) {
throw new SyntaxError("Secret key is required for this method")
}
}
makeQuery(url, dataQuery = {}, timestamp = -1) {
this.signedMethod()
if (!url || typeof url !== "string") {
throw "Url is missing and should be a string"
}
if (!dataQuery || typeof dataQuery !== "object") {
throw "Object type required for data param"
}
if (dataQuery.timestamp) {
delete dataQuery.timestamp
}
if (this.timeout)
dataQuery.recvWindow=timeout;
const query = Object.keys(dataQuery).map((key)=> {
return key+"="+dataQuery[key]
})
let now = Date.now() // for unit testing we set a static timestamp
if (timestamp != -1) {
now = timestamp
}
const queryTimeStamp = [ query.join('&'), "×tamp="+now ].join("")
return [ url, "?", queryTimeStamp, "&signature="+getSignature(queryTimeStamp, this.secret) ].join("")
}
async cancel(market, order_id){
try {
this.signedMethod() // secret and api key required for this method
let params = {}
params.symbol = market;
params.orderId = order_id;
this.checkParams(params, ["symbol", "orderId"]) // data required in the params object
const url = 'api/v3/order';
let query = this.makeQuery(url, params);
const resp = await this.request.delete(query);
return resp.data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async sell_limit(market, quantity, rate){
try {
let params = {}
params.symbol = market;
params.side = "SELL";
params.type = "LIMIT";
params.timeInForce = "GTC"
params.quantity = format(quantity)
params.price = format(rate)
this.signedMethod() // secret and api key required for this method
this.checkParams(params, ["symbol", "side", "type", "timeInForce", "quantity", "price"]) // data required in the params object
const url = "api/v3/order"
let query = this.makeQuery(url, params);
//console.log(query);
const resp = await this.request.post(query);
return resp.data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async sell_market(market, quantity){
try {
let params = {}
params.symbol = market;
params.side = "SELL";
params.type = "MARKET";
params.quantity = format(quantity)
this.signedMethod() // secret and api key required for this method
this.checkParams(params, ["symbol", "side", "type", "timeInForce", "quantity"]) // data required in the params object
const url = "api/v3/order"
let query = this.makeQuery(url, params);
console.log(query);
const resp = await this.request.post(query);
return resp.data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async get_products() {
try {
const url = "exchange/public/product"
const { data } = await this.request.get(url);
return data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
async get_account() {
try {
let params = {};
this.signedMethod() // secret and api key required for this method
const url = "api/v3/account"
let query = this.makeQuery(url, params);
const resp = await this.request.get(query);
return resp.data;
} catch (err){
if (debug) {
console.log(err);
}
if (err && err.response && err.response.data && err.response.data.msg){
print("Error Message: %s", err.response.data.msg);
}
throw err;
}
}
}
module.exports = Binance;