-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathrest2.js.html
More file actions
2028 lines (1807 loc) · 75.9 KB
/
Copy pathrest2.js.html
File metadata and controls
2028 lines (1807 loc) · 75.9 KB
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>rest2.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
<script src="scripts/nav.js" defer></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav >
<input type="text" id="nav-search" placeholder="Search" />
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="RESTv1.html">RESTv1</a><ul class='methods'><li data-type='method'><a href="RESTv1.html#account_infos">account_infos</a></li><li data-type='method'><a href="RESTv1.html#active_credits">active_credits</a></li><li data-type='method'><a href="RESTv1.html#active_offers">active_offers</a></li><li data-type='method'><a href="RESTv1.html#active_orders">active_orders</a></li><li data-type='method'><a href="RESTv1.html#active_positions">active_positions</a></li><li data-type='method'><a href="RESTv1.html#balance_history">balance_history</a></li><li data-type='method'><a href="RESTv1.html#cancel_all_orders">cancel_all_orders</a></li><li data-type='method'><a href="RESTv1.html#cancel_multiple_orders">cancel_multiple_orders</a></li><li data-type='method'><a href="RESTv1.html#cancel_offer">cancel_offer</a></li><li data-type='method'><a href="RESTv1.html#cancel_order">cancel_order</a></li><li data-type='method'><a href="RESTv1.html#claim_position">claim_position</a></li><li data-type='method'><a href="RESTv1.html#close_swap">close_swap</a></li><li data-type='method'><a href="RESTv1.html#fundingbook">fundingbook</a></li><li data-type='method'><a href="RESTv1.html#get_symbols">get_symbols</a></li><li data-type='method'><a href="RESTv1.html#lends">lends</a></li><li data-type='method'><a href="RESTv1.html#margin_infos">margin_infos</a></li><li data-type='method'><a href="RESTv1.html#movements">movements</a></li><li data-type='method'><a href="RESTv1.html#multiple_new_orders">multiple_new_orders</a></li><li data-type='method'><a href="RESTv1.html#new_deposit">new_deposit</a></li><li data-type='method'><a href="RESTv1.html#new_offer">new_offer</a></li><li data-type='method'><a href="RESTv1.html#new_order">new_order</a></li><li data-type='method'><a href="RESTv1.html#offer_status">offer_status</a></li><li data-type='method'><a href="RESTv1.html#order_status">order_status</a></li><li data-type='method'><a href="RESTv1.html#orderbook">orderbook</a></li><li data-type='method'><a href="RESTv1.html#orders_history">orders_history</a></li><li data-type='method'><a href="RESTv1.html#past_trades">past_trades</a></li><li data-type='method'><a href="RESTv1.html#replace_order">replace_order</a></li><li data-type='method'><a href="RESTv1.html#stats">stats</a></li><li data-type='method'><a href="RESTv1.html#symbols_details">symbols_details</a></li><li data-type='method'><a href="RESTv1.html#taken_swaps">taken_swaps</a></li><li data-type='method'><a href="RESTv1.html#ticker">ticker</a></li><li data-type='method'><a href="RESTv1.html#today">today</a></li><li data-type='method'><a href="RESTv1.html#total_taken_swaps">total_taken_swaps</a></li><li data-type='method'><a href="RESTv1.html#trades">trades</a></li><li data-type='method'><a href="RESTv1.html#transfer">transfer</a></li><li data-type='method'><a href="RESTv1.html#wallet_balances">wallet_balances</a></li><li data-type='method'><a href="RESTv1.html#withdraw">withdraw</a></li></ul></li><li><a href="RESTv2.html">RESTv2</a><ul class='methods'><li data-type='method'><a href="RESTv2.html#accountFees">accountFees</a></li><li data-type='method'><a href="RESTv2.html#accountSummary">accountSummary</a></li><li data-type='method'><a href="RESTv2.html#accountTrades">accountTrades</a></li><li data-type='method'><a href="RESTv2.html#activeOrders">activeOrders</a></li><li data-type='method'><a href="RESTv2.html#activeOrdersWithIds">activeOrdersWithIds</a></li><li data-type='method'><a href="RESTv2.html#alertDelete">alertDelete</a></li><li data-type='method'><a href="RESTv2.html#alertList">alertList</a></li><li data-type='method'><a href="RESTv2.html#alertSet">alertSet</a></li><li data-type='method'><a href="RESTv2.html#calcAvailableBalance">calcAvailableBalance</a></li><li data-type='method'><a href="RESTv2.html#cancelAllFundingOffers">cancelAllFundingOffers</a></li><li data-type='method'><a href="RESTv2.html#cancelFundingOffer">cancelFundingOffer</a></li><li data-type='method'><a href="RESTv2.html#cancelOrder">cancelOrder</a></li><li data-type='method'><a href="RESTv2.html#cancelOrderMulti">cancelOrderMulti</a></li><li data-type='method'><a href="RESTv2.html#cancelOrderWithCid">cancelOrderWithCid</a></li><li data-type='method'><a href="RESTv2.html#cancelOrders">cancelOrders</a></li><li data-type='method'><a href="RESTv2.html#cancelRecurringAlgoOrder">cancelRecurringAlgoOrder</a></li><li data-type='method'><a href="RESTv2.html#candles">candles</a></li><li data-type='method'><a href="RESTv2.html#changeLogs">changeLogs</a></li><li data-type='method'><a href="RESTv2.html#claimPosition">claimPosition</a></li><li data-type='method'><a href="RESTv2.html#closeFunding">closeFunding</a></li><li data-type='method'><a href="RESTv2.html#closePosition">closePosition</a></li><li data-type='method'><a href="RESTv2.html#conf">conf</a></li><li data-type='method'><a href="RESTv2.html#currencies">currencies</a></li><li data-type='method'><a href="RESTv2.html#deleteSettings">deleteSettings</a></li><li data-type='method'><a href="RESTv2.html#derivsPositionCollateralSet">derivsPositionCollateralSet</a></li><li data-type='method'><a href="RESTv2.html#exchangeRate">exchangeRate</a></li><li data-type='method'><a href="RESTv2.html#fundingCreditHistory">fundingCreditHistory</a></li><li data-type='method'><a href="RESTv2.html#fundingCredits">fundingCredits</a></li><li data-type='method'><a href="RESTv2.html#fundingInfo">fundingInfo</a></li><li data-type='method'><a href="RESTv2.html#fundingLoanHistory">fundingLoanHistory</a></li><li data-type='method'><a href="RESTv2.html#fundingLoans">fundingLoans</a></li><li data-type='method'><a href="RESTv2.html#fundingOfferHistory">fundingOfferHistory</a></li><li data-type='method'><a href="RESTv2.html#fundingOffers">fundingOffers</a></li><li data-type='method'><a href="RESTv2.html#fundingTrades">fundingTrades</a></li><li data-type='method'><a href="RESTv2.html#futures">futures</a></li><li data-type='method'><a href="RESTv2.html#generateInvoice">generateInvoice</a></li><li data-type='method'><a href="RESTv2.html#generateToken">generateToken</a></li><li data-type='method'><a href="RESTv2.html#getCoreSettings">getCoreSettings</a></li><li data-type='method'><a href="RESTv2.html#getDepositAddress">getDepositAddress</a></li><li data-type='method'><a href="RESTv2.html#getRecurringAlgoOrder">getRecurringAlgoOrder</a></li><li data-type='method'><a href="RESTv2.html#getRecurringAlgoOrders">getRecurringAlgoOrders</a></li><li data-type='method'><a href="RESTv2.html#getRecurringAoOrders">getRecurringAoOrders</a></li><li data-type='method'><a href="RESTv2.html#getSettings">getSettings</a></li><li data-type='method'><a href="RESTv2.html#getURL">getURL</a></li><li data-type='method'><a href="RESTv2.html#getWeightedAverages">getWeightedAverages</a></li><li data-type='method'><a href="RESTv2.html#inactiveSymbols">inactiveSymbols</a></li><li data-type='method'><a href="RESTv2.html#invalidateAuthToken">invalidateAuthToken</a></li><li data-type='method'><a href="RESTv2.html#keepFunding">keepFunding</a></li><li data-type='method'><a href="RESTv2.html#keyPermissions">keyPermissions</a></li><li data-type='method'><a href="RESTv2.html#ledgers">ledgers</a></li><li data-type='method'><a href="RESTv2.html#liquidations">liquidations</a></li><li data-type='method'><a href="RESTv2.html#lnxInvoicePayments">lnxInvoicePayments</a></li><li data-type='method'><a href="RESTv2.html#logins">logins</a></li><li data-type='method'><a href="RESTv2.html#marginInfo">marginInfo</a></li><li data-type='method'><a href="RESTv2.html#marketAveragePrice">marketAveragePrice</a></li><li data-type='method'><a href="RESTv2.html#movementInfo">movementInfo</a></li><li data-type='method'><a href="RESTv2.html#movements">movements</a></li><li data-type='method'><a href="RESTv2.html#orderBook">orderBook</a></li><li data-type='method'><a href="RESTv2.html#orderHistory">orderHistory</a></li><li data-type='method'><a href="RESTv2.html#orderHistoryWithIds">orderHistoryWithIds</a></li><li data-type='method'><a href="RESTv2.html#orderMultiOp">orderMultiOp</a></li><li data-type='method'><a href="RESTv2.html#orderTrades">orderTrades</a></li><li data-type='method'><a href="RESTv2.html#performance">performance</a></li><li data-type='method'><a href="RESTv2.html#positions">positions</a></li><li data-type='method'><a href="RESTv2.html#positionsAudit">positionsAudit</a></li><li data-type='method'><a href="RESTv2.html#positionsHistory">positionsHistory</a></li><li data-type='method'><a href="RESTv2.html#positionsSnapshot">positionsSnapshot</a></li><li data-type='method'><a href="RESTv2.html#stats">stats</a></li><li data-type='method'><a href="RESTv2.html#status">status</a></li><li data-type='method'><a href="RESTv2.html#statusMessages">statusMessages</a></li><li data-type='method'><a href="RESTv2.html#submitAutoFunding">submitAutoFunding</a></li><li data-type='method'><a href="RESTv2.html#submitFundingOffer">submitFundingOffer</a></li><li data-type='method'><a href="RESTv2.html#submitOrder">submitOrder</a></li><li data-type='method'><a href="RESTv2.html#submitOrderMulti">submitOrderMulti</a></li><li data-type='method'><a href="RESTv2.html#submitRecurringAlgoOrder">submitRecurringAlgoOrder</a></li><li data-type='method'><a href="RESTv2.html#symbolDetails">symbolDetails</a></li><li data-type='method'><a href="RESTv2.html#symbols">symbols</a></li><li data-type='method'><a href="RESTv2.html#ticker">ticker</a></li><li data-type='method'><a href="RESTv2.html#tickers">tickers</a></li><li data-type='method'><a href="RESTv2.html#tickersHistory">tickersHistory</a></li><li data-type='method'><a href="RESTv2.html#trades">trades</a></li><li data-type='method'><a href="RESTv2.html#transfer">transfer</a></li><li data-type='method'><a href="RESTv2.html#updateOrder">updateOrder</a></li><li data-type='method'><a href="RESTv2.html#updateOrderMulti">updateOrderMulti</a></li><li data-type='method'><a href="RESTv2.html#updateRecurringAlgoOrder">updateRecurringAlgoOrder</a></li><li data-type='method'><a href="RESTv2.html#updateSettings">updateSettings</a></li><li data-type='method'><a href="RESTv2.html#userInfo">userInfo</a></li><li data-type='method'><a href="RESTv2.html#usesAgent">usesAgent</a></li><li data-type='method'><a href="RESTv2.html#wallets">wallets</a></li><li data-type='method'><a href="RESTv2.html#walletsHistory">walletsHistory</a></li><li data-type='method'><a href="RESTv2.html#withdraw">withdraw</a></li></ul></li></ul><h3><a href="global.html">Global</a></h3>
</nav>
<div id="main">
<h1 class="page-title">rest2.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>'use strict'
const debug = require('debug')('bfx:rest2')
const fetch = require('node-fetch')
const _isEmpty = require('lodash/isEmpty')
const _isString = require('lodash/isString')
const _isFunction = require('lodash/isFunction')
const _pick = require('lodash/pick')
const _omitBy = require('lodash/omitBy')
const _isNil = require('lodash/isNil')
const _isInteger = require('lodash/isInteger')
const _flatten = require('lodash/flatten')
const { URLSearchParams } = require('url')
const { genAuthSig, nonce, isClass } = require('bfx-api-node-util')
const {
FundingCredit,
FundingLoan,
FundingOffer,
FundingTrade,
MarginInfo,
Order,
Position,
Trade,
PublicTrade,
TradingTicker,
TradingTickerHist,
FundingTicker,
FundingTickerHist,
Wallet,
WalletHist,
Alert,
Candle,
Movement,
MovementInfo,
LedgerEntry,
Liquidations,
UserInfo,
Currency,
StatusMessagesDeriv,
Notification,
Login,
ChangeLog,
Invoice,
SymbolDetails,
TransactionFee,
AccountSummary,
AuthPermission,
CoreSettings,
WeightedAverages
} = require('bfx-api-node-models')
const BASE_TIMEOUT = 15000
const API_URL = 'https://api.bitfinex.com'
/**
* Parses response into notification object
*
* @param {object} data - notification
* @returns {Notification} n
* @private
*/
function _takeResNotify (data) {
const notification = new Notification(data)
return notification
}
/**
* Communicates with v2 of the Bitfinex HTTP API
*/
class RESTv2 {
/**
* Instantiate a new REST v2 transport.
*
* @param {object} opts - options
* @param {string} [opts.affCode] - affiliate code to be applied to all orders
* @param {string} [opts.apiKey] - API key
* @param {string} [opts.apiSecret] - API secret
* @param {string} [opts.authToken] - optional auth option
* @param {string} [opts.url] - endpoint URL
* @param {boolean} [opts.transform] - default false
* @param {object} [opts.agent] - optional node agent for connection (proxy)
* @param {number} [opts.timeout] - default 15000
*/
constructor (opts = {
affCode: null,
apiKey: '',
apiSecret: '',
authToken: '',
company: '',
url: API_URL,
transform: false,
agent: null,
timeout: BASE_TIMEOUT
}) {
this._checkOpts(opts)
this._url = opts.url || API_URL
this._apiKey = opts.apiKey || ''
this._apiSecret = opts.apiSecret || ''
this._authToken = opts.authToken || ''
this._company = opts.company || ''
this._transform = !!opts.transform
this._agent = opts.agent
this._affCode = opts.affCode
this._timeout = _isInteger(opts.timeout)
? opts.timeout
: BASE_TIMEOUT
}
/**
* Check constructor options
*
* @param {object} opts - constructor options
* @throws {Error} - throws an Error if check is not passed
* @returns {undefined}
* @private
*/
_checkOpts (opts) {
if (
!_isNil(opts.timeout) &&
!_isInteger(opts.timeout)
) {
throw new Error('ERR_TIMEOUT_DATA_TYPE_ERROR')
}
}
/**
* @returns {boolean} url
*/
getURL () {
return this._url
}
/**
* @returns {boolean} usesAgent
*/
usesAgent () {
return !!this._agent
}
async _request (url, reqOpts, transformer, cb) {
try {
const resp = await fetch(url, reqOpts)
const raw = await resp.text()
if (!resp.ok) {
const err = this._apiError(resp, raw)
throw err
}
const json = JSON.parse(raw)
return this._response(json, transformer, cb)
} catch (err) {
return this._cb(err, null, cb)
}
}
_apiError (resp, rawBody) {
const err = new Error(`HTTP code ${resp.status} ${resp.statusText || ''}`)
err.status = resp.status
err.statustext = resp.statusText
try {
const [, code, response] = JSON.parse(rawBody)
err.code = code
err.response = response
} catch (_err) {
err.response = rawBody
}
return err
}
/**
* @param {string} path - path
* @param {object} payload - payload
* @param {Function} [cb] - legacy callback
* @param {object|Function} transformer - model class or function
* @returns {Promise} p
* @private
*/
async _makeAuthRequest (path, payload = {}, cb, transformer) {
if ((!this._apiKey || !this._apiSecret) && !this._authToken) {
const e = new Error('missing api key or secret')
return this._cb(e, null, cb)
}
const url = `${this._url}/v2${path}`
const n = nonce()
const sanitizedPayload = _omitBy(payload, _isNil)
const keys = () => {
const sigPayload = `/api/v2${path}${n}${JSON.stringify(sanitizedPayload)}`
const { sig } = genAuthSig(this._apiSecret, sigPayload)
return { 'bfx-apikey': this._apiKey, 'bfx-signature': sig }
}
const auth = (this._authToken)
? { 'bfx-token': this._authToken }
: keys()
debug('POST %s', url)
const reqOpts = {
method: 'POST',
timeout: this._timeout,
headers: {
'content-type': 'application/json',
'bfx-nonce': n,
...auth
},
agent: this._agent,
body: JSON.stringify(sanitizedPayload)
}
return this._request(url, reqOpts, transformer, cb)
}
/**
* @param {string} path - path
* @param {Function} [cb] - legacy callback
* @param {object|Function} transformer - model class or function
* @returns {Promise} p
* @private
*/
async _makePublicRequest (path, cb, transformer) {
if ((cb !== null && cb !== undefined) && typeof cb !== 'function') {
throw new Error('_makePublicRequest cb param must be a function')
}
const url = `${this._url}/v2${path}`
debug('GET %s', url)
const reqOpts = {
method: 'GET',
timeout: this._timeout,
agent: this._agent
}
return this._request(url, reqOpts, transformer, cb)
}
/**
* @param {string} path - path
* @param {object} body - payload
* @param {Function} [cb] - legacy callback
* @param {object|Function} transformer - model class or function
* @returns {Promise} p
* @private
*/
async _makePublicPostRequest (path, payload, cb, transformer) {
const url = `${this._url}/v2${path}`
debug('POST %s', url)
const sanitizedPayload = _omitBy(payload, _isNil)
const reqOpts = {
method: 'POST',
timeout: this._timeout,
headers: {
'content-type': 'application/json'
},
agent: this._agent,
body: JSON.stringify(sanitizedPayload)
}
return this._request(url, reqOpts, transformer, cb)
}
/**
* @param {object} data
* @param {object|Function} transformer - model class or function
* @returns {object|object[]} finalData
* @private
*/
_doTransform (data, transformer) {
if (isClass(transformer)) {
return this._classTransform(data, transformer)
} else if (_isFunction(transformer)) {
return transformer(data)
} else {
return data
}
}
/**
* @param {object} data - data
* @param {object} ModelClass - class
* @returns {object|object[]} finalData
* @private
*/
_classTransform (data, ModelClass) {
if (!data || data.length === 0) return []
if (!ModelClass || !this._transform) return data
if (Array.isArray(data[0])) {
return data.map(row => new ModelClass(row, this))
}
return new ModelClass(data, this)
}
/**
* @param {object} data - data
* @param {object|Function} transformer - model class or function
* @param {Function} [cb] - legacy callback
* @returns {Promise<object|object[]>} finalData
* @private
*/
_response (data, transformer, cb) {
try {
const res = (this._transform)
? this._doTransform(data, transformer)
: data
return this._cb(null, res, cb)
} catch (e) {
return this._cb(e, null, cb)
}
}
/**
* @param {Error} err - error
* @param {object} res -resposne
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @private
*/
_cb (err, res, cb) {
const _isCbFunc = _isFunction(cb)
if (err) {
if (err.error && err.error[1] === 10114) {
err.message += ' see https://github.com/bitfinexcom/bitfinex-api-node/blob/master/README.md#nonce-too-small for help'
}
return _isCbFunc ? cb(err) : Promise.reject(err)
}
return _isCbFunc ? cb(null, res) : Promise.resolve(res)
}
/**
* @param {Array[]} data order matters
* @returns {Array[]} merged arr of currencies and names sorted with no pairs repeated adding pool and explorer to each
* @private
*/
_genCurrencyList (data) {
if (!Array.isArray(data) || data.length !== 6) {
return data
}
const transformArrToObj = (arr) => {
const obj = {}
arr.forEach((c) => {
if (!Array.isArray(c)) {
obj[c] = c
} else if (c.length > 1) {
obj[c[0]] = c[1]
}
})
return obj
}
const listedCurr = transformArrToObj(data[0])
const mapedCurrSym = transformArrToObj(data[1])
const mapedCurrLabel = transformArrToObj(data[2])
const pool = transformArrToObj(data[3])
const explorer = transformArrToObj(data[4])
const walletFx = transformArrToObj(data[5])
const allCurrObj = {
...listedCurr,
...mapedCurrSym,
...mapedCurrLabel
}
// Assigne explores of pool to currencies
Object.keys(pool).forEach((key) => {
if (!explorer[key]) {
if (explorer[pool[key]]) {
explorer[key] = explorer[pool[key]]
}
}
})
const allCurArr = []
Object.keys(allCurrObj).forEach((key) => {
const cPool = pool[key] || null
const cExpl = explorer[key] || []
const cName = allCurrObj[key]
const cSymbol = mapedCurrSym[key] || key
const cWfx = walletFx[key] || []
allCurArr.push([key, cName, cPool, cExpl, cSymbol, cWfx])
})
return allCurArr
}
/**
* @param {object} params - parameters
* @param {string} params.symbol - i.e. tBTCUSD
* @param {string} params.prec - i.e. P0
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-books
*/
orderBook (params, cb = null) {
const { symbol, prec } = params
return this._makePublicRequest(`/book/${symbol}/${prec}`, cb)
}
/**
* @param {object} params - parameters
* @param {string} params.symbol - Symbol you want information about i.e tBTCUSD, fUSD
* @param {string} params.amount - Amount. Positive for buy, negative for sell (ex. "1.123")
* @param {string} [params.period] - (optional) Maximum period for Margin Funding
* @param {string} [params.rate_limit] - Limit rate/price (ex. "1000.5")
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/reference#rest-public-calc-market-average-price
*/
marketAveragePrice (params, cb = null) {
const usp = new URLSearchParams(params)
return this._makePublicPostRequest(`/calc/trade/avg?${usp.toString()}`, {}, cb)
}
/**
* @param {object} [params] - parameters
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-platform-status
*/
status (params = {}, cb = null) {
return this._makePublicRequest('/platform/status', cb)
}
/**
* @param {object} [params] - parameters
* @param {string} [params.type] - type
* @param {string[]} [params.keys] - keys
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#status
*/
statusMessages (params = {}, cb = null) {
const { type = 'deriv', keys = ['ALL'] } = params
const url = `/status/${type}?keys=${keys.join(',')}`
const transformer = (type === 'deriv') ? StatusMessagesDeriv : null
return this._makePublicRequest(url, cb, transformer)
}
/**
* @param {object} params - parameters
* @param {string} params.symbol - symbol
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-ticker
*/
ticker (params, cb = null) {
const { symbol } = params
const transformer = (data) => {
const ticker = [symbol, ...data]
return (symbol[0] === 't')
? new TradingTicker(ticker)
: new FundingTicker(ticker)
}
return this._makePublicRequest(`/ticker/${symbol}`, cb, transformer)
}
/**
* @param {object} [params] - parameters
* @param {string[]} [params.symbols] - symbols
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-tickers
*/
tickers (params = {}, cb = null) {
const { symbols = [] } = params
const transformer = (data) => {
return data.map(ticker => (
(ticker[0] || '')[0] === 't'
? new TradingTicker(ticker)
: new FundingTicker(ticker)
))
}
const url = `/tickers?symbols=${symbols.length ? symbols.join(',') : 'ALL'}`
return this._makePublicRequest(url, cb, transformer)
}
/**
* @param {object} [params] - parameters
* @param {string[]} [params.symbols] - symbols
* @param {number} [params.start] - query start timestamp
* @param {number} [params.end] - query end timestamp
* @param {number} [params.limit] - query limit
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-tickers-history
*/
tickersHistory (params = {}, cb = null) {
const { symbols = [], start, end, limit = 250 } = params
const transformer = (data) => {
return data.map(ticker => (
(ticker[0] || '')[0] === 't'
? new TradingTickerHist(ticker)
: new FundingTickerHist(ticker)
))
}
const s = (start) ? `&start=${start}` : ''
const e = (end) ? `&end=${end}` : ''
const query = `?symbols=${symbols.length ? symbols.join(',') : 'ALL'}${s}${e}&limit=${limit}`
const url = `/tickers/hist${query}`
return this._makePublicRequest(url, cb, transformer)
}
/**
* @param {object} params - parameters
* @param {string} params.key - key
* @param {string} params.context - context
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-stats
*/
stats (params, cb = null) {
const { key, context } = params
return this._makePublicRequest(`/stats1/${key}/${context}`, cb)
}
/**
* @param {object} params - parameters
* @param {string} params.timeframe - 1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M
* @param {string} params.symbol - symbol
* @param {string} params.section - hist, last
* @param {object} [params.query] - query params
* @param {number} [params.query.sort] - query sort param
* @param {number} [params.query.start] - query sort param
* @param {number} [params.query.end] - query sort param
* @param {number} [params.query.limit] - query sort param
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see http://docs.bitfinex.com/v2/reference#rest-public-candles
*/
candles (params, cb = null) {
const { timeframe, symbol, section, query = {} } = params
let url = `/candles/trade:${timeframe}:${symbol}/${section}`
if (Object.keys(query).length > 0) {
url += `?${new URLSearchParams(query).toString()}`
}
return this._makePublicRequest(url, cb, Candle)
}
/**
* Query configuration information
*
* @param {object} [params] - parameters
* @param {string[]} [params.keys] - keys
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
*/
conf (params = {}, cb = null) {
const { keys = [] } = params
if (_isEmpty(keys)) {
return this._response([], null, cb)
}
const url = `/conf/${keys.join(',')}`
return this._makePublicRequest(url, cb)
}
/**
* Get a list of valid currencies ids, full names, pool and explorer
*
* @param {object} [params] - parameters
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-currencies
*/
async currencies (params = {}, cb = null) {
const suffix = (this._company) ? ':' + this._company : ''
const url = `/conf/${[
`pub:list:currency${suffix}`,
`pub:map:currency:sym${suffix}`,
`pub:map:currency:label${suffix}`,
`pub:map:currency:pool${suffix}`,
`pub:map:currency:explorer${suffix}`,
`pub:map:currency:wfx${suffix}`
].join(',')}`
return this._makePublicRequest(url, cb, (data) => {
const res = this._genCurrencyList(data)
return this._doTransform(res, Currency)
})
}
/**
* @param {object} params - parameters
* @param {string} params.type - type
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-alert-list
*/
alertList (params, cb = null) {
const { type } = params
return this._makeAuthRequest('/auth/r/alerts', { type }, cb, Alert)
}
/**
* @param {object} params - parameters
* @param {string} params.type - type
* @param {string} params.symbol - symbol
* @param {number} params.price - price
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-alert-set
*/
alertSet (params, cb = null) {
const { type, symbol, price } = params
return this._makeAuthRequest('/auth/w/alert/set', { type, symbol, price }, cb, Alert)
}
/**
* @param {object} params - parameters
* @param {string} params.symbol - symbol
* @param {number} params.price - price
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-alert-delete
*/
alertDelete (params, cb = null) {
const { symbol, price } = params
return this._makeAuthRequest('/auth/w/alert/del', { symbol, price }, cb)
}
/**
* @param {object} params - parameters
* @param {string} params.symbol - symbol
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {number} [params.sort] - if 1, sorts results oldest first
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-trades
*/
trades (params, cb = null) {
const { symbol, start, end, limit, sort } = params
const query = {}
Object.assign(query, _omitBy({ start, end, limit, sort }, _isNil))
let url = `/trades/${symbol}/hist`
if (Object.keys(query).length > 0) {
url += `?${new URLSearchParams(query).toString()}`
}
return this._makePublicRequest(url, cb, PublicTrade)
}
/**
* @param {object} [params] - parameters
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {number} [params.sort] - if 1, sorts results oldest first
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-public-liquidations
*/
liquidations (params = {}, cb = null) {
const { start, end, limit, sort } = params
const query = {}
Object.assign(query, _omitBy({ start, end, limit, sort }, _isNil))
let url = '/liquidations/hist'
if (Object.keys(query).length > 0) {
url += `?${new URLSearchParams(query).toString()}`
}
return this._makePublicRequest(url, cb, Liquidations)
}
/**
* @param {object} [params] - parameters
* @param {string} [params.symbol] - optional, omit/leave empty for all
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {number} [params.sort] - if 1, sorts results oldest first
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-trades-hist
*/
accountTrades (params = {}, cb = null) {
const { symbol, start, end, limit, sort } = params
const url = !_isEmpty(symbol)
? `/auth/r/trades/${symbol}/hist`
: '/auth/r/trades/hist'
return this._makeAuthRequest(url, {
start, end, limit, sort
}, cb, Trade)
}
/**
* @param {object} [params] - parameters
* @param {string} [params.symbol] - query symbol
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
*/
getWeightedAverages (params = {}, cb = null) {
const { symbol, start, end, limit } = params
const url = '/auth/r/trades/calc'
return this._makeAuthRequest(url, {
symbol, start, end, limit
}, cb, WeightedAverages)
}
/**
* @param {object} [params] - parameters
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-logins-hist
*/
logins (params = {}, cb = null) {
const url = '/auth/r/logins/hist'
const { start, end, limit } = params
return this._makeAuthRequest(url, {
start, end, limit
}, cb, Login)
}
/**
* @param {object} [params] - parameters
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-wallets
*/
wallets (params = {}, cb = null) {
return this._makeAuthRequest('/auth/r/wallets', params, cb, Wallet)
}
/**
* @param {object} [params] - parameters
* @param {number} [params.end] - query end
* @param {string} [params.currency] - currency
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-wallets-hist
*/
walletsHistory (params = {}, cb = null) {
return this._makeAuthRequest('/auth/r/wallets/hist', params, cb, WalletHist)
}
/**
* @param {object} [params] - parameters
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/reference#rest-auth-info-user
*/
userInfo (params = {}, cb = null) {
return this._makeAuthRequest('/auth/r/info/user', params, cb, UserInfo)
}
/**
* @param {object} [params] - parameters
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-orders
*/
activeOrders (params = {}, cb = null) {
return this._makeAuthRequest('/auth/r/orders', params, cb, Order)
}
/**
* @param {object} params - parameters
* @param {Array} params.ids - order ids
* @param {Function} cb - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-orders
*/
activeOrdersWithIds (params, cb = null) {
const { ids } = params
const url = '/auth/r/orders'
return this._makeAuthRequest(url, { id: ids }, cb, Order)
}
/**
* @param {object} [params] - parameters
* @param {string} [params.ccy] - i.e. ETH
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit, default 25
* @param {string} [params.address] - query address
* @param {Array<number>} [params.id] - Optional array of deposit/withdrawal ids
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#movements
*/
movements (params = {}, cb = null) {
const { ccy, start, end, limit = 25, id, address } = params
const url = ccy
? `/auth/r/movements/${ccy}/hist`
: '/auth/r/movements/hist'
return this._makeAuthRequest(url, { start, end, limit, id, address }, cb, Movement)
}
/**
* @param {object} [params] - parameters
* @param {number} [params.id] - movement id
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/reference/movement-info
*/
movementInfo (params, cb = null) {
const { id } = params
const url = '/auth/r/movements/info'
return this._makeAuthRequest(url, { id }, cb, MovementInfo)
}
/**
* @param {object} params - parameters
* @param {object|string} params.filters - filters
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - default 25
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#ledgers
*/
ledgers (params, cb = null) {
const { filters, start, end, limit = 25 } = params
const parseFilters = (sent) => {
if (_isString(sent)) return { ccy: sent }
return sent || {}
}
const { ccy, category } = parseFilters(filters)
const url = ccy
? `/auth/r/ledgers/${ccy}/hist`
: '/auth/r/ledgers/hist'
return this._makeAuthRequest(url, {
start, end, limit, category
}, cb, LedgerEntry)
}
/**
* @param {object} [params] - parameters
* @param {string} [params.symbol] - optional, omit/leave empty for all
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/reference#rest-auth-orders-history
*/
orderHistory (params = {}, cb = null) {
const { symbol, start, end, limit } = params
const url = !_isEmpty(symbol)
? `/auth/r/orders/${symbol}/hist`
: '/auth/r/orders/hist'
return this._makeAuthRequest(url, {
start, end, limit
}, cb, Order)
}
/**
* @param {object} params - parameters
* @param {Array} params.ids - order ids
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/reference#rest-auth-orders-history
*/
orderHistoryWithIds (params, cb = null) {
const { ids } = params
const url = '/auth/r/orders/hist'
return this._makeAuthRequest(url, { id: ids }, cb, Order)
}
/**
* @param {object} params - parameters
* @param {string} params.symbol - symbol
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {number} params.orderId - order ID
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-order-trades
*/
orderTrades (params, cb = null) {
const { symbol, start, end, limit, orderId } = params
return this._makeAuthRequest(`/auth/r/order/${symbol}:${orderId}/trades`, {
start, end, limit
}, cb, Trade)
}
/**
* @param {object} [params] - parameters
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-positions
*/
positions (params = {}, cb = null) {
return this._makeAuthRequest('/auth/r/positions', params, cb, Position)
}
/**
* @param {object} [params] - parameters
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-positions-history
*/
positionsHistory (params = {}, cb = null) {
const { start, end, limit = 50 } = params
return this._makeAuthRequest('/auth/r/positions/hist', {
start, end, limit
}, cb, Position)
}
/**
* @param {object} [params] - parameters
* @param {number[]} [params.id] - ids of positions to audit
* @param {number} [params.start] - query start
* @param {number} [params.end] - query end
* @param {number} [params.limit] - query limit
* @param {Function} [cb] - legacy callback
* @returns {Promise} p
* @see https://docs.bitfinex.com/v2/reference#rest-auth-positions-audit
*/