forked from ccxt/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathderibit.js
2683 lines (2633 loc) · 124 KB
/
deribit.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 { TICK_SIZE } = require ('./base/functions/number');
const { AuthenticationError, ExchangeError, ArgumentsRequired, PermissionDenied, InvalidOrder, OrderNotFound, DDoSProtection, NotSupported, ExchangeNotAvailable, InsufficientFunds, BadRequest, InvalidAddress, OnMaintenance } = require ('./base/errors');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class deribit extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'deribit',
'name': 'Deribit',
'countries': [ 'NL' ], // Netherlands
'version': 'v2',
'userAgent': undefined,
// 20 requests per second for non-matching-engine endpoints, 1000ms / 20 = 50ms between requests
// 5 requests per second for matching-engine endpoints, cost = (1000ms / rateLimit) / 5 = 4
'rateLimit': 50,
'pro': true,
'has': {
'CORS': true,
'spot': false,
'margin': false,
'swap': true,
'future': true,
'option': true,
'cancelAllOrders': true,
'cancelOrder': true,
'cancelOrders': false,
'createDepositAddress': true,
'createOrder': true,
'createStopLimitOrder': true,
'createStopMarketOrder': true,
'createStopOrder': true,
'editOrder': true,
'fetchAccounts': true,
'fetchBalance': true,
'fetchBorrowRate': false,
'fetchBorrowRateHistories': false,
'fetchBorrowRateHistory': false,
'fetchBorrowRates': false,
'fetchBorrowRatesPerSymbol': false,
'fetchClosedOrders': true,
'fetchDeposit': false,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchHistoricalVolatility': true,
'fetchIndexOHLCV': false,
'fetchLeverageTiers': false,
'fetchMarginMode': false,
'fetchMarkets': true,
'fetchMarkOHLCV': false,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': false,
'fetchOrderTrades': true,
'fetchPosition': true,
'fetchPositionMode': false,
'fetchPositions': true,
'fetchPremiumIndexOHLCV': false,
'fetchStatus': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': false,
'fetchTradingFees': true,
'fetchTransactions': false,
'fetchTransfer': false,
'fetchTransfers': true,
'fetchWithdrawal': false,
'fetchWithdrawals': true,
'transfer': true,
'withdraw': true,
},
'timeframes': {
'1m': '1',
'3m': '3',
'5m': '5',
'10m': '10',
'15m': '15',
'30m': '30',
'1h': '60',
'2h': '120',
'3h': '180',
'6h': '360',
'12h': '720',
'1d': '1D',
},
'urls': {
'test': {
'rest': 'https://test.deribit.com',
},
'logo': 'https://user-images.githubusercontent.com/1294454/41933112-9e2dd65a-798b-11e8-8440-5bab2959fcb8.jpg',
'api': {
'rest': 'https://www.deribit.com',
},
'www': 'https://www.deribit.com',
'doc': [
'https://docs.deribit.com/v2',
'https://github.com/deribit',
],
'fees': 'https://www.deribit.com/pages/information/fees',
'referral': {
'url': 'https://www.deribit.com/reg-1189.4038',
'discount': 0.1,
},
},
'api': {
'public': {
'get': {
// Authentication
'auth': 1,
'exchange_token': 1,
'fork_token': 1,
// Session management
'set_heartbeat': 1,
'disable_heartbeat': 1,
// Supporting
'get_time': 1,
'hello': 1,
'status': 1,
'test': 1,
// Subscription management
'subscribe': 1,
'unsubscribe': 1,
'unsubscribe_all': 1,
// Account management
'get_announcements': 1,
// Market data
'get_book_summary_by_currency': 1,
'get_book_summary_by_instrument': 1,
'get_contract_size': 1,
'get_currencies': 1,
'get_delivery_prices': 1,
'get_funding_chart_data': 1,
'get_funding_rate_history': 1,
'get_funding_rate_value': 1,
'get_historical_volatility': 1,
'get_index': 1,
'get_index_price': 1,
'get_index_price_names': 1,
'get_instrument': 1,
'get_instruments': 1,
'get_last_settlements_by_currency': 1,
'get_last_settlements_by_instrument': 1,
'get_last_trades_by_currency': 1,
'get_last_trades_by_currency_and_time': 1,
'get_last_trades_by_instrument': 1,
'get_last_trades_by_instrument_and_time': 1,
'get_mark_price_history': 1,
'get_order_book': 1,
'get_trade_volumes': 1,
'get_tradingview_chart_data': 1,
'get_volatility_index_data': 1,
'ticker': 1,
},
},
'private': {
'get': {
// Authentication
'logout': 1,
// Session management
'enable_cancel_on_disconnect': 1,
'disable_cancel_on_disconnect': 1,
'get_cancel_on_disconnect': 1,
// Subscription management
'subscribe': 1,
'unsubscribe': 1,
'unsubscribe_all': 1,
// Account management
'change_api_key_name': 1,
'change_scope_in_api_key': 1,
'change_subaccount_name': 1,
'create_api_key': 1,
'create_subaccount': 1,
'disable_api_key': 1,
'disable_tfa_for_subaccount': 1,
'enable_affiliate_program': 1,
'enable_api_key': 1,
'get_access_log': 1,
'get_account_summary': 1,
'get_affiliate_program_info': 1,
'get_email_language': 1,
'get_new_announcements': 1,
'get_portfolio_margins': 1,
'get_position': 1,
'get_positions': 1,
'get_subaccounts': 1,
'get_subaccounts_details': 1,
'get_transaction_log': 1,
'list_api_keys': 1,
'remove_api_key': 1,
'remove_subaccount': 1,
'reset_api_key': 1,
'set_announcement_as_read': 1,
'set_api_key_as_default': 1,
'set_email_for_subaccount': 1,
'set_email_language': 1,
'set_password_for_subaccount': 1,
'toggle_notifications_from_subaccount': 1,
'toggle_subaccount_login': 1,
// Block Trade
'execute_block_trade': 4,
'get_block_trade': 1,
'get_last_block_trades_by_currency': 1,
'invalidate_block_trade_signature': 1,
'verify_block_trade': 4,
// Trading
'buy': 4,
'sell': 4,
'edit': 4,
'edit_by_label': 4,
'cancel': 4,
'cancel_all': 4,
'cancel_all_by_currency': 4,
'cancel_all_by_instrument': 4,
'cancel_by_label': 4,
'close_position': 4,
'get_margins': 1,
'get_mmp_config': 1,
'get_open_orders_by_currency': 1,
'get_open_orders_by_instrument': 1,
'get_order_history_by_currency': 1,
'get_order_history_by_instrument': 1,
'get_order_margin_by_ids': 1,
'get_order_state': 1,
'get_stop_order_history': 1, // deprecated
'get_trigger_order_history': 1,
'get_user_trades_by_currency': 1,
'get_user_trades_by_currency_and_time': 1,
'get_user_trades_by_instrument': 1,
'get_user_trades_by_instrument_and_time': 1,
'get_user_trades_by_order': 1,
'reset_mmp': 1,
'set_mmp_config': 1,
'get_settlement_history_by_instrument': 1,
'get_settlement_history_by_currency': 1,
// Wallet
'cancel_transfer_by_id': 1,
'cancel_withdrawal': 1,
'create_deposit_address': 1,
'get_current_deposit_address': 1,
'get_deposits': 1,
'get_transfers': 1,
'get_withdrawals': 1,
'submit_transfer_to_subaccount': 1,
'submit_transfer_to_user': 1,
'withdraw': 1,
},
},
},
'exceptions': {
// 0 or absent Success, No error.
'9999': PermissionDenied, // 'api_not_enabled' User didn't enable API for the Account.
'10000': AuthenticationError, // 'authorization_required' Authorization issue, invalid or absent signature etc.
'10001': ExchangeError, // 'error' Some general failure, no public information available.
'10002': InvalidOrder, // 'qty_too_low' Order quantity is too low.
'10003': InvalidOrder, // 'order_overlap' Rejection, order overlap is found and self-trading is not enabled.
'10004': OrderNotFound, // 'order_not_found' Attempt to operate with order that can't be found by specified id.
'10005': InvalidOrder, // 'price_too_low <Limit>' Price is too low, <Limit> defines current limit for the operation.
'10006': InvalidOrder, // 'price_too_low4idx <Limit>' Price is too low for current index, <Limit> defines current bottom limit for the operation.
'10007': InvalidOrder, // 'price_too_high <Limit>' Price is too high, <Limit> defines current up limit for the operation.
'10008': InvalidOrder, // 'price_too_high4idx <Limit>' Price is too high for current index, <Limit> defines current up limit for the operation.
'10009': InsufficientFunds, // 'not_enough_funds' Account has not enough funds for the operation.
'10010': OrderNotFound, // 'already_closed' Attempt of doing something with closed order.
'10011': InvalidOrder, // 'price_not_allowed' This price is not allowed for some reason.
'10012': InvalidOrder, // 'book_closed' Operation for instrument which order book had been closed.
'10013': PermissionDenied, // 'pme_max_total_open_orders <Limit>' Total limit of open orders has been exceeded, it is applicable for PME users.
'10014': PermissionDenied, // 'pme_max_future_open_orders <Limit>' Limit of count of futures' open orders has been exceeded, it is applicable for PME users.
'10015': PermissionDenied, // 'pme_max_option_open_orders <Limit>' Limit of count of options' open orders has been exceeded, it is applicable for PME users.
'10016': PermissionDenied, // 'pme_max_future_open_orders_size <Limit>' Limit of size for futures has been exceeded, it is applicable for PME users.
'10017': PermissionDenied, // 'pme_max_option_open_orders_size <Limit>' Limit of size for options has been exceeded, it is applicable for PME users.
'10018': PermissionDenied, // 'non_pme_max_future_position_size <Limit>' Limit of size for futures has been exceeded, it is applicable for non-PME users.
'10019': PermissionDenied, // 'locked_by_admin' Trading is temporary locked by admin.
'10020': ExchangeError, // 'invalid_or_unsupported_instrument' Instrument name is not valid.
'10021': InvalidOrder, // 'invalid_amount' Amount is not valid.
'10022': InvalidOrder, // 'invalid_quantity' quantity was not recognized as a valid number (for API v1).
'10023': InvalidOrder, // 'invalid_price' price was not recognized as a valid number.
'10024': InvalidOrder, // 'invalid_max_show' max_show parameter was not recognized as a valid number.
'10025': InvalidOrder, // 'invalid_order_id' Order id is missing or its format was not recognized as valid.
'10026': InvalidOrder, // 'price_precision_exceeded' Extra precision of the price is not supported.
'10027': InvalidOrder, // 'non_integer_contract_amount' Futures contract amount was not recognized as integer.
'10028': DDoSProtection, // 'too_many_requests' Allowed request rate has been exceeded.
'10029': OrderNotFound, // 'not_owner_of_order' Attempt to operate with not own order.
'10030': ExchangeError, // 'must_be_websocket_request' REST request where Websocket is expected.
'10031': ExchangeError, // 'invalid_args_for_instrument' Some of arguments are not recognized as valid.
'10032': InvalidOrder, // 'whole_cost_too_low' Total cost is too low.
'10033': NotSupported, // 'not_implemented' Method is not implemented yet.
'10034': InvalidOrder, // 'stop_price_too_high' Stop price is too high.
'10035': InvalidOrder, // 'stop_price_too_low' Stop price is too low.
'10036': InvalidOrder, // 'invalid_max_show_amount' Max Show Amount is not valid.
'10040': ExchangeNotAvailable, // 'retry' Request can't be processed right now and should be retried.
'10041': OnMaintenance, // 'settlement_in_progress' Settlement is in progress. Every day at settlement time for several seconds, the system calculates user profits and updates balances. That time trading is paused for several seconds till the calculation is completed.
'10043': InvalidOrder, // 'price_wrong_tick' Price has to be rounded to a certain tick size.
'10044': InvalidOrder, // 'stop_price_wrong_tick' Stop Price has to be rounded to a certain tick size.
'10045': InvalidOrder, // 'can_not_cancel_liquidation_order' Liquidation order can't be canceled.
'10046': InvalidOrder, // 'can_not_edit_liquidation_order' Liquidation order can't be edited.
'10047': DDoSProtection, // 'matching_engine_queue_full' Reached limit of pending Matching Engine requests for user.
'10048': ExchangeError, // 'not_on_this_server' The requested operation is not available on this server.
'11008': InvalidOrder, // 'already_filled' This request is not allowed in regards to the filled order.
'11029': BadRequest, // 'invalid_arguments' Some invalid input has been detected.
'11030': ExchangeError, // 'other_reject <Reason>' Some rejects which are not considered as very often, more info may be specified in <Reason>.
'11031': ExchangeError, // 'other_error <Error>' Some errors which are not considered as very often, more info may be specified in <Error>.
'11035': DDoSProtection, // 'no_more_stops <Limit>' Allowed amount of stop orders has been exceeded.
'11036': InvalidOrder, // 'invalid_stoppx_for_index_or_last' Invalid StopPx (too high or too low) as to current index or market.
'11037': BadRequest, // 'outdated_instrument_for_IV_order' Instrument already not available for trading.
'11038': InvalidOrder, // 'no_adv_for_futures' Advanced orders are not available for futures.
'11039': InvalidOrder, // 'no_adv_postonly' Advanced post-only orders are not supported yet.
'11041': InvalidOrder, // 'not_adv_order' Advanced order properties can't be set if the order is not advanced.
'11042': PermissionDenied, // 'permission_denied' Permission for the operation has been denied.
'11043': BadRequest, // 'bad_argument' Bad argument has been passed.
'11044': InvalidOrder, // 'not_open_order' Attempt to do open order operations with the not open order.
'11045': BadRequest, // 'invalid_event' Event name has not been recognized.
'11046': BadRequest, // 'outdated_instrument' At several minutes to instrument expiration, corresponding advanced implied volatility orders are not allowed.
'11047': BadRequest, // 'unsupported_arg_combination' The specified combination of arguments is not supported.
'11048': ExchangeError, // 'wrong_max_show_for_option' Wrong Max Show for options.
'11049': BadRequest, // 'bad_arguments' Several bad arguments have been passed.
'11050': BadRequest, // 'bad_request' Request has not been parsed properly.
'11051': OnMaintenance, // 'system_maintenance' System is under maintenance.
'11052': ExchangeError, // 'subscribe_error_unsubscribed' Subscription error. However, subscription may fail without this error, please check list of subscribed channels returned, as some channels can be not subscribed due to wrong input or lack of permissions.
'11053': ExchangeError, // 'transfer_not_found' Specified transfer is not found.
'11090': InvalidAddress, // 'invalid_addr' Invalid address.
'11091': InvalidAddress, // 'invalid_transfer_address' Invalid addres for the transfer.
'11092': InvalidAddress, // 'address_already_exist' The address already exists.
'11093': DDoSProtection, // 'max_addr_count_exceeded' Limit of allowed addresses has been reached.
'11094': ExchangeError, // 'internal_server_error' Some unhandled error on server. Please report to admin. The details of the request will help to locate the problem.
'11095': ExchangeError, // 'disabled_deposit_address_creation' Deposit address creation has been disabled by admin.
'11096': ExchangeError, // 'address_belongs_to_user' Withdrawal instead of transfer.
'12000': AuthenticationError, // 'bad_tfa' Wrong TFA code
'12001': DDoSProtection, // 'too_many_subaccounts' Limit of subbacounts is reached.
'12002': ExchangeError, // 'wrong_subaccount_name' The input is not allowed as name of subaccount.
'12998': AuthenticationError, // 'tfa_over_limit' The number of failed TFA attempts is limited.
'12003': AuthenticationError, // 'login_over_limit' The number of failed login attempts is limited.
'12004': AuthenticationError, // 'registration_over_limit' The number of registration requests is limited.
'12005': AuthenticationError, // 'country_is_banned' The country is banned (possibly via IP check).
'12100': ExchangeError, // 'transfer_not_allowed' Transfer is not allowed. Possible wrong direction or other mistake.
'12999': AuthenticationError, // 'tfa_used' TFA code is correct but it is already used. Please, use next code.
'13000': AuthenticationError, // 'invalid_login' Login name is invalid (not allowed or it contains wrong characters).
'13001': AuthenticationError, // 'account_not_activated' Account must be activated.
'13002': PermissionDenied, // 'account_blocked' Account is blocked by admin.
'13003': AuthenticationError, // 'tfa_required' This action requires TFA authentication.
'13004': AuthenticationError, // 'invalid_credentials' Invalid credentials has been used.
'13005': AuthenticationError, // 'pwd_match_error' Password confirmation error.
'13006': AuthenticationError, // 'security_error' Invalid Security Code.
'13007': AuthenticationError, // 'user_not_found' User's security code has been changed or wrong.
'13008': ExchangeError, // 'request_failed' Request failed because of invalid input or internal failure.
'13009': AuthenticationError, // 'unauthorized' Wrong or expired authorization token or bad signature. For example, please check scope of the token, 'connection' scope can't be reused for other connections.
'13010': BadRequest, // 'value_required' Invalid input, missing value.
'13011': BadRequest, // 'value_too_short' Input is too short.
'13012': PermissionDenied, // 'unavailable_in_subaccount' Subaccount restrictions.
'13013': BadRequest, // 'invalid_phone_number' Unsupported or invalid phone number.
'13014': BadRequest, // 'cannot_send_sms' SMS sending failed -- phone number is wrong.
'13015': BadRequest, // 'invalid_sms_code' Invalid SMS code.
'13016': BadRequest, // 'invalid_input' Invalid input.
'13017': ExchangeError, // 'subscription_failed' Subscription hailed, invalid subscription parameters.
'13018': ExchangeError, // 'invalid_content_type' Invalid content type of the request.
'13019': ExchangeError, // 'orderbook_closed' Closed, expired order book.
'13020': ExchangeError, // 'not_found' Instrument is not found, invalid instrument name.
'13021': PermissionDenied, // 'forbidden' Not enough permissions to execute the request, forbidden.
'13025': ExchangeError, // 'method_switched_off_by_admin' API method temporarily switched off by administrator.
'-32602': BadRequest, // 'Invalid params' see JSON-RPC spec.
'-32601': BadRequest, // 'Method not found' see JSON-RPC spec.
'-32700': BadRequest, // 'Parse error' see JSON-RPC spec.
'-32000': BadRequest, // 'Missing params' see JSON-RPC spec.
'11054': InvalidOrder, // 'post_only_reject' post order would be filled immediately
},
'precisionMode': TICK_SIZE,
'options': {
'code': 'BTC',
'fetchBalance': {
'code': 'BTC',
},
'fetchPositions': {
'code': 'BTC',
},
'transfer': {
'method': 'privateGetSubmitTransferToSubaccount', // or 'privateGetSubmitTransferToUser'
},
},
});
}
async fetchTime (params = {}) {
/**
* @method
* @name deribit#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @param {object} params extra parameters specific to the deribit api endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
const response = await this.publicGetGetTime (params);
//
// {
// jsonrpc: '2.0',
// result: 1583922446019,
// usIn: 1583922446019955,
// usOut: 1583922446019956,
// usDiff: 1,
// testnet: false
// }
//
return this.safeInteger (response, 'result');
}
codeFromOptions (methodName, params = {}) {
const defaultCode = this.safeValue (this.options, 'code', 'BTC');
const options = this.safeValue (this.options, methodName, {});
const code = this.safeValue (options, 'code', defaultCode);
return this.safeValue (params, 'code', code);
}
async fetchStatus (params = {}) {
/**
* @method
* @name deribit#fetchStatus
* @description the latest known information on the availability of the exchange API
* @param {object} params extra parameters specific to the deribit api endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/en/latest/manual.html#exchange-status-structure}
*/
const response = await this.publicGetStatus (params);
//
// {
// "jsonrpc": "2.0",
// "result": {
// "locked": "false" // true, partial, false
// },
// "usIn": 1650641690226788,
// "usOut": 1650641690226836,
// "usDiff": 48,
// "testnet": false
// }
//
const result = this.safeValue (response, 'result');
const locked = this.safeString (result, 'locked');
const updateTime = this.safeIntegerProduct (response, 'usIn', 0.001, this.milliseconds ());
return {
'status': (locked === 'false') ? 'ok' : 'maintenance',
'updated': updateTime,
'eta': undefined,
'url': undefined,
'info': response,
};
}
async fetchAccounts (params = {}) {
/**
* @method
* @name deribit#fetchAccounts
* @description fetch all the accounts associated with a profile
* @param {object} params extra parameters specific to the deribit api endpoint
* @returns {object} a dictionary of [account structures]{@link https://docs.ccxt.com/en/latest/manual.html#account-structure} indexed by the account type
*/
await this.loadMarkets ();
const response = await this.privateGetGetSubaccounts (params);
//
// {
// jsonrpc: '2.0',
// result: [{
// username: 'someusername',
// type: 'main',
// system_name: 'someusername',
// security_keys_enabled: false,
// security_keys_assignments: [],
// receive_notifications: false,
// login_enabled: true,
// is_password: true,
// id: '238216',
// email: '[email protected]'
// },
// {
// username: 'someusername_1',
// type: 'subaccount',
// system_name: 'someusername_1',
// security_keys_enabled: false,
// security_keys_assignments: [],
// receive_notifications: false,
// login_enabled: false,
// is_password: false,
// id: '245499',
// email: '[email protected]'
// }
// ],
// usIn: '1652736468292006',
// usOut: '1652736468292377',
// usDiff: '371',
// testnet: false
// }
//
const result = this.safeValue (response, 'result', []);
return this.parseAccounts (result);
}
parseAccount (account, currency = undefined) {
//
// {
// username: 'someusername_1',
// type: 'subaccount',
// system_name: 'someusername_1',
// security_keys_enabled: false,
// security_keys_assignments: [],
// receive_notifications: false,
// login_enabled: false,
// is_password: false,
// id: '245499',
// email: '[email protected]'
// }
//
return {
'info': account,
'id': this.safeString (account, 'id'),
'type': this.safeString (account, 'type'),
'code': this.safeCurrencyCode (undefined, currency),
};
}
async fetchMarkets (params = {}) {
/**
* @method
* @name deribit#fetchMarkets
* @description retrieves data on all markets for deribit
* @param {object} params extra parameters specific to the exchange api endpoint
* @returns {[object]} an array of objects representing market data
*/
const currenciesResponse = await this.publicGetGetCurrencies (params);
//
// {
// jsonrpc: '2.0',
// result: [
// {
// withdrawal_priorities: [
// { value: 0.15, name: 'very_low' },
// { value: 1.5, name: 'very_high' },
// ],
// withdrawal_fee: 0.0005,
// min_withdrawal_fee: 0.0005,
// min_confirmations: 1,
// fee_precision: 4,
// currency_long: 'Bitcoin',
// currency: 'BTC',
// coin_type: 'BITCOIN'
// }
// ],
// usIn: 1583761588590479,
// usOut: 1583761588590544,
// usDiff: 65,
// testnet: false
// }
//
const currenciesResult = this.safeValue (currenciesResponse, 'result', []);
const result = [];
for (let i = 0; i < currenciesResult.length; i++) {
const currencyId = this.safeString (currenciesResult[i], 'currency');
const request = {
'currency': currencyId,
};
const instrumentsResponse = await this.publicGetGetInstruments (this.extend (request, params));
//
// {
// "jsonrpc":"2.0",
// "result":[
// {
// "tick_size":0.0005,
// "taker_commission":0.0003,
// "strike":52000.0,
// "settlement_period":"month",
// "settlement_currency":"BTC",
// "quote_currency":"BTC",
// "option_type":"put", // put, call
// "min_trade_amount":0.1,
// "maker_commission":0.0003,
// "kind":"option",
// "is_active":true,
// "instrument_name":"BTC-24JUN22-52000-P",
// "expiration_timestamp":1656057600000,
// "creation_timestamp":1648199543000,
// "counter_currency":"USD",
// "contract_size":1.0,
// "block_trade_commission":0.0003,
// "base_currency":"BTC"
// },
// {
// "tick_size":0.5,
// "taker_commission":0.0005,
// "settlement_period":"month", // month, week
// "settlement_currency":"BTC",
// "quote_currency":"USD",
// "min_trade_amount":10.0,
// "max_liquidation_commission":0.0075,
// "max_leverage":50,
// "maker_commission":0.0,
// "kind":"future",
// "is_active":true,
// "instrument_name":"BTC-27MAY22",
// "future_type":"reversed",
// "expiration_timestamp":1653638400000,
// "creation_timestamp":1648195209000,
// "counter_currency":"USD",
// "contract_size":10.0,
// "block_trade_commission":0.0001,
// "base_currency":"BTC"
// },
// {
// "tick_size":0.5,
// "taker_commission":0.0005,
// "settlement_period":"perpetual",
// "settlement_currency":"BTC",
// "quote_currency":"USD",
// "min_trade_amount":10.0,
// "max_liquidation_commission":0.0075,
// "max_leverage":50,
// "maker_commission":0.0,
// "kind":"future",
// "is_active":true,
// "instrument_name":"BTC-PERPETUAL",
// "future_type":"reversed",
// "expiration_timestamp":32503708800000,
// "creation_timestamp":1534242287000,
// "counter_currency":"USD",
// "contract_size":10.0,
// "block_trade_commission":0.0001,
// "base_currency":"BTC"
// },
// ],
// "usIn":1648691472831791,
// "usOut":1648691472831896,
// "usDiff":105,
// "testnet":false
// }
//
const instrumentsResult = this.safeValue (instrumentsResponse, 'result', []);
for (let k = 0; k < instrumentsResult.length; k++) {
const market = instrumentsResult[k];
const id = this.safeString (market, 'instrument_name');
const baseId = this.safeString (market, 'base_currency');
const quoteId = this.safeString (market, 'counter_currency');
const settleId = this.safeString (market, 'settlement_currency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const settle = this.safeCurrencyCode (settleId);
const kind = this.safeString (market, 'kind');
const settlementPeriod = this.safeValue (market, 'settlement_period');
const swap = (settlementPeriod === 'perpetual');
const future = !swap && (kind.indexOf ('future') >= 0);
const option = (kind.indexOf ('option') >= 0);
const isComboMarket = kind.indexOf ('combo') >= 0;
const expiry = this.safeInteger (market, 'expiration_timestamp');
let strike = undefined;
let optionType = undefined;
let symbol = id;
let type = 'swap';
if (future) {
type = 'future';
} else if (option) {
type = 'option';
}
if (!isComboMarket) {
symbol = base + '/' + quote + ':' + settle;
if (option || future) {
symbol = symbol + '-' + this.yymmdd (expiry, '');
if (option) {
strike = this.safeNumber (market, 'strike');
optionType = this.safeString (market, 'option_type');
const letter = (optionType === 'call') ? 'C' : 'P';
symbol = symbol + '-' + this.numberToString (strike) + '-' + letter;
}
}
}
const minTradeAmount = this.safeNumber (market, 'min_trade_amount');
const tickSize = this.safeNumber (market, 'tick_size');
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': false,
'margin': false,
'swap': swap,
'future': future,
'option': option,
'active': this.safeValue (market, 'is_active'),
'contract': true,
'linear': (settle === quote),
'inverse': (settle !== quote),
'taker': this.safeNumber (market, 'taker_commission'),
'maker': this.safeNumber (market, 'maker_commission'),
'contractSize': this.safeNumber (market, 'contract_size'),
'expiry': expiry,
'expiryDatetime': this.iso8601 (expiry),
'strike': strike,
'optionType': optionType,
'precision': {
'amount': minTradeAmount,
'price': tickSize,
},
'limits': {
'leverage': {
'min': undefined,
'max': undefined,
},
'amount': {
'min': minTradeAmount,
'max': undefined,
},
'price': {
'min': tickSize,
'max': undefined,
},
'cost': {
'min': undefined,
'max': undefined,
},
},
'info': market,
});
}
}
return result;
}
parseBalance (balance) {
const result = {
'info': balance,
};
const currencyId = this.safeString (balance, 'currency');
const currencyCode = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (balance, 'available_funds');
account['used'] = this.safeString (balance, 'maintenance_margin');
account['total'] = this.safeString (balance, 'equity');
result[currencyCode] = account;
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
/**
* @method
* @name deribit#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @param {object} params extra parameters specific to the deribit api endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/en/latest/manual.html?#balance-structure}
*/
await this.loadMarkets ();
const code = this.codeFromOptions ('fetchBalance', params);
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const response = await this.privateGetGetAccountSummary (this.extend (request, params));
//
// {
// jsonrpc: '2.0',
// result: {
// total_pl: 0,
// session_upl: 0,
// session_rpl: 0,
// session_funding: 0,
// portfolio_margining_enabled: false,
// options_vega: 0,
// options_theta: 0,
// options_session_upl: 0,
// options_session_rpl: 0,
// options_pl: 0,
// options_gamma: 0,
// options_delta: 0,
// margin_balance: 0.00062359,
// maintenance_margin: 0,
// limits: {
// non_matching_engine_burst: 300,
// non_matching_engine: 200,
// matching_engine_burst: 20,
// matching_engine: 2
// },
// initial_margin: 0,
// futures_session_upl: 0,
// futures_session_rpl: 0,
// futures_pl: 0,
// equity: 0.00062359,
// deposit_address: '13tUtNsJSZa1F5GeCmwBywVrymHpZispzw',
// delta_total: 0,
// currency: 'BTC',
// balance: 0.00062359,
// available_withdrawal_funds: 0.00062359,
// available_funds: 0.00062359
// },
// usIn: 1583775838115975,
// usOut: 1583775838116520,
// usDiff: 545,
// testnet: false
// }
//
const result = this.safeValue (response, 'result', {});
return this.parseBalance (result);
}
async createDepositAddress (code, params = {}) {
/**
* @method
* @name deribit#createDepositAddress
* @description create a currency deposit address
* @param {string} code unified currency code of the currency for the deposit address
* @param {object} params extra parameters specific to the deribit api endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/en/latest/manual.html#address-structure}
*/
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const response = await this.privateGetCreateDepositAddress (this.extend (request, params));
//
// {
// 'jsonrpc': '2.0',
// 'id': 7538,
// 'result': {
// 'address': '2N8udZGBc1hLRCFsU9kGwMPpmYUwMFTuCwB',
// 'creation_timestamp': 1550575165170,
// 'currency': 'BTC',
// 'type': 'deposit'
// }
// }
//
const result = this.safeValue (response, 'result', {});
const address = this.safeString (result, 'address');
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': undefined,
'info': response,
};
}
async fetchDepositAddress (code, params = {}) {
/**
* @method
* @name deribit#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @param {string} code unified currency code
* @param {object} params extra parameters specific to the deribit api endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/en/latest/manual.html#address-structure}
*/
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const response = await this.privateGetGetCurrentDepositAddress (this.extend (request, params));
//
// {
// jsonrpc: '2.0',
// result: {
// type: 'deposit',
// status: 'ready',
// requires_confirmation: true,
// currency: 'BTC',
// creation_timestamp: 1514694684651,
// address: '13tUtNsJSZa1F5GeCmwBywVrymHpZispzw'
// },
// usIn: 1583785137274288,
// usOut: 1583785137274454,
// usDiff: 166,
// testnet: false
// }
//
const result = this.safeValue (response, 'result', {});
const address = this.safeString (result, 'address');
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': undefined,
'network': undefined,
'info': response,
};
}
parseTicker (ticker, market = undefined) {
//
// fetchTicker /public/ticker
//
// {
// timestamp: 1583778859480,
// stats: { volume: 60627.57263769, low: 7631.5, high: 8311.5 },
// state: 'open',
// settlement_price: 7903.21,
// open_interest: 111543850,
// min_price: 7634,
// max_price: 7866.51,
// mark_price: 7750.02,
// last_price: 7750.5,
// instrument_name: 'BTC-PERPETUAL',
// index_price: 7748.01,
// funding_8h: 0.0000026,
// current_funding: 0,
// best_bid_price: 7750,
// best_bid_amount: 19470,
// best_ask_price: 7750.5,
// best_ask_amount: 343280
// }
//
// fetchTicker /public/get_book_summary_by_instrument
// fetchTickers /public/get_book_summary_by_currency
//
// {
// volume: 124.1,
// underlying_price: 7856.445926872601,
// underlying_index: 'SYN.BTC-10MAR20',
// quote_currency: 'USD',
// open_interest: 121.8,
// mid_price: 0.01975,
// mark_price: 0.01984559,
// low: 0.0095,
// last: 0.0205,
// interest_rate: 0,
// instrument_name: 'BTC-10MAR20-7750-C',
// high: 0.0295,
// estimated_delivery_price: 7856.29,
// creation_timestamp: 1583783678366,
// bid_price: 0.0185,
// base_currency: 'BTC',
// ask_price: 0.021
// },
//
const timestamp = this.safeInteger2 (ticker, 'timestamp', 'creation_timestamp');
const marketId = this.safeString (ticker, 'instrument_name');
const symbol = this.safeSymbol (marketId, market);
const last = this.safeString2 (ticker, 'last_price', 'last');
const stats = this.safeValue (ticker, 'stats', ticker);
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeString2 (stats, 'high', 'max_price'),
'low': this.safeString2 (stats, 'low', 'min_price'),
'bid': this.safeString2 (ticker, 'best_bid_price', 'bid_price'),
'bidVolume': this.safeString (ticker, 'best_bid_amount'),
'ask': this.safeString2 (ticker, 'best_ask_price', 'ask_price'),
'askVolume': this.safeString (ticker, 'best_ask_amount'),
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': undefined,
'quoteVolume': this.safeString (stats, 'volume'),
'info': ticker,
}, market);
}
async fetchTicker (symbol, params = {}) {
/**
* @method
* @name deribit#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} params extra parameters specific to the deribit api endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/en/latest/manual.html#ticker-structure}
*/
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'instrument_name': market['id'],
};
const response = await this.publicGetTicker (this.extend (request, params));
//
// {
// jsonrpc: '2.0',
// result: {
// timestamp: 1583778859480,
// stats: { volume: 60627.57263769, low: 7631.5, high: 8311.5 },
// state: 'open',
// settlement_price: 7903.21,
// open_interest: 111543850,
// min_price: 7634,
// max_price: 7866.51,
// mark_price: 7750.02,
// last_price: 7750.5,
// instrument_name: 'BTC-PERPETUAL',
// index_price: 7748.01,
// funding_8h: 0.0000026,
// current_funding: 0,
// best_bid_price: 7750,
// best_bid_amount: 19470,
// best_ask_price: 7750.5,
// best_ask_amount: 343280