-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitvavo.js
1574 lines (1533 loc) · 66.7 KB
/
bitvavo.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
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
'use strict';
// ----------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, BadSymbol, AuthenticationError, InsufficientFunds, InvalidOrder, ArgumentsRequired, OrderNotFound, InvalidAddress, BadRequest, RateLimitExceeded, PermissionDenied, ExchangeNotAvailable, AccountSuspended, OnMaintenance } = require ('./base/errors');
const { SIGNIFICANT_DIGITS, DECIMAL_PLACES, TRUNCATE, ROUND } = require ('./base/functions/number');
// ----------------------------------------------------------------------------
module.exports = class bitvavo extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bitvavo',
'name': 'Bitvavo',
'countries': [ 'NL' ], // Netherlands
'rateLimit': 60.1, // 1000 requests per second
'version': 'v2',
'certified': true,
'pro': true,
'has': {
'CORS': undefined,
'spot': true,
'margin': false,
'swap': false,
'future': false,
'option': false,
'addMargin': false,
'cancelAllOrders': true,
'cancelOrder': true,
'createOrder': true,
'createReduceOnlyOrder': false,
'editOrder': true,
'fetchBalance': true,
'fetchBorrowRate': false,
'fetchBorrowRateHistories': false,
'fetchBorrowRateHistory': false,
'fetchBorrowRates': false,
'fetchBorrowRatesPerSymbol': false,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchFundingHistory': false,
'fetchFundingRate': false,
'fetchFundingRateHistory': false,
'fetchFundingRates': false,
'fetchIndexOHLCV': false,
'fetchIsolatedPositions': false,
'fetchLeverage': false,
'fetchLeverageTiers': false,
'fetchMarkets': true,
'fetchMarkOHLCV': false,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchPosition': false,
'fetchPositions': false,
'fetchPositionsRisk': false,
'fetchPremiumIndexOHLCV': false,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': false,
'fetchTradingFees': true,
'fetchWithdrawals': true,
'reduceMargin': false,
'setLeverage': false,
'setMarginMode': false,
'setPositionMode': false,
'withdraw': true,
},
'timeframes': {
'1m': '1m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'4h': '4h',
'6h': '6h',
'8h': '8h',
'12h': '12h',
'1d': '1d',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/83165440-2f1cf200-a116-11ea-9046-a255d09fb2ed.jpg',
'api': {
'public': 'https://api.bitvavo.com',
'private': 'https://api.bitvavo.com',
},
'www': 'https://bitvavo.com/',
'doc': 'https://docs.bitvavo.com/',
'fees': 'https://bitvavo.com/en/fees',
'referral': 'https://bitvavo.com/?a=24F34952F7',
},
'api': {
'public': {
'get': {
'time': 1,
'markets': 1,
'assets': 1,
'{market}/book': 1,
'{market}/trades': 5,
'{market}/candles': 1,
'ticker/price': 1,
'ticker/book': 1,
'ticker/24h': { 'cost': 1, 'noMarket': 25 },
},
},
'private': {
'get': {
'account': 1,
'order': 1,
'orders': 5,
'ordersOpen': { 'cost': 1, 'noMarket': 25 },
'trades': 5,
'balance': 5,
'deposit': 1,
'depositHistory': 5,
'withdrawalHistory': 5,
},
'post': {
'order': 1,
'withdrawal': 1,
},
'put': {
'order': 1,
},
'delete': {
'order': 1,
'orders': 1,
},
},
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0025'),
'maker': this.parseNumber ('0.002'),
'tiers': {
'taker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0025') ],
[ this.parseNumber ('100000'), this.parseNumber ('0.0020') ],
[ this.parseNumber ('250000'), this.parseNumber ('0.0016') ],
[ this.parseNumber ('500000'), this.parseNumber ('0.0012') ],
[ this.parseNumber ('1000000'), this.parseNumber ('0.0010') ],
[ this.parseNumber ('2500000'), this.parseNumber ('0.0008') ],
[ this.parseNumber ('5000000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('10000000'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('25000000'), this.parseNumber ('0.0004') ],
],
'maker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0015') ],
[ this.parseNumber ('100000'), this.parseNumber ('0.0010') ],
[ this.parseNumber ('250000'), this.parseNumber ('0.0008') ],
[ this.parseNumber ('500000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('1000000'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('2500000'), this.parseNumber ('0.0004') ],
[ this.parseNumber ('5000000'), this.parseNumber ('0.0004') ],
[ this.parseNumber ('10000000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('25000000'), this.parseNumber ('0.0003') ],
],
},
},
},
'requiredCredentials': {
'apiKey': true,
'secret': true,
},
'exceptions': {
'exact': {
'101': ExchangeError, // Unknown error. Operation may or may not have succeeded.
'102': BadRequest, // Invalid JSON.
'103': RateLimitExceeded, // You have been rate limited. Please observe the Bitvavo-Ratelimit-AllowAt header to see when you can send requests again. Failure to respect this limit will result in an IP ban. The default value is 1000 weighted requests per minute. Please contact support if you wish to increase this limit.
'104': RateLimitExceeded, // You have been rate limited by the number of new orders. The default value is 100 new orders per second or 100.000 new orders per day. Please update existing orders instead of cancelling and creating orders. Please contact support if you wish to increase this limit.
'105': PermissionDenied, // Your IP or API key has been banned for not respecting the rate limit. The ban expires at ${expiryInMs}.
'107': ExchangeNotAvailable, // The matching engine is overloaded. Please wait 500ms and resubmit your order.
'108': ExchangeNotAvailable, // The matching engine could not process your order in time. Please consider increasing the access window or resubmit your order.
'109': ExchangeNotAvailable, // The matching engine did not respond in time. Operation may or may not have succeeded.
'110': BadRequest, // Invalid endpoint. Please check url and HTTP method.
'200': BadRequest, // ${param} url parameter is not supported. Please note that parameters are case-sensitive and use body parameters for PUT and POST requests.
'201': BadRequest, // ${param} body parameter is not supported. Please note that parameters are case-sensitive and use url parameters for GET and DELETE requests.
'202': BadRequest, // ${param} order parameter is not supported. Please note that certain parameters are only allowed for market or limit orders.
'203': BadSymbol, // {"errorCode":203,"error":"symbol parameter is required."}
'204': BadRequest, // ${param} parameter is not supported.
'205': BadRequest, // ${param} parameter is invalid.
'206': BadRequest, // Use either ${paramA} or ${paramB}. The usage of both parameters at the same time is not supported.
'210': InvalidOrder, // Amount exceeds the maximum allowed amount (1000000000).
'211': InvalidOrder, // Price exceeds the maximum allowed amount (100000000000).
'212': InvalidOrder, // Amount is below the minimum allowed amount for this asset.
'213': InvalidOrder, // Price is below the minimum allowed amount (0.000000000000001).
'214': InvalidOrder, // Price is too detailed
'215': InvalidOrder, // Price is too detailed. A maximum of 15 digits behind the decimal point are allowed.
'216': InsufficientFunds, // {"errorCode":216,"error":"You do not have sufficient balance to complete this operation."}
'217': InvalidOrder, // {"errorCode":217,"error":"Minimum order size in quote currency is 5 EUR or 0.001 BTC."}
'230': ExchangeError, // The order is rejected by the matching engine.
'231': ExchangeError, // The order is rejected by the matching engine. TimeInForce must be GTC when markets are paused.
'232': BadRequest, // You must change at least one of amount, amountRemaining, price, timeInForce, selfTradePrevention or postOnly.
'233': InvalidOrder, // {"errorCode":233,"error":"Order must be active (status new or partiallyFilled) to allow updating/cancelling."}
'234': InvalidOrder, // Market orders cannot be updated.
'235': ExchangeError, // You can only have 100 open orders on each book.
'236': BadRequest, // You can only update amount or amountRemaining, not both.
'240': OrderNotFound, // {"errorCode":240,"error":"No order found. Please be aware that simultaneously updating the same order may return this error."}
'300': AuthenticationError, // Authentication is required for this endpoint.
'301': AuthenticationError, // {"errorCode":301,"error":"API Key must be of length 64."}
'302': AuthenticationError, // Timestamp is invalid. This must be a timestamp in ms. See Bitvavo-Access-Timestamp header or timestamp parameter for websocket.
'303': AuthenticationError, // Window must be between 100 and 60000 ms.
'304': AuthenticationError, // Request was not received within acceptable window (default 30s, or custom with Bitvavo-Access-Window header) of Bitvavo-Access-Timestamp header (or timestamp parameter for websocket).
// '304': AuthenticationError, // Authentication is required for this endpoint.
'305': AuthenticationError, // {"errorCode":305,"error":"No active API key found."}
'306': AuthenticationError, // No active API key found. Please ensure that you have confirmed the API key by e-mail.
'307': PermissionDenied, // This key does not allow access from this IP.
'308': AuthenticationError, // {"errorCode":308,"error":"The signature length is invalid (HMAC-SHA256 should return a 64 length hexadecimal string)."}
'309': AuthenticationError, // {"errorCode":309,"error":"The signature is invalid."}
'310': PermissionDenied, // This key does not allow trading actions.
'311': PermissionDenied, // This key does not allow showing account information.
'312': PermissionDenied, // This key does not allow withdrawal of funds.
'315': BadRequest, // Websocket connections may not be used in a browser. Please use REST requests for this.
'317': AccountSuspended, // This account is locked. Please contact support.
'400': ExchangeError, // Unknown error. Please contact support with a copy of your request.
'401': ExchangeError, // Deposits for this asset are not available at this time.
'402': PermissionDenied, // You need to verify your identitiy before you can deposit and withdraw digital assets.
'403': PermissionDenied, // You need to verify your phone number before you can deposit and withdraw digital assets.
'404': OnMaintenance, // Could not complete this operation, because our node cannot be reached. Possibly under maintenance.
'405': ExchangeError, // You cannot withdraw digital assets during a cooldown period. This is the result of newly added bank accounts.
'406': BadRequest, // {"errorCode":406,"error":"Your withdrawal is too small."}
'407': ExchangeError, // Internal transfer is not possible.
'408': InsufficientFunds, // {"errorCode":408,"error":"You do not have sufficient balance to complete this operation."}
'409': InvalidAddress, // {"errorCode":409,"error":"This is not a verified bank account."}
'410': ExchangeError, // Withdrawals for this asset are not available at this time.
'411': BadRequest, // You can not transfer assets to yourself.
'412': InvalidAddress, // {"errorCode":412,"error":"eth_address_invalid."}
'413': InvalidAddress, // This address violates the whitelist.
'414': ExchangeError, // You cannot withdraw assets within 2 minutes of logging in.
},
'broad': {
'start parameter is invalid': BadRequest, // {"errorCode":205,"error":"start parameter is invalid."}
'symbol parameter is invalid': BadSymbol, // {"errorCode":205,"error":"symbol parameter is invalid."}
'amount parameter is invalid': InvalidOrder, // {"errorCode":205,"error":"amount parameter is invalid."}
'orderId parameter is invalid': InvalidOrder, // {"errorCode":205,"error":"orderId parameter is invalid."}
},
},
'options': {
'BITVAVO-ACCESS-WINDOW': 10000, // default 10 sec
'fetchCurrencies': {
'expires': 1000, // 1 second
},
},
'precisionMode': SIGNIFICANT_DIGITS,
'commonCurrencies': {
'MIOTA': 'IOTA', // https://github.com/ccxt/ccxt/issues/7487
},
});
}
currencyToPrecision (currency, fee) {
return this.decimalToPrecision (fee, 0, this.currencies[currency]['precision']);
}
amountToPrecision (symbol, amount) {
// https://docs.bitfinex.com/docs/introduction#amount-precision
// The amount field allows up to 8 decimals.
// Anything exceeding this will be rounded to the 8th decimal.
return this.decimalToPrecision (amount, TRUNCATE, this.markets[symbol]['precision']['amount'], DECIMAL_PLACES);
}
priceToPrecision (symbol, price) {
price = this.decimalToPrecision (price, ROUND, this.markets[symbol]['precision']['price'], this.precisionMode);
// https://docs.bitfinex.com/docs/introduction#price-precision
// The precision level of all trading prices is based on significant figures.
// All pairs on Bitfinex use up to 5 significant digits and up to 8 decimals (e.g. 1.2345, 123.45, 1234.5, 0.00012345).
// Prices submit with a precision larger than 5 will be cut by the API.
return this.decimalToPrecision (price, TRUNCATE, 8, DECIMAL_PLACES);
}
async fetchTime (params = {}) {
const response = await this.publicGetTime (params);
//
// { "time": 1590379519148 }
//
return this.safeInteger (response, 'time');
}
async fetchMarkets (params = {}) {
const response = await this.publicGetMarkets (params);
const currencies = await this.fetchCurrenciesFromCache (params);
const currenciesById = this.indexBy (currencies, 'symbol');
//
// [
// {
// "market":"ADA-BTC",
// "status":"trading", // "trading" "halted" "auction"
// "base":"ADA",
// "quote":"BTC",
// "pricePrecision":5,
// "minOrderInBaseAsset":"100",
// "minOrderInQuoteAsset":"0.001",
// "orderTypes": [ "market", "limit" ]
// }
// ]
//
const result = [];
for (let i = 0; i < response.length; i++) {
const market = response[i];
const id = this.safeString (market, 'market');
const baseId = this.safeString (market, 'base');
const quoteId = this.safeString (market, 'quote');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const status = this.safeString (market, 'status');
const baseCurrency = this.safeValue (currenciesById, baseId);
let amountPrecision = undefined;
if (baseCurrency !== undefined) {
amountPrecision = this.safeInteger (baseCurrency, 'decimals', 8);
}
result.push ({
'id': id,
'symbol': base + '/' + quote,
'base': base,
'quote': quote,
'settle': undefined,
'baseId': baseId,
'quoteId': quoteId,
'settleId': undefined,
'type': 'spot',
'spot': true,
'margin': false,
'swap': false,
'future': false,
'option': false,
'active': (status === 'trading'),
'contract': false,
'linear': undefined,
'inverse': undefined,
'contractSize': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': amountPrecision,
'price': this.safeInteger (market, 'pricePrecision'),
},
'limits': {
'leverage': {
'min': undefined,
'max': undefined,
},
'amount': {
'min': this.safeNumber (market, 'minOrderInBaseAsset'),
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber (market, 'minOrderInQuoteAsset'),
'max': undefined,
},
},
'info': market,
});
}
return result;
}
async fetchCurrenciesFromCache (params = {}) {
// this method is now redundant
// currencies are now fetched before markets
const options = this.safeValue (this.options, 'fetchCurrencies', {});
const timestamp = this.safeInteger (options, 'timestamp');
const expires = this.safeInteger (options, 'expires', 1000);
const now = this.milliseconds ();
if ((timestamp === undefined) || ((now - timestamp) > expires)) {
const response = await this.publicGetAssets (params);
this.options['fetchCurrencies'] = this.extend (options, {
'response': response,
'timestamp': now,
});
}
return this.safeValue (this.options['fetchCurrencies'], 'response');
}
async fetchCurrencies (params = {}) {
const response = await this.fetchCurrenciesFromCache (params);
//
// [
// {
// "symbol":"ADA",
// "name":"Cardano",
// "decimals":6,
// "depositFee":"0",
// "depositConfirmations":15,
// "depositStatus":"OK", // "OK", "MAINTENANCE", "DELISTED"
// "withdrawalFee":"0.2",
// "withdrawalMinAmount":"0.2",
// "withdrawalStatus":"OK", // "OK", "MAINTENANCE", "DELISTED"
// "networks": [ "Mainnet" ], // "ETH", "NEO", "ONT", "SEPA", "VET"
// "message":"",
// },
// ]
//
const result = {};
for (let i = 0; i < response.length; i++) {
const currency = response[i];
const id = this.safeString (currency, 'symbol');
const code = this.safeCurrencyCode (id);
const depositStatus = this.safeValue (currency, 'depositStatus');
const deposit = (depositStatus === 'OK');
const withdrawalStatus = this.safeValue (currency, 'withdrawalStatus');
const withdrawal = (withdrawalStatus === 'OK');
const active = deposit && withdrawal;
const name = this.safeString (currency, 'name');
const precision = this.safeInteger (currency, 'decimals', 8);
result[code] = {
'id': id,
'info': currency,
'code': code,
'name': name,
'active': active,
'deposit': deposit,
'withdraw': withdrawal,
'fee': this.safeNumber (currency, 'withdrawalFee'),
'precision': precision,
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
'withdraw': {
'min': this.safeNumber (currency, 'withdrawalMinAmount'),
'max': undefined,
},
},
};
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
};
const response = await this.publicGetTicker24h (this.extend (request, params));
//
// {
// "market":"ETH-BTC",
// "open":"0.022578",
// "high":"0.023019",
// "low":"0.022573",
// "last":"0.023019",
// "volume":"25.16366324",
// "volumeQuote":"0.57333305",
// "bid":"0.023039",
// "bidSize":"0.53500578",
// "ask":"0.023041",
// "askSize":"0.47859202",
// "timestamp":1590381666900
// }
//
return this.parseTicker (response, market);
}
parseTicker (ticker, market = undefined) {
//
// fetchTicker
//
// {
// "market":"ETH-BTC",
// "open":"0.022578",
// "high":"0.023019",
// "low":"0.022573",
// "last":"0.023019",
// "volume":"25.16366324",
// "volumeQuote":"0.57333305",
// "bid":"0.023039",
// "bidSize":"0.53500578",
// "ask":"0.023041",
// "askSize":"0.47859202",
// "timestamp":1590381666900
// }
//
const marketId = this.safeString (ticker, 'market');
const symbol = this.safeSymbol (marketId, market, '-');
const timestamp = this.safeInteger (ticker, 'timestamp');
const last = this.safeString (ticker, 'last');
const baseVolume = this.safeString (ticker, 'volume');
const quoteVolume = this.safeString (ticker, 'volumeQuote');
const open = this.safeString (ticker, 'open');
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeString (ticker, 'high'),
'low': this.safeString (ticker, 'low'),
'bid': this.safeString (ticker, 'bid'),
'bidVolume': this.safeString (ticker, 'bidSize'),
'ask': this.safeString (ticker, 'ask'),
'askVolume': this.safeString (ticker, 'askSize'),
'vwap': undefined,
'open': open,
'close': last,
'last': last,
'previousClose': undefined, // previous day close
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market, false);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.publicGetTicker24h (params);
//
// [
// {
// "market":"ADA-BTC",
// "open":"0.0000059595",
// "high":"0.0000059765",
// "low":"0.0000059595",
// "last":"0.0000059765",
// "volume":"2923.172",
// "volumeQuote":"0.01743483",
// "bid":"0.0000059515",
// "bidSize":"1117.630919",
// "ask":"0.0000059585",
// "askSize":"809.999739",
// "timestamp":1590382266324
// }
// ]
//
return this.parseTickers (response, symbols);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
// 'limit': 500, // default 500, max 1000
// 'start': since,
// 'end': this.milliseconds (),
// 'tradeIdFrom': '57b1159b-6bf5-4cde-9e2c-6bd6a5678baf',
// 'tradeIdTo': '57b1159b-6bf5-4cde-9e2c-6bd6a5678baf',
};
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['start'] = since;
}
const response = await this.publicGetMarketTrades (this.extend (request, params));
//
// [
// {
// "id":"94154c98-6e8b-4e33-92a8-74e33fc05650",
// "timestamp":1590382761859,
// "amount":"0.06026079",
// "price":"8095.3",
// "side":"buy"
// }
// ]
//
return this.parseTrades (response, market, since, limit);
}
parseTrade (trade, market = undefined) {
//
// fetchTrades (public)
//
// {
// "id":"94154c98-6e8b-4e33-92a8-74e33fc05650",
// "timestamp":1590382761859,
// "amount":"0.06026079",
// "price":"8095.3",
// "side":"buy"
// }
//
// createOrder, fetchOpenOrders, fetchOrders, editOrder (private)
//
// {
// "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
// "timestamp":1590505649245,
// "amount":"0.249825",
// "price":"183.49",
// "taker":true,
// "fee":"0.12038925",
// "feeCurrency":"EUR",
// "settled":true
// }
//
// fetchMyTrades (private)
//
// {
// "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
// "orderId":"af76d6ce-9f7c-4006-b715-bb5d430652d0",
// "timestamp":1590505649245,
// "market":"ETH-EUR",
// "side":"sell",
// "amount":"0.249825",
// "price":"183.49",
// "taker":true,
// "fee":"0.12038925",
// "feeCurrency":"EUR",
// "settled":true
// }
//
// watchMyTrades (private)
//
// {
// event: 'fill',
// timestamp: 1590964470132,
// market: 'ETH-EUR',
// orderId: '85d082e1-eda4-4209-9580-248281a29a9a',
// fillId: '861d2da5-aa93-475c-8d9a-dce431bd4211',
// side: 'sell',
// amount: '0.1',
// price: '211.46',
// taker: true,
// fee: '0.056',
// feeCurrency: 'EUR'
// }
//
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString (trade, 'amount');
const timestamp = this.safeInteger (trade, 'timestamp');
const side = this.safeString (trade, 'side');
const id = this.safeString2 (trade, 'id', 'fillId');
const marketId = this.safeString (trade, 'market');
const symbol = this.safeSymbol (marketId, market, '-');
const taker = this.safeValue (trade, 'taker');
let takerOrMaker = undefined;
if (taker !== undefined) {
takerOrMaker = taker ? 'taker' : 'maker';
}
const feeCostString = this.safeString (trade, 'fee');
let fee = undefined;
if (feeCostString !== undefined) {
const feeCurrencyId = this.safeString (trade, 'feeCurrency');
const feeCurrencyCode = this.safeCurrencyCode (feeCurrencyId);
fee = {
'cost': feeCostString,
'currency': feeCurrencyCode,
};
}
const orderId = this.safeString (trade, 'orderId');
return this.safeTrade ({
'info': trade,
'id': id,
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'order': orderId,
'type': undefined,
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': undefined,
'fee': fee,
}, market);
}
async fetchTradingFees (params = {}) {
await this.loadMarkets ();
const response = await this.privateGetAccount (params);
//
// {
// "fees": {
// "taker": "0.0025",
// "maker": "0.0015",
// "volume": "10000.00"
// }
// }
//
const fees = this.safeValue (response, 'fees');
const maker = this.safeNumber (fees, 'maker');
const taker = this.safeNumber (fees, 'taker');
const result = {};
for (let i = 0; i < this.symbols.length; i++) {
const symbol = this.symbols[i];
result[symbol] = {
'info': response,
'symbol': symbol,
'maker': maker,
'taker': taker,
'percentage': true,
'tierBased': true,
};
}
return result;
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'market': this.marketId (symbol),
};
if (limit !== undefined) {
request['depth'] = limit;
}
const response = await this.publicGetMarketBook (this.extend (request, params));
//
// {
// "market":"BTC-EUR",
// "nonce":35883831,
// "bids":[
// ["8097.4","0.6229099"],
// ["8097.2","0.64151283"],
// ["8097.1","0.24966294"],
// ],
// "asks":[
// ["8097.5","1.36916911"],
// ["8098.8","0.33462248"],
// ["8099.3","1.12908646"],
// ]
// }
//
const orderbook = this.parseOrderBook (response, symbol);
orderbook['nonce'] = this.safeInteger (response, 'nonce');
return orderbook;
}
parseOHLCV (ohlcv, market = undefined) {
//
// [
// 1590383700000,
// "8088.5",
// "8088.5",
// "8088.5",
// "8088.5",
// "0.04788623"
// ]
//
return [
this.safeInteger (ohlcv, 0),
this.safeNumber (ohlcv, 1),
this.safeNumber (ohlcv, 2),
this.safeNumber (ohlcv, 3),
this.safeNumber (ohlcv, 4),
this.safeNumber (ohlcv, 5),
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
'interval': this.timeframes[timeframe],
// 'limit': 1440, // default 1440, max 1440
// 'start': since,
// 'end': this.milliseconds (),
};
if (since !== undefined) {
// https://github.com/ccxt/ccxt/issues/9227
const duration = this.parseTimeframe (timeframe);
request['start'] = since;
if (limit === undefined) {
limit = 1440;
}
request['end'] = this.sum (since, limit * duration * 1000);
}
if (limit !== undefined) {
request['limit'] = limit; // default 1440, max 1440
}
const response = await this.publicGetMarketCandles (this.extend (request, params));
//
// [
// [1590383700000,"8088.5","8088.5","8088.5","8088.5","0.04788623"],
// [1590383580000,"8091.3","8091.5","8091.3","8091.5","0.04931221"],
// [1590383520000,"8090.3","8092.7","8090.3","8092.5","0.04001286"],
// ]
//
return this.parseOHLCVs (response, market, timeframe, since, limit);
}
parseBalance (response) {
const result = {
'info': response,
'timestamp': undefined,
'datetime': undefined,
};
for (let i = 0; i < response.length; i++) {
const balance = response[i];
const currencyId = this.safeString (balance, 'symbol');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (balance, 'available');
account['used'] = this.safeString (balance, 'inOrder');
result[code] = account;
}
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const response = await this.privateGetBalance (params);
//
// [
// {
// "symbol": "BTC",
// "available": "1.57593193",
// "inOrder": "0.74832374"
// }
// ]
//
return this.parseBalance (response);
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'symbol': currency['id'],
};
const response = await this.privateGetDeposit (this.extend (request, params));
//
// {
// "address": "0x449889e3234514c45d57f7c5a571feba0c7ad567",
// "paymentId": "10002653"
// }
//
const address = this.safeString (response, 'address');
const tag = this.safeString (response, 'paymentId');
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': tag,
'network': undefined,
'info': response,
};
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
'side': side,
'orderType': type, // 'market', 'limit', 'stopLoss', 'stopLossLimit', 'takeProfit', 'takeProfitLimit'
// 'amount': this.amountToPrecision (symbol, amount),
// 'price': this.priceToPrecision (symbol, price),
// 'amountQuote': this.costToPrecision (symbol, cost),
// 'timeInForce': 'GTC', // 'GTC', 'IOC', 'FOK'
// 'selfTradePrevention': 'decrementAndCancel', // 'decrementAndCancel', 'cancelOldest', 'cancelNewest', 'cancelBoth'
// 'postOnly': false,
// 'disableMarketProtection': false, // don't cancel if the next fill price is 10% worse than the best fill price
// 'responseRequired': true, // false is faster
};
const isStopLimit = (type === 'stopLossLimit') || (type === 'takeProfitLimit');
const isStopMarket = (type === 'stopLoss') || (type === 'takeProfit');
if (type === 'market') {
let cost = undefined;
if (price !== undefined) {
cost = amount * price;
} else {
cost = this.safeNumber2 (params, 'cost', 'amountQuote');
}
if (cost !== undefined) {
const precision = market['precision']['price'];
request['amountQuote'] = this.decimalToPrecision (cost, TRUNCATE, precision, this.precisionMode);
} else {
request['amount'] = this.amountToPrecision (symbol, amount);
}
params = this.omit (params, [ 'cost', 'amountQuote' ]);
} else if (type === 'limit') {
request['price'] = this.priceToPrecision (symbol, price);
request['amount'] = this.amountToPrecision (symbol, amount);
} else if (isStopMarket || isStopLimit) {
let stopPrice = this.safeNumber2 (params, 'stopPrice', 'triggerAmount');
if (stopPrice === undefined) {
if (isStopLimit) {
throw new ArgumentsRequired (this.id + ' createOrder requires a stopPrice parameter for a ' + type + ' order');
} else if (isStopMarket) {
if (price === undefined) {
throw new ArgumentsRequired (this.id + ' createOrder requires a price argument or a stopPrice parameter for a ' + type + ' order');
} else {
stopPrice = price;
}
}
}
if (isStopLimit) {
request['price'] = this.priceToPrecision (symbol, price);
}
params = this.omit (params, [ 'stopPrice', 'triggerAmount' ]);
request['triggerAmount'] = this.priceToPrecision (symbol, stopPrice);
request['triggerType'] = 'price';
request['amount'] = this.amountToPrecision (symbol, amount);
}
const response = await this.privatePostOrder (this.extend (request, params));
//
// {
// "orderId":"af76d6ce-9f7c-4006-b715-bb5d430652d0",
// "market":"ETH-EUR",
// "created":1590505649241,
// "updated":1590505649241,
// "status":"filled",
// "side":"sell",
// "orderType":"market",
// "amount":"0.249825",
// "amountRemaining":"0",
// "onHold":"0",
// "onHoldCurrency":"ETH",
// "filledAmount":"0.249825",
// "filledAmountQuote":"45.84038925",
// "feePaid":"0.12038925",
// "feeCurrency":"EUR",
// "fills":[
// {
// "id":"b0c86aa5-6ed3-4a2d-ba3a-be9a964220f4",
// "timestamp":1590505649245,
// "amount":"0.249825",
// "price":"183.49",
// "taker":true,
// "fee":"0.12038925",
// "feeCurrency":"EUR",
// "settled":true
// }
// ],
// "selfTradePrevention":"decrementAndCancel",
// "visible":false,
// "disableMarketProtection":false
// }
//
return this.parseOrder (response, market);
}
async editOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
let request = {};
const amountRemaining = this.safeNumber (params, 'amountRemaining');
params = this.omit (params, 'amountRemaining');
if (price !== undefined) {
request['price'] = this.priceToPrecision (symbol, price);
}
if (amount !== undefined) {
request['amount'] = this.amountToPrecision (symbol, amount);
}
if (amountRemaining !== undefined) {
request['amountRemaining'] = this.amountToPrecision (symbol, amountRemaining);
}
request = this.extend (request, params);
if (Object.keys (request).length) {
request['orderId'] = id;
request['market'] = market['id'];
const response = await this.privatePutOrder (this.extend (request, params));
return this.parseOrder (response, market);
} else {
throw new ArgumentsRequired (this.id + ' editOrder() requires an amount argument, or a price argument, or non-empty params');
}
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'orderId': id,
'market': market['id'],
};
const response = await this.privateDeleteOrder (this.extend (request, params));
//
// {
// "orderId": "2e7ce7fc-44e2-4d80-a4a7-d079c4750b61"
// }
//
return this.parseOrder (response, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
request['market'] = market['id'];
}
const response = await this.privateDeleteOrders (this.extend (request, params));
//
// [
// {
// "orderId": "1be6d0df-d5dc-4b53-a250-3376f3b393e6"
// }
// ]