UNPKG

sfccxt

Version:

A JavaScript / Python / PHP cryptocurrency trading library with support for 130+ exchanges

965 lines (950 loc) 127 kB
'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': undefined, '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': undefined, '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: 'pablo@abcdef.com' // }, // { // 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: 'pablo@abcdef.com' // } // ], // 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: 'pablo@abcdef.com' // } // 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 fetchTic