# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange from ccxt.abstract.digifinex import ImplicitAPI import hashlib import json from ccxt.base.types import Any, Balances, BorrowInterest, CrossBorrowRate, CrossBorrowRates, Currencies, Currency, DepositAddress, Int, LedgerEntry, LeverageTier, LeverageTiers, MarginModification, Market, Num, Order, OrderBook, OrderRequest, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, FundingRate, Trade, TradingFeeInterface, Transaction, TransferEntry from typing import List from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.base.errors import PermissionDenied from ccxt.base.errors import AccountSuspended from ccxt.base.errors import ArgumentsRequired from ccxt.base.errors import BadRequest from ccxt.base.errors import BadSymbol from ccxt.base.errors import InsufficientFunds from ccxt.base.errors import InvalidAddress from ccxt.base.errors import InvalidOrder from ccxt.base.errors import OrderNotFound from ccxt.base.errors import NotSupported from ccxt.base.errors import NetworkError from ccxt.base.errors import DDoSProtection from ccxt.base.errors import RateLimitExceeded from ccxt.base.errors import InvalidNonce from ccxt.base.errors import BadResponse from ccxt.base.decimal_to_precision import TICK_SIZE from ccxt.base.precise import Precise class digifinex(Exchange, ImplicitAPI): def describe(self) -> Any: return self.deep_extend(super(digifinex, self).describe(), { 'id': 'digifinex', 'name': 'DigiFinex', 'countries': ['SG'], 'version': 'v3', 'rateLimit': 900, # 300 for posts 'has': { 'CORS': None, 'spot': True, 'margin': True, 'swap': True, 'future': False, 'option': False, 'addMargin': True, 'cancelOrder': True, 'cancelOrders': True, 'createMarketBuyOrderWithCost': True, 'createMarketOrderWithCost': False, 'createMarketSellOrderWithCost': False, 'createOrder': True, 'createOrders': True, 'createPostOnlyOrder': True, 'createReduceOnlyOrder': True, 'createStopLimitOrder': False, 'createStopMarketOrder': False, 'createStopOrder': False, 'fetchBalance': True, 'fetchBorrowInterest': True, 'fetchBorrowRateHistories': False, 'fetchBorrowRateHistory': False, 'fetchCrossBorrowRate': True, 'fetchCrossBorrowRates': True, 'fetchCurrencies': True, 'fetchDepositAddress': True, 'fetchDepositAddresses': False, 'fetchDepositAddressesByNetwork': False, 'fetchDeposits': True, 'fetchDepositWithdrawFee': 'emulated', 'fetchDepositWithdrawFees': True, 'fetchFundingHistory': True, 'fetchFundingInterval': True, 'fetchFundingIntervals': False, 'fetchFundingRate': True, 'fetchFundingRateHistory': True, 'fetchFundingRates': False, 'fetchIndexOHLCV': False, 'fetchIsolatedBorrowRate': False, 'fetchIsolatedBorrowRates': False, 'fetchLedger': True, 'fetchLeverage': False, 'fetchLeverageTiers': True, 'fetchMarginMode': False, 'fetchMarketLeverageTiers': True, 'fetchMarkets': True, 'fetchMarkOHLCV': False, 'fetchMyTrades': True, 'fetchOHLCV': True, 'fetchOpenOrders': True, 'fetchOrder': True, 'fetchOrderBook': True, 'fetchOrders': True, 'fetchPosition': True, 'fetchPositionMode': False, 'fetchPositions': True, 'fetchPositionsRisk': False, 'fetchPremiumIndexOHLCV': False, 'fetchStatus': True, 'fetchTicker': True, 'fetchTickers': True, 'fetchTime': True, 'fetchTrades': True, 'fetchTradingFee': True, 'fetchTradingFees': False, 'fetchTransfers': True, 'fetchWithdrawals': True, 'reduceMargin': True, 'setLeverage': True, 'setMargin': False, 'setMarginMode': True, 'setPositionMode': False, 'transfer': True, 'withdraw': True, }, 'timeframes': { '1m': '1', '5m': '5', '15m': '15', '30m': '30', '1h': '60', '4h': '240', '12h': '720', '1d': '1D', '1w': '1W', }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/51840849/87443315-01283a00-c5fe-11ea-8628-c2a0feaf07ac.jpg', 'api': { 'rest': 'https://openapi.digifinex.com', }, 'www': 'https://www.digifinex.com', 'doc': [ 'https://docs.digifinex.com', ], 'fees': 'https://digifinex.zendesk.com/hc/en-us/articles/360000328422-Fee-Structure-on-DigiFinex', 'referral': 'https://www.digifinex.com/en-ww/from/DhOzBg?channelCode=ljaUPp', }, 'api': { 'public': { 'spot': { 'get': [ '{market}/symbols', 'kline', 'margin/currencies', 'margin/symbols', 'markets', 'order_book', 'ping', 'spot/symbols', 'time', 'trades', 'trades/symbols', 'ticker', 'currencies', ], }, 'swap': { 'get': [ 'public/api_weight', 'public/candles', 'public/candles_history', 'public/depth', 'public/funding_rate', 'public/funding_rate_history', 'public/instrument', 'public/instruments', 'public/ticker', 'public/tickers', 'public/time', 'public/trades', ], }, }, 'private': { 'spot': { 'get': [ '{market}/financelog', '{market}/mytrades', '{market}/order', '{market}/order/detail', '{market}/order/current', '{market}/order/history', 'margin/assets', 'margin/financelog', 'margin/mytrades', 'margin/order', 'margin/order/current', 'margin/order/history', 'margin/positions', 'otc/financelog', 'spot/assets', 'spot/financelog', 'spot/mytrades', 'spot/order', 'spot/order/current', 'spot/order/history', 'deposit/address', 'deposit/history', 'withdraw/history', ], 'post': [ '{market}/order/cancel', '{market}/order/new', '{market}/order/batch_new', 'margin/order/cancel', 'margin/order/new', 'margin/position/close', 'spot/order/cancel', 'spot/order/new', 'transfer', 'withdraw/new', 'withdraw/cancel', ], }, 'swap': { 'get': [ 'account/balance', 'account/positions', 'account/finance_record', 'account/trading_fee_rate', 'account/transfer_record', 'account/funding_fee', 'trade/history_orders', 'trade/history_trades', 'trade/open_orders', 'trade/order_info', ], 'post': [ 'account/transfer', 'account/leverage', 'account/position_mode', 'account/position_margin', 'trade/batch_cancel_order', 'trade/batch_order', 'trade/cancel_order', 'trade/order_place', 'follow/sponsor_order', 'follow/close_order', 'follow/cancel_order', 'follow/user_center_current', 'follow/user_center_history', 'follow/expert_current_open_order', 'follow/add_algo', 'follow/cancel_algo', 'follow/account_available', 'follow/plan_task', 'follow/instrument_list', ], }, }, }, 'features': { 'default': { 'sandbox': False, 'createOrder': { 'marginMode': True, 'triggerPrice': False, 'triggerPriceType': None, 'triggerDirection': False, 'stopLossPrice': False, 'takeProfitPrice': False, 'attachedStopLossTakeProfit': None, 'timeInForce': { 'IOC': False, 'FOK': False, 'PO': True, 'GTD': False, }, 'hedged': False, 'selfTradePrevention': False, 'trailing': False, 'leverage': False, 'marketBuyByCost': False, 'marketBuyRequiresPrice': False, 'iceberg': False, }, 'createOrders': { 'max': 10, }, 'fetchMyTrades': { 'marginMode': True, 'limit': 500, 'daysBack': 100000, # todo 'untilDays': 30, 'symbolRequired': False, }, 'fetchOrder': { 'marginMode': True, 'trigger': False, 'trailing': False, 'marketType': True, 'symbolRequired': True, }, 'fetchOpenOrders': { 'marginMode': True, 'limit': None, 'trigger': False, 'trailing': False, 'symbolRequired': False, }, 'fetchOrders': { 'marginMode': True, 'limit': 100, 'daysBack': 100000, # todo 'untilDays': 30, 'trigger': False, 'trailing': False, 'symbolRequired': False, }, 'fetchClosedOrders': None, 'fetchOHLCV': { 'limit': 500, }, }, 'spot': { 'extends': 'default', }, 'forDerivatives': { 'extends': 'default', 'createOrders': { 'max': 20, 'marginMode': False, }, 'fetchMyTrades': { 'marginMode': False, 'limit': 100, 'daysBack': 100000, # todo 'untilDays': 100000, # todo }, 'fetchOrder': { 'marginMode': False, }, 'fetchOpenOrders': { 'marginMode': False, 'limit': 100, }, 'fetchOrders': { 'marginMode': False, 'daysBack': 100000, # todo }, 'fetchOHLCV': { 'limit': 100, }, }, 'swap': { 'linear': { 'extends': 'forDerivatives', }, 'inverse': { 'extends': 'forDerivatives', }, }, 'future': { 'linear': None, 'inverse': None, }, }, 'fees': { 'trading': { 'tierBased': True, 'percentage': True, 'maker': self.parse_number('0.002'), 'taker': self.parse_number('0.002'), }, }, 'precisionMode': TICK_SIZE, 'exceptions': { 'exact': { '10001': [BadRequest, "Wrong request method, please check it's a GET ot POST request"], '10002': [AuthenticationError, 'Invalid ApiKey'], '10003': [AuthenticationError, "Sign doesn't match"], '10004': [BadRequest, 'Illegal request parameters'], '10005': [DDoSProtection, 'Request frequency exceeds the limit'], '10006': [PermissionDenied, 'Unauthorized to execute self request'], '10007': [PermissionDenied, 'IP address Unauthorized'], '10008': [InvalidNonce, 'Timestamp for self request is invalid, timestamp must within 1 minute'], '10009': [NetworkError, 'Unexist endpoint, please check endpoint URL'], '10011': [AccountSuspended, 'ApiKey expired. Please go to client side to re-create an ApiKey'], '20001': [PermissionDenied, 'Trade is not open for self trading pair'], '20002': [PermissionDenied, 'Trade of self trading pair is suspended'], '20003': [InvalidOrder, 'Invalid price or amount'], '20007': [InvalidOrder, 'Price precision error'], '20008': [InvalidOrder, 'Amount precision error'], '20009': [InvalidOrder, 'Amount is less than the minimum requirement'], '20010': [InvalidOrder, 'Cash Amount is less than the minimum requirement'], '20011': [InsufficientFunds, 'Insufficient balance'], '20012': [BadRequest, 'Invalid trade type, valid value: buy/sell)'], '20013': [InvalidOrder, 'No order info found'], '20014': [BadRequest, 'Invalid date, Valid format: 2018-07-25)'], '20015': [BadRequest, 'Date exceeds the limit'], '20018': [PermissionDenied, 'Your trading rights have been banned by the system'], '20019': [BadSymbol, 'Wrong trading pair symbol. Correct format:"usdt_btc". Quote asset is in the front'], '20020': [DDoSProtection, "You have violated the API operation trading rules and temporarily forbid trading. At present, we have certain restrictions on the user's transaction rate and withdrawal rate."], '50000': [ExchangeError, 'Exception error'], '20021': [BadRequest, 'Invalid currency'], '20022': [BadRequest, 'The ending timestamp must be larger than the starting timestamp'], '20023': [BadRequest, 'Invalid transfer type'], '20024': [BadRequest, 'Invalid amount'], '20025': [BadRequest, 'This currency is not transferable at the moment'], '20026': [InsufficientFunds, 'Transfer amount exceed your balance'], '20027': [PermissionDenied, 'Abnormal account status'], '20028': [PermissionDenied, 'Blacklist for transfer'], '20029': [PermissionDenied, 'Transfer amount exceed your daily limit'], '20030': [BadRequest, 'You have no position on self trading pair'], '20032': [PermissionDenied, 'Withdrawal limited'], '20033': [BadRequest, 'Wrong Withdrawal ID'], '20034': [PermissionDenied, 'Withdrawal service of self crypto has been closed'], '20035': [PermissionDenied, 'Withdrawal limit'], '20036': [ExchangeError, 'Withdrawal cancellation failed'], '20037': [InvalidAddress, 'The withdrawal address, Tag or chain type is not included in the withdrawal management list'], '20038': [InvalidAddress, 'The withdrawal address is not on the white list'], '20039': [ExchangeError, "Can't be canceled in current status"], '20040': [RateLimitExceeded, 'Withdraw too frequently; limitation: 3 times a minute, 100 times a day'], '20041': [PermissionDenied, 'Beyond the daily withdrawal limit'], '20042': [BadSymbol, 'Current trading pair does not support API trading'], '400002': [BadRequest, 'Invalid Parameter'], }, 'broad': { }, }, 'options': { 'defaultType': 'spot', 'types': ['spot', 'margin', 'otc'], 'createMarketBuyOrderRequiresPrice': True, 'accountsByType': { 'spot': '1', 'margin': '2', 'OTC': '3', }, 'networks': { 'ARBITRUM': 'Arbitrum', 'AVALANCEC': 'AVAX-CCHAIN', 'AVALANCEX': 'AVAX-XCHAIN', 'BEP20': 'BEP20', 'BSC': 'BEP20', 'CARDANO': 'Cardano', 'CELO': 'Celo', 'CHILIZ': 'Chiliz', 'COSMOS': 'COSMOS', 'CRC20': 'Crypto.com', 'CRONOS': 'Crypto.com', 'DOGECOIN': 'DogeChain', 'ERC20': 'ERC20', 'ETH': 'ERC20', 'ETHW': 'ETHW', 'IOTA': 'MIOTA', 'KLAYTN': 'KLAY', 'MATIC': 'Polygon', 'METIS': 'MetisDAO', 'MOONBEAM': 'GLMR', 'MOONRIVER': 'Moonriver', 'OPTIMISM': 'OPETH', 'POLYGON': 'Polygon', 'RIPPLE': 'XRP', 'SOLANA': 'SOL', # SOL & SPL 'STELLAR': 'Stella', # XLM 'TERRACLASSIC': 'TerraClassic', 'TERRA': 'Terra', 'TON': 'Ton', 'TRC20': 'TRC20', 'TRON': 'TRC20', 'TRX': 'TRC20', 'VECHAIN': 'Vechain', # VET }, 'networksById': { 'TRC20': 'TRC20', 'TRX': 'TRC20', 'BEP20': 'BEP20', 'BSC': 'BEP20', 'ERC20': 'ERC20', 'ETH': 'ERC20', 'Polygon': 'POLYGON', 'Crypto.com': 'CRONOS', }, }, 'commonCurrencies': { 'BHT': 'Black House Test', 'EPS': 'Epanus', 'FREE': 'FreeRossDAO', 'MBN': 'Mobilian Coin', 'TEL': 'TEL666', }, }) def fetch_currencies(self, params={}) -> Currencies: """ fetches all available currencies on an exchange :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an associative dictionary of currencies """ response = self.publicSpotGetCurrencies(params) # # { # "data":[ # { # "deposit_status":1, # "min_deposit_amount":10, # "withdraw_fee_rate":0, # "min_withdraw_amount":10, # "min_withdraw_fee":5, # "currency":"USDT", # "withdraw_fee_currency":"USDT", # "withdraw_status":0, # "chain":"OMNI" # }, # { # "deposit_status":1, # "min_deposit_amount":10, # "withdraw_fee_rate":0, # "min_withdraw_amount":10, # "min_withdraw_fee":3, # "currency":"USDT", # "withdraw_fee_currency":"USDT", # "withdraw_status":1, # "chain":"ERC20" # }, # { # "deposit_status":0, # "min_deposit_amount":0, # "withdraw_fee_rate":0, # "min_withdraw_amount":0, # "min_withdraw_fee":0, # "currency":"DGF13", # "withdraw_fee_currency":"DGF13", # "withdraw_status":0, # "chain":"" # }, # ], # "code":200 # } # data = self.safe_list(response, 'data', []) groupedById = self.group_by(data, 'currency') keys = list(groupedById.keys()) result: dict = {} for i in range(0, len(keys)): id = keys[i] networkEntries = groupedById[id] code = self.safe_currency_code(id) networks = {} for j in range(0, len(networkEntries)): networkEntry = networkEntries[j] networkId = self.safe_string_2(networkEntry, 'chain', 'currency') networkCode = self.network_id_to_code(networkId) networks[networkCode] = { 'id': networkId, 'network': networkCode, 'active': None, 'deposit': self.safe_integer(networkEntry, 'deposit_status') == 1, 'withdraw': self.safe_integer(networkEntry, 'withdraw_status') == 1, 'fee': self.safe_number(networkEntry, 'min_withdraw_fee'), 'precision': None, 'limits': { 'withdraw': { 'min': self.safe_number(networkEntry, 'min_withdraw_amount'), 'max': None, }, 'deposit': { 'min': self.safe_number(networkEntry, 'min_deposit_amount'), 'max': None, }, }, 'info': networkEntry, } result[code] = self.safe_currency_structure({ 'id': id, 'code': code, 'info': networkEntries, 'networks': networks, }) return result def fetch_markets(self, params={}) -> List[Market]: """ retrieves data on all markets for digifinex :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: an array of objects representing market data """ options = self.safe_value(self.options, 'fetchMarkets', {}) method = self.safe_string(options, 'method', 'fetch_markets_v2') if method == 'fetch_markets_v2': return self.fetch_markets_v2(params) return self.fetch_markets_v1(params) def fetch_markets_v2(self, params={}): defaultType = self.safe_string(self.options, 'defaultType') marginMode, query = self.handle_margin_mode_and_params('fetchMarketsV2', params) promisesRaw = [] if marginMode is not None: promisesRaw.append(self.publicSpotGetMarginSymbols(query)) else: promisesRaw.append(self.publicSpotGetTradesSymbols(query)) promisesRaw.append(self.publicSwapGetPublicInstruments(params)) promises = promisesRaw spotMarkets = promises[0] swapMarkets = promises[1] # # spot and margin # # { # "symbol_list":[ # { # "order_types":["LIMIT","MARKET"], # "quote_asset":"USDT", # "minimum_value":2, # "amount_precision":4, # "status":"TRADING", # "minimum_amount":0.0001, # "symbol":"BTC_USDT", # "is_allow":1, # "zone":"MAIN", # "base_asset":"BTC", # "price_precision":2 # } # ], # "code":0 # } # # swap # # { # "code": 0, # "data": [ # { # "instrument_id": "BTCUSDTPERP", # "type": "REAL", # "contract_type": "PERPETUAL", # "base_currency": "BTC", # "quote_currency": "USDT", # "clear_currency": "USDT", # "contract_value": "0.001", # "contract_value_currency": "BTC", # "is_inverse": False, # "is_trading": True, # "status": "ONLINE", # "price_precision": 4, # "tick_size": "0.0001", # "min_order_amount": 1, # "open_max_limits": [ # { # "leverage": "50", # "max_limit": "1000000" # } # ] # }, # ] # } # spotData = self.safe_value(spotMarkets, 'symbol_list', []) swapData = self.safe_value(swapMarkets, 'data', []) response = self.array_concat(spotData, swapData) result = [] for i in range(0, len(response)): market = response[i] id = self.safe_string_2(market, 'symbol', 'instrument_id') baseId = self.safe_string_2(market, 'base_asset', 'base_currency') quoteId = self.safe_string_2(market, 'quote_asset', 'quote_currency') settleId = self.safe_string(market, 'clear_currency') base = self.safe_currency_code(baseId) quote = self.safe_currency_code(quoteId) settle = self.safe_currency_code(settleId) # # The status is documented in the exchange API docs: # TRADING, HALT(delisted), BREAK(trading paused) # https://docs.digifinex.vip/en-ww/v3/#/public/spot/symbols # However, all spot markets actually have status == 'HALT' # despite that they appear to be active on the exchange website. # Apparently, we can't trust self status. # status = self.safe_string(market, 'status') # active = (status == 'TRADING') # isAllowed = self.safe_integer(market, 'is_allow', 1) type = 'margin' if (defaultType == 'margin') else 'spot' spot = settle is None swap = not spot margin = True if (marginMode is not None) else None symbol = base + '/' + quote isInverse = None isLinear = None if swap: type = 'swap' symbol = base + '/' + quote + ':' + settle isInverse = self.safe_value(market, 'is_inverse') isLinear = True if (not isInverse) else False isTrading = self.safe_value(market, 'isTrading') if isTrading: isAllowed = 1 result.append({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'settle': settle, 'baseId': baseId, 'quoteId': quoteId, 'settleId': settleId, 'type': type, 'spot': spot, 'margin': margin, 'swap': swap, 'future': False, 'option': False, 'active': True if isAllowed else False, 'contract': swap, 'linear': isLinear, 'inverse': isInverse, 'contractSize': self.safe_number(market, 'contract_value'), 'expiry': None, 'expiryDatetime': None, 'strike': None, 'optionType': None, 'precision': { 'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'amount_precision'))), 'price': self.parse_number(self.parse_precision(self.safe_string(market, 'price_precision'))), }, 'limits': { 'leverage': { 'min': None, 'max': None, }, 'amount': { 'min': self.safe_number_2(market, 'minimum_amount', 'min_order_amount'), 'max': None, }, 'price': { 'min': self.safe_number(market, 'tick_size'), 'max': None, }, 'cost': { 'min': self.safe_number(market, 'minimum_value'), 'max': None, }, }, 'created': None, 'info': market, }) return result def fetch_markets_v1(self, params={}): response = self.publicSpotGetMarkets(params) # # { # "data": [ # { # "volume_precision":4, # "price_precision":2, # "market":"btc_usdt", # "min_amount":2, # "min_volume":0.0001 # }, # ], # "date":1564507456, # "code":0 # } # markets = self.safe_value(response, 'data', []) result = [] for i in range(0, len(markets)): market = markets[i] id = self.safe_string(market, 'market') baseId, quoteId = id.split('_') base = self.safe_currency_code(baseId) quote = self.safe_currency_code(quoteId) result.append({ 'id': id, 'symbol': base + '/' + quote, 'base': base, 'quote': quote, 'settle': None, 'baseId': baseId, 'quoteId': quoteId, 'settleId': None, 'type': 'spot', 'spot': True, 'margin': None, 'swap': False, 'future': False, 'option': False, 'active': None, 'contract': False, 'linear': None, 'inverse': None, 'contractSize': None, 'expiry': None, 'expiryDatetime': None, 'strike': None, 'optionType': None, 'precision': { 'price': self.parse_number(self.parse_precision(self.safe_string(market, 'price_precision'))), 'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'volume_precision'))), }, 'limits': { 'leverage': { 'min': None, 'max': None, }, 'amount': { 'min': self.safe_number(market, 'min_volume'), 'max': None, }, 'price': { 'min': None, 'max': None, }, 'cost': { 'min': self.safe_number(market, 'min_amount'), 'max': None, }, }, 'info': market, }) return result def parse_balance(self, response) -> Balances: # # spot and margin # # { # "currency": "BTC", # "free": 4723846.89208129, # "total": 0 # } # # swap # # { # "equity": "0", # "currency": "BTC", # "margin": "0", # "frozen_margin": "0", # "frozen_money": "0", # "margin_ratio": "0", # "realized_pnl": "0", # "avail_balance": "0", # "unrealized_pnl": "0", # "time_stamp": 1661487402396 # } # result: dict = {'info': response} for i in range(0, len(response)): balance = response[i] currencyId = self.safe_string(balance, 'currency') code = self.safe_currency_code(currencyId) account = self.account() free = self.safe_string_2(balance, 'free', 'avail_balance') total = self.safe_string_2(balance, 'total', 'equity') account['free'] = free account['used'] = Precise.string_sub(total, free) account['total'] = total result[code] = account return self.safe_balance(result) def fetch_balance(self, params={}) -> Balances: """ query for balance and get the amount of funds available for trading or funds locked in orders https://docs.digifinex.com/en-ww/spot/v3/rest.html#spot-account-assets https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-assets https://docs.digifinex.com/en-ww/swap/v2/rest.html#accountbalance :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `balance structure ` """ self.load_markets() marketType = None marketType, params = self.handle_market_type_and_params('fetchBalance', None, params) marginMode, query = self.handle_margin_mode_and_params('fetchBalance', params) response = None if marginMode is not None or marketType == 'margin': marketType = 'margin' response = self.privateSpotGetMarginAssets(query) elif marketType == 'spot': response = self.privateSpotGetSpotAssets(query) elif marketType == 'swap': response = self.privateSwapGetAccountBalance(query) else: raise NotSupported(self.id + ' fetchBalance() not support self market type') # # spot and margin # # { # "code": 0, # "list": [ # { # "currency": "BTC", # "free": 4723846.89208129, # "total": 0 # }, # ... # ] # } # # swap # # { # "code": 0, # "data": [ # { # "equity": "0", # "currency": "BTC", # "margin": "0", # "frozen_margin": "0", # "frozen_money": "0", # "margin_ratio": "0", # "realized_pnl": "0", # "avail_balance": "0", # "unrealized_pnl": "0", # "time_stamp": 1661487402396 # }, # ... # ] # } # balanceRequest = 'data' if (marketType == 'swap') else 'list' balances = self.safe_value(response, balanceRequest, []) return self.parse_balance(balances) def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook: """ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-orderbook https://docs.digifinex.com/en-ww/swap/v2/rest.html#orderbook :param str symbol: unified symbol of the market to fetch the order book for :param int [limit]: the maximum amount of order book entries to return :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: A dictionary of `order book structures ` indexed by market symbols """ self.load_markets() market = self.market(symbol) marketType, query = self.handle_market_type_and_params('fetchOrderBook', market, params) request: dict = {} if limit is not None: request['limit'] = limit response = None if marketType == 'swap': request['instrument_id'] = market['id'] response = self.publicSwapGetPublicDepth(self.extend(request, query)) else: request['symbol'] = market['id'] response = self.publicSpotGetOrderBook(self.extend(request, query)) # # spot # # { # "bids": [ # [9605.77,0.0016], # [9605.46,0.0003], # [9602.04,0.0127], # ], # "asks": [ # [9627.22,0.025803], # [9627.12,0.168543], # [9626.52,0.0011529], # ], # "date":1564509499, # "code":0 # } # # swap # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "timestamp": 1667975290425, # "asks": [ # ["18384.7",3492], # ["18402.7",5000], # ["18406.7",5000], # ], # "bids": [ # ["18366.2",4395], # ["18364.3",3070], # ["18359.4",5000], # ] # } # } # timestamp = None orderBook = None if marketType == 'swap': orderBook = self.safe_value(response, 'data', {}) timestamp = self.safe_integer(orderBook, 'timestamp') else: orderBook = response timestamp = self.safe_timestamp(response, 'date') return self.parse_order_book(orderBook, market['symbol'], timestamp) def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers: """ fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market https://docs.digifinex.com/en-ww/spot/v3/rest.html#ticker-price https://docs.digifinex.com/en-ww/swap/v2/rest.html#tickers :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a dictionary of `ticker structures ` """ self.load_markets() symbols = self.market_symbols(symbols) first = self.safe_string(symbols, 0) market = None if first is not None: market = self.market(first) type = None type, params = self.handle_market_type_and_params('fetchTickers', market, params) request: dict = {} response = None if type == 'swap': response = self.publicSwapGetPublicTickers(self.extend(request, params)) else: response = self.publicSpotGetTicker(self.extend(request, params)) # # spot # # { # "ticker": [{ # "vol": 40717.4461, # "change": -1.91, # "base_vol": 392447999.65374, # "sell": 9592.23, # "last": 9592.22, # "symbol": "btc_usdt", # "low": 9476.24, # "buy": 9592.03, # "high": 9793.87 # }], # "date": 1589874294, # "code": 0 # } # # swap # # { # "code": 0, # "data": [ # { # "instrument_id": "SUSHIUSDTPERP", # "index_price": "1.1297", # "mark_price": "1.1289", # "max_buy_price": "1.1856", # "min_sell_price": "1.0726", # "best_bid": "1.1278", # "best_bid_size": "500", # "best_ask": "1.1302", # "best_ask_size": "471", # "high_24h": "1.2064", # "open_24h": "1.1938", # "low_24h": "1.1239", # "last": "1.1302", # "last_qty": "29", # "volume_24h": "4946163", # "price_change_percent": "-0.053275255486681085", # "open_interest": "-", # "timestamp": 1663222782100 # }, # ... # ] # } # result: dict = {} tickers = self.safe_value_2(response, 'ticker', 'data', []) date = self.safe_integer(response, 'date') for i in range(0, len(tickers)): rawTicker = self.extend({ 'date': date, }, tickers[i]) ticker = self.parse_ticker(rawTicker) symbol = ticker['symbol'] result[symbol] = ticker return self.filter_by_array_tickers(result, 'symbol', symbols) def fetch_ticker(self, symbol: str, params={}) -> Ticker: """ fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market https://docs.digifinex.com/en-ww/spot/v3/rest.html#ticker-price https://docs.digifinex.com/en-ww/swap/v2/rest.html#ticker :param str symbol: unified symbol of the market to fetch the ticker for :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `ticker structure ` """ self.load_markets() market = self.market(symbol) request: dict = {} response = None if market['swap']: request['instrument_id'] = market['id'] response = self.publicSwapGetPublicTicker(self.extend(request, params)) else: request['symbol'] = market['id'] response = self.publicSpotGetTicker(self.extend(request, params)) # # spot # # { # "ticker": [{ # "vol": 40717.4461, # "change": -1.91, # "base_vol": 392447999.65374, # "sell": 9592.23, # "last": 9592.22, # "symbol": "btc_usdt", # "low": 9476.24, # "buy": 9592.03, # "high": 9793.87 # }], # "date": 1589874294, # "code": 0 # } # # swap # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "index_price": "20141.9967", # "mark_price": "20139.3404", # "max_buy_price": "21146.4838", # "min_sell_price": "19132.2725", # "best_bid": "20140.0998", # "best_bid_size": "3116", # "best_ask": "20140.0999", # "best_ask_size": "9004", # "high_24h": "20410.6496", # "open_24h": "20308.6998", # "low_24h": "19600", # "last": "20140.0999", # "last_qty": "2", # "volume_24h": "49382816", # "price_change_percent": "-0.008301855936636448", # "open_interest": "-", # "timestamp": 1663221614998 # } # } # date = self.safe_integer(response, 'date') tickers = self.safe_value(response, 'ticker', []) data = self.safe_value(response, 'data', {}) firstTicker = self.safe_value(tickers, 0, {}) result = None if market['swap']: result = data else: result = self.extend({'date': date}, firstTicker) return self.parse_ticker(result, market) def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker: # # spot: fetchTicker, fetchTickers # # { # "last":0.021957, # "symbol": "btc_usdt", # "base_vol":2249.3521732227, # "change":-0.6, # "vol":102443.5111, # "sell":0.021978, # "low":0.021791, # "buy":0.021946, # "high":0.022266, # "date"1564518452, # injected from fetchTicker/fetchTickers # } # # swap: fetchTicker, fetchTickers # # { # "instrument_id": "BTCUSDTPERP", # "index_price": "20141.9967", # "mark_price": "20139.3404", # "max_buy_price": "21146.4838", # "min_sell_price": "19132.2725", # "best_bid": "20140.0998", # "best_bid_size": "3116", # "best_ask": "20140.0999", # "best_ask_size": "9004", # "high_24h": "20410.6496", # "open_24h": "20308.6998", # "low_24h": "19600", # "last": "20140.0999", # "last_qty": "2", # "volume_24h": "49382816", # "price_change_percent": "-0.008301855936636448", # "open_interest": "-", # "timestamp": 1663221614998 # } # indexPrice = self.safe_number(ticker, 'index_price') marketType = 'contract' if (indexPrice is not None) else 'spot' marketId = self.safe_string_upper_2(ticker, 'symbol', 'instrument_id') symbol = self.safe_symbol(marketId, market, None, marketType) market = self.safe_market(marketId, market, None, marketType) timestamp = self.safe_timestamp(ticker, 'date') if market['swap']: timestamp = self.safe_integer(ticker, 'timestamp') last = self.safe_string(ticker, 'last') return self.safe_ticker({ 'symbol': symbol, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'high': self.safe_string_2(ticker, 'high', 'high_24h'), 'low': self.safe_string_2(ticker, 'low', 'low_24h'), 'bid': self.safe_string_2(ticker, 'buy', 'best_bid'), 'bidVolume': self.safe_string(ticker, 'best_bid_size'), 'ask': self.safe_string_2(ticker, 'sell', 'best_ask'), 'askVolume': self.safe_string(ticker, 'best_ask_size'), 'vwap': None, 'open': self.safe_string(ticker, 'open_24h'), 'close': last, 'last': last, 'previousClose': None, 'change': None, 'percentage': self.safe_string_2(ticker, 'change', 'price_change_percent'), 'average': None, 'baseVolume': self.safe_string_2(ticker, 'vol', 'volume_24h'), 'quoteVolume': self.safe_string(ticker, 'base_vol'), 'markPrice': self.safe_string(ticker, 'mark_price'), 'indexPrice': indexPrice, 'info': ticker, }, market) def parse_trade(self, trade: dict, market: Market = None) -> Trade: # # spot: fetchTrades # # { # "date":1564520003, # "id":1596149203, # "amount":0.7073, # "type":"buy", # "price":0.02193, # } # # swap: fetchTrades # # { # "instrument_id": "BTCUSDTPERP", # "trade_id": "1595190773677035521", # "direction": "4", # "volume": "4", # "price": "16188.3", # "trade_time": 1669158092314 # } # # spot: fetchMyTrades # # { # "symbol": "BTC_USDT", # "order_id": "6707cbdcda0edfaa7f4ab509e4cbf966", # "id": 28457, # "price": 0.1, # "amount": 0, # "fee": 0.096, # "fee_currency": "USDT", # "timestamp": 1499865549, # "side": "buy", # or "side": "sell_market" # "is_maker": True # } # # swap: fetchMyTrades # # { # "trade_id": "1590136768424841218", # "instrument_id": "BTCUSDTPERP", # "order_id": "1590136768156405760", # "type": 1, # "order_type": 8, # "price": "18514.5", # "size": "1", # "fee": "0.00925725", # "close_profit": "0", # "leverage": "20", # "trade_type": 0, # "match_role": 1, # "trade_time": 1667953123562 # } # id = self.safe_string_2(trade, 'id', 'trade_id') orderId = self.safe_string(trade, 'order_id') priceString = self.safe_string(trade, 'price') amountString = self.safe_string_n(trade, ['amount', 'volume', 'size']) marketId = self.safe_string_upper_2(trade, 'symbol', 'instrument_id') symbol = self.safe_symbol(marketId, market) if market is None: market = self.safe_market(marketId) timestamp = self.safe_timestamp_2(trade, 'date', 'timestamp') side = self.safe_string_2(trade, 'type', 'side') type = None takerOrMaker = None if market['type'] == 'swap': timestamp = self.safe_integer(trade, 'trade_time') orderType = self.safe_string(trade, 'order_type') tradeRole = self.safe_string(trade, 'match_role') direction = self.safe_string(trade, 'direction') if orderType is not None: type = 'limit' if (orderType == '0') else None if tradeRole == '1': takerOrMaker = 'taker' elif tradeRole == '2': takerOrMaker = 'maker' else: takerOrMaker = None if (side == '1') or (direction == '1'): # side = 'open long' side = 'buy' elif (side == '2') or (direction == '2'): # side = 'open short' side = 'sell' elif (side == '3') or (direction == '3'): # side = 'close long' side = 'sell' elif (side == '4') or (direction == '4'): # side = 'close short' side = 'buy' else: parts = side.split('_') side = self.safe_string(parts, 0) type = self.safe_string(parts, 1) if type is None: type = 'limit' isMaker = self.safe_value(trade, 'is_maker') takerOrMaker = 'maker' if isMaker else 'taker' fee = None feeCostString = self.safe_string(trade, 'fee') if feeCostString is not None: feeCurrencyId = self.safe_string(trade, 'fee_currency') feeCurrencyCode = None if feeCurrencyId is not None: feeCurrencyCode = self.safe_currency_code(feeCurrencyId) fee = { 'cost': feeCostString, 'currency': feeCurrencyCode, } return self.safe_trade({ 'id': id, 'info': trade, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': symbol, 'type': type, 'order': orderId, 'side': side, 'price': priceString, 'amount': amountString, 'cost': None, 'takerOrMaker': takerOrMaker, 'fee': fee, }, market) def fetch_time(self, params={}) -> Int: """ fetches the current integer timestamp in milliseconds from the exchange server :param dict [params]: extra parameters specific to the exchange API endpoint :returns int: the current integer timestamp in milliseconds from the exchange server """ response = self.publicSpotGetTime(params) # # { # "server_time": 1589873762, # "code": 0 # } # return self.safe_timestamp(response, 'server_time') def fetch_status(self, params={}): """ the latest known information on the availability of the exchange API :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `status structure ` """ response = self.publicSpotGetPing(params) # # { # "msg": "pong", # "code": 0 # } # code = self.safe_integer(response, 'code') status = 'ok' if (code == 0) else 'maintenance' return { 'status': status, 'updated': None, 'eta': None, 'url': None, 'info': response, } def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]: """ get the list of most recent trades for a particular symbol https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-recent-trades https://docs.digifinex.com/en-ww/swap/v2/rest.html#recenttrades :param str symbol: unified symbol of the market to fetch trades for :param int [since]: timestamp in ms of the earliest trade to fetch :param int [limit]: the maximum amount of trades to fetch :param dict [params]: extra parameters specific to the exchange API endpoint :returns Trade[]: a list of `trade structures ` """ self.load_markets() market = self.market(symbol) request: dict = {} if limit is not None: request['limit'] = min(limit, 100) if market['swap'] else limit response = None if market['swap']: request['instrument_id'] = market['id'] response = self.publicSwapGetPublicTrades(self.extend(request, params)) else: request['symbol'] = market['id'] response = self.publicSpotGetTrades(self.extend(request, params)) # # spot # # { # "data":[ # { # "date":1564520003, # "id":1596149203, # "amount":0.7073, # "type":"buy", # "price":0.02193, # }, # { # "date":1564520002, # "id":1596149165, # "amount":0.3232, # "type":"sell", # "price":0.021927, # }, # ], # "code": 0, # "date": 1564520003, # } # # swap # # { # "code": 0, # "data": [ # { # "instrument_id": "BTCUSDTPERP", # "trade_id": "1595190773677035521", # "direction": "4", # "volume": "4", # "price": "16188.3", # "trade_time": 1669158092314 # }, # ... # ] # } # data = self.safe_list(response, 'data', []) return self.parse_trades(data, market, since, limit) def parse_ohlcv(self, ohlcv, market: Market = None) -> list: # # [ # 1556712900, # 2205.899, # 0.029967, # 0.02997, # 0.029871, # 0.029927 # ] # if market['swap']: return [ self.safe_integer(ohlcv, 0), self.safe_number(ohlcv, 1), # open self.safe_number(ohlcv, 2), # high self.safe_number(ohlcv, 3), # low self.safe_number(ohlcv, 4), # close self.safe_number(ohlcv, 5), # volume ] else: return [ self.safe_timestamp(ohlcv, 0), self.safe_number(ohlcv, 5), # open self.safe_number(ohlcv, 3), # high self.safe_number(ohlcv, 4), # low self.safe_number(ohlcv, 2), # close self.safe_number(ohlcv, 1), # volume ] def fetch_ohlcv(self, symbol: str, timeframe: str = '1m', since: Int = None, limit: Int = None, params={}) -> List[list]: """ fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-candles-data https://docs.digifinex.com/en-ww/swap/v2/rest.html#recentcandle :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param int [since]: timestamp in ms of the earliest candle to fetch :param int [limit]: the maximum amount of candles to fetch :param dict [params]: extra parameters specific to the exchange API endpoint :param int [params.until]: timestamp in ms of the latest candle to fetch :returns int[][]: A list of candles ordered, open, high, low, close, volume """ self.load_markets() market = self.market(symbol) request: dict = {} response = None if market['swap']: request['instrument_id'] = market['id'] request['granularity'] = timeframe if limit is not None: request['limit'] = min(limit, 100) response = self.publicSwapGetPublicCandles(self.extend(request, params)) else: until = self.safe_integer(params, 'until') request['symbol'] = market['id'] request['period'] = self.safe_string(self.timeframes, timeframe, timeframe) startTime = since duration = self.parse_timeframe(timeframe) if startTime is None: if (limit is not None) or (until is not None): endTime = until if (until is not None) else self.milliseconds() startLimit = limit if (limit is not None) else 200 startTime = endTime - (startLimit * duration * 1000) if startTime is not None: startTime = self.parse_to_int(startTime / 1000) request['start_time'] = startTime if (limit is not None) or (until is not None): if until is not None: endByUntil = self.parse_to_int(until / 1000) if limit is not None: endByLimit = self.sum(startTime, limit * duration) request['end_time'] = min(endByLimit, endByUntil) else: request['end_time'] = endByUntil else: request['end_time'] = self.sum(startTime, limit * duration) params = self.omit(params, 'until') response = self.publicSpotGetKline(self.extend(request, params)) # # spot # # { # "code":0, # "data":[ # [1556712900,2205.899,0.029967,0.02997,0.029871,0.029927], # [1556713800,1912.9174,0.029992,0.030014,0.029955,0.02996], # [1556714700,1556.4795,0.029974,0.030019,0.029969,0.02999], # ] # } # # swap # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "granularity": "1m", # "candles": [ # [1588089660000,"6900","6900","6900","6900","0","0"], # [1588089720000,"6900","6900","6900","6900","0","0"], # [1588089780000,"6900","6900","6900","6900","0","0"], # ] # } # } # candles = None if market['swap']: data = self.safe_value(response, 'data', {}) candles = self.safe_value(data, 'candles', []) else: candles = self.safe_value(response, 'data', []) return self.parse_ohlcvs(candles, market, timeframe, since, limit) def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}): """ create a trade order https://docs.digifinex.com/en-ww/spot/v3/rest.html#create-new-order https://docs.digifinex.com/en-ww/swap/v2/rest.html#orderplace :param str symbol: unified symbol of the market to create an order in :param str type: 'market' or 'limit' :param str side: 'buy' or 'sell' :param float amount: how much you want to trade in units of the base currency, spot market orders use the quote currency, swap requires the number of contracts :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders :param dict [params]: extra parameters specific to the exchange API endpoint :param str [params.timeInForce]: "GTC", "IOC", "FOK", or "PO" :param bool [params.postOnly]: True or False :param bool [params.reduceOnly]: True or False :param str [params.marginMode]: 'cross' or 'isolated', for spot margin trading :param float [params.cost]: *spot market buy only* the quote quantity that can be used alternative for the amount :returns dict: an `order structure ` """ self.load_markets() market = self.market(symbol) marginResult = self.handle_margin_mode_and_params('createOrder', params) marginMode = marginResult[0] request = self.create_order_request(symbol, type, side, amount, price, params) response = None if market['swap']: response = self.privateSwapPostTradeOrderPlace(request) else: if marginMode is not None: response = self.privateSpotPostMarginOrderNew(request) else: response = self.privateSpotPostSpotOrderNew(request) # # spot and margin # # { # "code": 0, # "order_id": "198361cecdc65f9c8c9bb2fa68faec40" # } # # swap # # { # "code": 0, # "data": "1590873693003714560" # } # order = self.parse_order(response, market) order['symbol'] = market['symbol'] order['type'] = type order['side'] = side order['amount'] = amount order['price'] = price return order def create_orders(self, orders: List[OrderRequest], params={}): """ create a list of trade orders(all orders should be of the same symbol) https://docs.digifinex.com/en-ww/spot/v3/rest.html#create-multiple-order https://docs.digifinex.com/en-ww/swap/v2/rest.html#batchorder :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an `order structure ` """ self.load_markets() ordersRequests = [] symbol = None marginMode = None for i in range(0, len(orders)): rawOrder = orders[i] marketId = self.safe_string(rawOrder, 'symbol') if symbol is None: symbol = marketId else: if symbol != marketId: raise BadRequest(self.id + ' createOrders() requires all orders to have the same symbol') type = self.safe_string(rawOrder, 'type') side = self.safe_string(rawOrder, 'side') amount = self.safe_value(rawOrder, 'amount') price = self.safe_value(rawOrder, 'price') orderParams = self.safe_value(rawOrder, 'params', {}) marginResult = self.handle_margin_mode_and_params('createOrders', orderParams) currentMarginMode = marginResult[0] if currentMarginMode is not None: if marginMode is None: marginMode = currentMarginMode else: if marginMode != currentMarginMode: raise BadRequest(self.id + ' createOrders() requires all orders to have the same margin mode(isolated or cross)') orderRequest = self.create_order_request(marketId, type, side, amount, price, orderParams) ordersRequests.append(orderRequest) market = self.market(symbol) request: dict = {} response = None if market['swap']: response = self.privateSwapPostTradeBatchOrder(ordersRequests) else: request['market'] = 'margin' if (marginMode is not None) else 'spot' request['symbol'] = market['id'] request['list'] = self.json(ordersRequests) response = self.privateSpotPostMarketOrderBatchNew(request) # # spot # # { # "code": 0, # "order_ids": [ # "064290fbe2d26e7b28d7e6c0a5cf70a5", # "24c8f9b73d81e4d9d8d7e3280281c258" # ] # } # # swap # # { # "code": 0, # "data": [ # "1720297963537829888", # "1720297963537829889" # ] # } # data = [] if market['swap']: data = self.safe_value(response, 'data', []) else: data = self.safe_value(response, 'order_ids', []) result = [] for i in range(0, len(orders)): rawOrder = orders[i] individualOrder: dict = {} individualOrder['order_id'] = data[i] individualOrder['instrument_id'] = market['id'] individualOrder['amount'] = self.safe_number(rawOrder, 'amount') individualOrder['price'] = self.safe_number(rawOrder, 'price') result.append(individualOrder) return self.parse_orders(result, market) def create_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}): """ @ignore helper function to build request :param str symbol: unified symbol of the market to create an order in :param str type: 'market' or 'limit' :param str side: 'buy' or 'sell' :param float amount: how much you want to trade in units of the base currency, spot market orders use the quote currency, swap requires the number of contracts :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: request to be sent to the exchange """ market = self.market(symbol) marketType = None marginMode = None marketType, params = self.handle_market_type_and_params('createOrderRequest', market, params) marginMode, params = self.handle_margin_mode_and_params('createOrderRequest', params) if marginMode is not None: marketType = 'margin' request: dict = {} swap = (marketType == 'swap') isMarketOrder = (type == 'market') isLimitOrder = (type == 'limit') marketIdRequest = 'instrument_id' if swap else 'symbol' request[marketIdRequest] = market['id'] postOnly = self.is_post_only(isMarketOrder, False, params) postOnlyParsed = None if swap: reduceOnly = self.safe_bool(params, 'reduceOnly', False) timeInForce = self.safe_string(params, 'timeInForce') orderType = None if side == 'buy': requestType = 4 if (reduceOnly) else 1 request['type'] = requestType else: requestType = 3 if (reduceOnly) else 2 request['type'] = requestType if isLimitOrder: orderType = 0 if timeInForce == 'FOK': orderType = 15 if isMarketOrder else 9 elif timeInForce == 'IOC': orderType = 13 if isMarketOrder else 4 elif (timeInForce == 'GTC') or (isMarketOrder): orderType = 14 elif timeInForce == 'PO': postOnly = True if price is not None: request['price'] = self.price_to_precision(symbol, price) request['order_type'] = orderType request['size'] = amount # swap orders require the amount to be the number of contracts params = self.omit(params, ['reduceOnly', 'timeInForce']) else: postOnlyParsed = 1 if (postOnly is True) else 2 request['market'] = marketType suffix = '' if type == 'market': suffix = '_market' else: request['price'] = self.price_to_precision(symbol, price) request['type'] = side + suffix # limit orders require the amount in the base currency, market orders require the amount in the quote currency quantity = None createMarketBuyOrderRequiresPrice = True createMarketBuyOrderRequiresPrice, params = self.handle_option_and_params(params, 'createOrderRequest', 'createMarketBuyOrderRequiresPrice', True) if isMarketOrder and (side == 'buy'): cost = self.safe_number(params, 'cost') params = self.omit(params, 'cost') if cost is not None: quantity = self.cost_to_precision(symbol, cost) elif createMarketBuyOrderRequiresPrice: if price is None: raise InvalidOrder(self.id + ' createOrder() requires a price argument for market buy orders on spot markets to calculate the total amount to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to False and pass the cost to spend in the amount argument') else: amountString = self.number_to_string(amount) priceString = self.number_to_string(price) costRequest = self.parse_number(Precise.string_mul(amountString, priceString)) quantity = self.cost_to_precision(symbol, costRequest) else: quantity = self.cost_to_precision(symbol, amount) else: quantity = self.amount_to_precision(symbol, amount) request['amount'] = quantity if postOnly: if postOnlyParsed: request['post_only'] = postOnlyParsed else: request['post_only'] = postOnly params = self.omit(params, ['postOnly']) return self.extend(request, params) def create_market_buy_order_with_cost(self, symbol: str, cost: float, params={}): """ create a market buy order by providing the symbol and cost https://docs.digifinex.com/en-ww/spot/v3/rest.html#create-new-order :param str symbol: unified symbol of the market to create an order in :param float cost: how much you want to trade in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an `order structure ` """ self.load_markets() market = self.market(symbol) if not market['spot']: raise NotSupported(self.id + ' createMarketBuyOrderWithCost() supports spot orders only') params['createMarketBuyOrderRequiresPrice'] = False return self.create_order(symbol, 'market', 'buy', cost, None, params) def cancel_order(self, id: str, symbol: Str = None, params={}): """ cancels an open order https://docs.digifinex.com/en-ww/spot/v3/rest.html#cancel-order https://docs.digifinex.com/en-ww/swap/v2/rest.html#cancelorder :param str id: order id :param str symbol: not used by digifinex cancelOrder() :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: An `order structure ` """ self.load_markets() market = None if symbol is not None: market = self.market(symbol) id = str(id) marketType = None marketType, params = self.handle_market_type_and_params('cancelOrder', market, params) request: dict = { 'order_id': id, } if marketType == 'swap': if symbol is None: raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument') request['instrument_id'] = market['id'] else: request['market'] = marketType marginMode, query = self.handle_margin_mode_and_params('cancelOrder', params) response = None if marginMode is not None or marketType == 'margin': marketType = 'margin' response = self.privateSpotPostMarginOrderCancel(self.extend(request, query)) elif marketType == 'spot': response = self.privateSpotPostSpotOrderCancel(self.extend(request, query)) elif marketType == 'swap': response = self.privateSwapPostTradeCancelOrder(self.extend(request, query)) else: raise NotSupported(self.id + ' cancelOrder() not support self market type') # # spot and margin # # { # "code": 0, # "success": [ # "198361cecdc65f9c8c9bb2fa68faec40", # "3fb0d98e51c18954f10d439a9cf57de0" # ], # "error": [ # "78a7104e3c65cc0c5a212a53e76d0205" # ] # } # # swap # # { # "code": 0, # "data": "1590923061186531328" # } # if (marketType == 'spot') or (marketType == 'margin'): canceledOrders = self.safe_value(response, 'success', []) numCanceledOrders = len(canceledOrders) if numCanceledOrders != 1: raise OrderNotFound(self.id + ' cancelOrder() ' + id + ' not found') orders = self.parse_cancel_orders(response) return self.safe_dict(orders, 0) else: return self.safe_order({ 'info': response, 'orderId': self.safe_string(response, 'data'), }) def parse_cancel_orders(self, response): success = self.safe_list(response, 'success') error = self.safe_list(response, 'error') result = [] for i in range(0, len(success)): order = success[i] result.append(self.safe_order({ 'info': order, 'id': order, 'status': 'canceled', })) for i in range(0, len(error)): order = error[i] result.append(self.safe_order({ 'info': order, 'id': self.safe_string_2(order, 'order-id', 'order_id'), 'status': 'failed', 'clientOrderId': self.safe_string(order, 'client-order-id'), })) return result def cancel_orders(self, ids: List[str], symbol: Str = None, params={}): """ cancel multiple orders :param str[] ids: order ids :param str symbol: not used by digifinex cancelOrders() :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an list of `order structures ` """ self.load_markets() defaultType = self.safe_string(self.options, 'defaultType', 'spot') orderType = self.safe_string(params, 'type', defaultType) params = self.omit(params, 'type') request: dict = { 'market': orderType, 'order_id': ','.join(ids), } response = self.privateSpotPostSpotOrderCancel(self.extend(request, params)) # # { # "code": 0, # "success": [ # "198361cecdc65f9c8c9bb2fa68faec40", # "3fb0d98e51c18954f10d439a9cf57de0" # ], # "error": [ # "78a7104e3c65cc0c5a212a53e76d0205" # ] # } # return self.parse_cancel_orders(response) def parse_order_status(self, status: Str): statuses: dict = { '0': 'open', '1': 'open', # partially filled '2': 'closed', '3': 'canceled', '4': 'canceled', # partially filled and canceled } return self.safe_string(statuses, status, status) def parse_order(self, order: dict, market: Market = None) -> Order: # # spot: createOrder # # { # "code": 0, # "order_id": "198361cecdc65f9c8c9bb2fa68faec40" # } # # swap: createOrder # # { # "code": 0, # "data": "1590873693003714560" # } # # spot and swap: createOrders # # { # "order_id": "d64d92a5e0a120f792f385485bc3d95b", # "instrument_id": "BTC_USDT", # "amount": 0.0001, # "price": 27000 # } # # spot: fetchOrder, fetchOpenOrders, fetchOrders # # { # "symbol": "BTC_USDT", # "order_id": "dd3164b333a4afa9d5730bb87f6db8b3", # "created_date": 1562303547, # "finished_date": 0, # "price": 0.1, # "amount": 1, # "cash_amount": 1, # "executed_amount": 0, # "avg_price": 0, # "status": 1, # "type": "buy", # "kind": "margin" # } # # swap: fetchOrder, fetchOpenOrders, fetchOrders # # { # "order_id": "1590898207657824256", # "instrument_id": "BTCUSDTPERP", # "margin_mode": "crossed", # "contract_val": "0.001", # "type": 1, # "order_type": 0, # "price": "14000", # "size": "6", # "filled_qty": "0", # "price_avg": "0", # "fee": "0", # "state": 0, # "leverage": "20", # "turnover": "0", # "has_stop": 0, # "insert_time": 1668134664828, # "time_stamp": 1668134664828 # } # timestamp = None lastTradeTimestamp = None timeInForce = None type = None side = self.safe_string(order, 'type') marketId = self.safe_string_2(order, 'symbol', 'instrument_id') symbol = self.safe_symbol(marketId, market) market = self.market(symbol) if market['type'] == 'swap': orderType = self.safe_integer(order, 'order_type') if orderType is not None: if (orderType == 9) or (orderType == 10) or (orderType == 11) or (orderType == 12) or (orderType == 15): timeInForce = 'FOK' elif (orderType == 1) or (orderType == 2) or (orderType == 3) or (orderType == 4) or (orderType == 13): timeInForce = 'IOC' elif (orderType == 6) or (orderType == 7) or (orderType == 8) or (orderType == 14): timeInForce = 'GTC' if (orderType == 0) or (orderType == 1) or (orderType == 4) or (orderType == 5) or (orderType == 9) or (orderType == 10): type = 'limit' else: type = 'market' if side == '1': side = 'open long' elif side == '2': side = 'open short' elif side == '3': side = 'close long' elif side == '4': side = 'close short' timestamp = self.safe_integer(order, 'insert_time') lastTradeTimestamp = self.safe_integer(order, 'time_stamp') else: timestamp = self.safe_timestamp(order, 'created_date') lastTradeTimestamp = self.safe_timestamp(order, 'finished_date') if side is not None: parts = side.split('_') numParts = len(parts) if numParts > 1: side = parts[0] type = parts[1] else: type = 'limit' return self.safe_order({ 'info': order, 'id': self.safe_string_2(order, 'order_id', 'data'), 'clientOrderId': None, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'lastTradeTimestamp': lastTradeTimestamp, 'symbol': symbol, 'type': type, 'timeInForce': timeInForce, 'postOnly': None, 'side': side, 'price': self.safe_number(order, 'price'), 'triggerPrice': None, 'amount': self.safe_number_2(order, 'amount', 'size'), 'filled': self.safe_number_2(order, 'executed_amount', 'filled_qty'), 'remaining': None, 'cost': None, 'average': self.safe_number_2(order, 'avg_price', 'price_avg'), 'status': self.parse_order_status(self.safe_string_2(order, 'status', 'state')), 'fee': { 'cost': self.safe_number(order, 'fee'), }, 'trades': None, }, market) def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]: """ fetch all unfilled currently open orders https://docs.digifinex.com/en-ww/spot/v3/rest.html#current-active-orders https://docs.digifinex.com/en-ww/swap/v2/rest.html#openorder :param str symbol: unified market symbol :param int [since]: the earliest time in ms to fetch open orders for :param int [limit]: the maximum number of open orders structures to retrieve :param dict [params]: extra parameters specific to the exchange API endpoint :returns Order[]: a list of `order structures ` """ self.load_markets() market = None if symbol is not None: market = self.market(symbol) marketType = None marketType, params = self.handle_market_type_and_params('fetchOpenOrders', market, params) marginMode, query = self.handle_margin_mode_and_params('fetchOpenOrders', params) request: dict = {} swap = (marketType == 'swap') if swap: if since is not None: request['start_timestamp'] = since if limit is not None: request['limit'] = limit else: request['market'] = marketType if market is not None: marketIdRequest = 'instrument_id' if swap else 'symbol' request[marketIdRequest] = market['id'] response = None if marginMode is not None or marketType == 'margin': marketType = 'margin' response = self.privateSpotGetMarginOrderCurrent(self.extend(request, query)) elif marketType == 'spot': response = self.privateSpotGetSpotOrderCurrent(self.extend(request, query)) elif marketType == 'swap': response = self.privateSwapGetTradeOpenOrders(self.extend(request, query)) else: raise NotSupported(self.id + ' fetchOpenOrders() not support self market type') # # spot and margin # # { # "code": 0, # "data": [ # { # "symbol": "BTC_USDT", # "order_id": "dd3164b333a4afa9d5730bb87f6db8b3", # "created_date": 1562303547, # "finished_date": 0, # "price": 0.1, # "amount": 1, # "cash_amount": 1, # "executed_amount": 0, # "avg_price": 0, # "status": 1, # "type": "buy", # "kind": "margin" # } # ] # } # # swap # # { # "code": 0, # "data": [ # { # "order_id": "1590898207657824256", # "instrument_id": "BTCUSDTPERP", # "margin_mode": "crossed", # "contract_val": "0.001", # "type": 1, # "order_type": 0, # "price": "14000", # "size": "6", # "filled_qty": "0", # "price_avg": "0", # "fee": "0", # "state": 0, # "leverage": "20", # "turnover": "0", # "has_stop": 0, # "insert_time": 1668134664828, # "time_stamp": 1668134664828 # }, # ... # ] # } # data = self.safe_list(response, 'data', []) return self.parse_orders(data, market, since, limit) def fetch_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]: """ fetches information on multiple orders made by the user https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-all-orders-including-history-orders https://docs.digifinex.com/en-ww/swap/v2/rest.html#historyorder :param str symbol: unified market symbol of the market orders were made in :param int [since]: the earliest time in ms to fetch orders for :param int [limit]: the maximum number of order structures to retrieve :param dict [params]: extra parameters specific to the exchange API endpoint :returns Order[]: a list of `order structures ` """ self.load_markets() market = None if symbol is not None: market = self.market(symbol) marketType = None marketType, params = self.handle_market_type_and_params('fetchOrders', market, params) marginMode, query = self.handle_margin_mode_and_params('fetchOrders', params) request: dict = {} if marketType == 'swap': if since is not None: request['start_timestamp'] = since else: request['market'] = marketType if since is not None: request['start_time'] = self.parse_to_int(since / 1000) # default 3 days from now, max 30 days if market is not None: marketIdRequest = 'instrument_id' if (marketType == 'swap') else 'symbol' request[marketIdRequest] = market['id'] if limit is not None: request['limit'] = limit response = None if marginMode is not None or marketType == 'margin': marketType = 'margin' response = self.privateSpotGetMarginOrderHistory(self.extend(request, query)) elif marketType == 'spot': response = self.privateSpotGetSpotOrderHistory(self.extend(request, query)) elif marketType == 'swap': response = self.privateSwapGetTradeHistoryOrders(self.extend(request, query)) else: raise NotSupported(self.id + ' fetchOrders() not support self market type') # # spot and margin # # { # "code": 0, # "data": [ # { # "symbol": "BTC_USDT", # "order_id": "dd3164b333a4afa9d5730bb87f6db8b3", # "created_date": 1562303547, # "finished_date": 0, # "price": 0.1, # "amount": 1, # "cash_amount": 1, # "executed_amount": 0, # "avg_price": 0, # "status": 1, # "type": "buy", # "kind": "margin" # } # ] # } # # swap # # { # "code": 0, # "data": [ # { # "order_id": "1590136768156405760", # "instrument_id": "BTCUSDTPERP", # "margin_mode": "crossed", # "contract_val": "0.001", # "type": 1, # "order_type": 8, # "price": "18660.2", # "size": "1", # "filled_qty": "1", # "price_avg": "18514.5", # "fee": "0.00925725", # "state": 2, # "leverage": "20", # "turnover": "18.5145", # "has_stop": 0, # "insert_time": 1667953123526, # "time_stamp": 1667953123596 # }, # ... # ] # } # data = self.safe_list(response, 'data', []) return self.parse_orders(data, market, since, limit) def fetch_order(self, id: str, symbol: Str = None, params={}): """ fetches information on an order made by the user https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-order-status https://docs.digifinex.com/en-ww/swap/v2/rest.html#orderinfo :param str id: order id :param str symbol: unified symbol of the market the order was made in :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: An `order structure ` """ self.load_markets() market = None if symbol is not None: market = self.market(symbol) marketType = None marketType, params = self.handle_market_type_and_params('fetchOrder', market, params) marginMode, query = self.handle_margin_mode_and_params('fetchOrder', params) request: dict = { 'order_id': id, } if marketType == 'swap': if market is not None: request['instrument_id'] = market['id'] else: request['market'] = marketType response = None if (marginMode is not None) or (marketType == 'margin'): marketType = 'margin' response = self.privateSpotGetMarginOrder(self.extend(request, query)) elif marketType == 'spot': response = self.privateSpotGetSpotOrder(self.extend(request, query)) elif marketType == 'swap': response = self.privateSwapGetTradeOrderInfo(self.extend(request, query)) else: raise NotSupported(self.id + ' fetchOrder() not support self market type') # # spot and margin # # { # "code": 0, # "data": [ # { # "symbol": "BTC_USDT", # "order_id": "dd3164b333a4afa9d5730bb87f6db8b3", # "created_date": 1562303547, # "finished_date": 0, # "price": 0.1, # "amount": 1, # "cash_amount": 1, # "executed_amount": 0, # "avg_price": 0, # "status": 1, # "type": "buy", # "kind": "margin" # } # ] # } # # swap # # { # "code": 0, # "data": { # "order_id": "1590923061186531328", # "instrument_id": "ETHUSDTPERP", # "margin_mode": "crossed", # "contract_val": "0.01", # "type": 1, # "order_type": 0, # "price": "900", # "size": "6", # "filled_qty": "0", # "price_avg": "0", # "fee": "0", # "state": 0, # "leverage": "20", # "turnover": "0", # "has_stop": 0, # "insert_time": 1668140590372, # "time_stamp": 1668140590372 # } # } # data = self.safe_value(response, 'data') order = data if (marketType == 'swap') else self.safe_value(data, 0) if order is None: raise OrderNotFound(self.id + ' fetchOrder() order ' + str(id) + ' not found') return self.parse_order(order, market) def fetch_my_trades(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}): """ fetch all trades made by the user https://docs.digifinex.com/en-ww/spot/v3/rest.html#customer-39-s-trades https://docs.digifinex.com/en-ww/swap/v2/rest.html#historytrade :param str symbol: unified market symbol :param int [since]: the earliest time in ms to fetch trades for :param int [limit]: the maximum number of trades structures to retrieve :param dict [params]: extra parameters specific to the exchange API endpoint :returns Trade[]: a list of `trade structures ` """ self.load_markets() market = None request: dict = {} if symbol is not None: market = self.market(symbol) marketType = None marketType, params = self.handle_market_type_and_params('fetchMyTrades', market, params) marginMode, query = self.handle_margin_mode_and_params('fetchMyTrades', params) if marketType == 'swap': if since is not None: request['start_timestamp'] = since else: request['market'] = marketType if since is not None: request['start_time'] = self.parse_to_int(since / 1000) # default 3 days from now, max 30 days marketIdRequest = 'instrument_id' if (marketType == 'swap') else 'symbol' if symbol is not None: request[marketIdRequest] = market['id'] if limit is not None: request['limit'] = limit response = None if marginMode is not None or marketType == 'margin': marketType = 'margin' response = self.privateSpotGetMarginMytrades(self.extend(request, query)) elif marketType == 'spot': response = self.privateSpotGetSpotMytrades(self.extend(request, query)) elif marketType == 'swap': response = self.privateSwapGetTradeHistoryTrades(self.extend(request, query)) else: raise NotSupported(self.id + ' fetchMyTrades() not support self market type') # # spot and margin # # { # "list":[ # { # "timestamp":1639506068, # "is_maker":false, # "id":"8975951332", # "amount":31.83, # "side":"sell_market", # "symbol":"DOGE_USDT", # "fee_currency":"USDT", # "fee":0.01163774826 # ,"order_id":"32b169792f4a7a19e5907dc29fc123d4", # "price":0.182811 # } # ], # "code": 0 # } # # swap # # { # "code": 0, # "data": [ # { # "trade_id": "1590136768424841218", # "instrument_id": "BTCUSDTPERP", # "order_id": "1590136768156405760", # "type": 1, # "order_type": 8, # "price": "18514.5", # "size": "1", # "fee": "0.00925725", # "close_profit": "0", # "leverage": "20", # "trade_type": 0, # "match_role": 1, # "trade_time": 1667953123562 # }, # ... # ] # } # responseRequest = 'data' if (marketType == 'swap') else 'list' data = self.safe_list(response, responseRequest, []) return self.parse_trades(data, market, since, limit) def parse_ledger_entry_type(self, type): types: dict = {} return self.safe_string(types, type, type) def parse_ledger_entry(self, item: dict, currency: Currency = None) -> LedgerEntry: # # spot and margin # # { # "currency_mark": "BTC", # "type": 100234, # "num": -10, # "balance": 0.1, # "time": 1546272000 # } # # swap # # { # "currency": "USDT", # "finance_type": 17, # "change": "-3.01", # "timestamp": 1650809432000 # } # type = self.parse_ledger_entry_type(self.safe_string_2(item, 'type', 'finance_type')) currencyId = self.safe_string_2(item, 'currency_mark', 'currency') code = self.safe_currency_code(currencyId, currency) currency = self.safe_currency(currencyId, currency) amount = self.safe_number_2(item, 'num', 'change') after = self.safe_number(item, 'balance') timestamp = self.safe_timestamp(item, 'time') if timestamp is None: timestamp = self.safe_integer(item, 'timestamp') return self.safe_ledger_entry({ 'info': item, 'id': None, 'direction': None, 'account': None, 'referenceId': None, 'referenceAccount': None, 'type': type, 'currency': code, 'amount': amount, 'before': None, 'after': after, 'status': None, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'fee': None, }, currency) def fetch_ledger(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[LedgerEntry]: """ fetch the history of changes, actions done by the user or operations that altered the balance of the user https://docs.digifinex.com/en-ww/spot/v3/rest.html#spot-margin-otc-financial-logs https://docs.digifinex.com/en-ww/swap/v2/rest.html#bills :param str [code]: unified currency code, default is None :param int [since]: timestamp in ms of the earliest ledger entry, default is None :param int [limit]: max number of ledger entries to return, default is None :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `ledger structure ` """ self.load_markets() request: dict = {} marketType = None marketType, params = self.handle_market_type_and_params('fetchLedger', None, params) marginMode, query = self.handle_margin_mode_and_params('fetchLedger', params) if marketType == 'swap': if since is not None: request['start_timestamp'] = since else: request['market'] = marketType if since is not None: request['start_time'] = self.parse_to_int(since / 1000) # default 3 days from now, max 30 days currencyIdRequest = 'currency' if (marketType == 'swap') else 'currency_mark' currency = None if code is not None: currency = self.currency(code) request[currencyIdRequest] = currency['id'] if limit is not None: request['limit'] = limit response = None if marginMode is not None or marketType == 'margin': marketType = 'margin' response = self.privateSpotGetMarginFinancelog(self.extend(request, query)) elif marketType == 'spot': response = self.privateSpotGetSpotFinancelog(self.extend(request, query)) elif marketType == 'swap': response = self.privateSwapGetAccountFinanceRecord(self.extend(request, query)) else: raise NotSupported(self.id + ' fetchLedger() not support self market type') # # spot and margin # # { # "code": 0, # "data": { # "total": 521, # "finance": [ # { # "currency_mark": "BTC", # "type": 100234, # "num": 28457, # "balance": 0.1, # "time": 1546272000 # } # ] # } # } # # swap # # { # "code": 0, # "data": [ # { # "currency": "USDT", # "finance_type": 17, # "change": "3.01", # "timestamp": 1650809432000 # }, # ] # } # ledger = None if marketType == 'swap': ledger = self.safe_value(response, 'data', []) else: data = self.safe_value(response, 'data', {}) ledger = self.safe_value(data, 'finance', []) return self.parse_ledger(ledger, currency, since, limit) def parse_deposit_address(self, depositAddress, currency: Currency = None) -> DepositAddress: # # { # "addressTag":"", # "address":"0xf1104d9f8624f89775a3e9d480fc0e75a8ef4373", # "currency":"USDT", # "chain":"ERC20" # } # address = self.safe_string(depositAddress, 'address') tag = self.safe_string(depositAddress, 'addressTag') currencyId = self.safe_string_upper(depositAddress, 'currency') code = self.safe_currency_code(currencyId) return { 'info': depositAddress, 'currency': code, 'network': None, 'address': address, 'tag': tag, } def fetch_deposit_address(self, code: str, params={}) -> DepositAddress: """ fetch the deposit address for a currency associated with self account :param str code: unified currency code :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an `address structure ` """ self.load_markets() currency = self.currency(code) request: dict = { 'currency': currency['id'], } response = self.privateSpotGetDepositAddress(self.extend(request, params)) # # { # "data":[ # { # "addressTag":"", # "address":"0xf1104d9f8624f89775a3e9d480fc0e75a8ef4373", # "currency":"USDT", # "chain":"ERC20" # } # ], # "code":200 # } # data = self.safe_value(response, 'data', []) addresses = self.parse_deposit_addresses(data, [currency['code']]) address = self.safe_value(addresses, code) if address is None: raise InvalidAddress(self.id + ' fetchDepositAddress() did not return an address for ' + code + ' - create the deposit address in the user settings on the exchange website first.') return address def fetch_transactions_by_type(self, type, code: Str = None, since: Int = None, limit: Int = None, params={}): self.load_markets() currency = None request: dict = { # 'currency': currency['id'], # 'from': 'fromId', # When direct is' prev ', from is 1, returning from old to new ascending, when direct is' next ', from is the ID of the most recent record, returned from the old descending order # 'size': 100, # default 100, max 500 # 'direct': 'prev', # "prev" ascending, "next" descending } if code is not None: currency = self.currency(code) request['currency'] = currency['id'] if limit is not None: request['size'] = min(500, limit) response = None if type == 'deposit': response = self.privateSpotGetDepositHistory(self.extend(request, params)) else: response = self.privateSpotGetWithdrawHistory(self.extend(request, params)) # # { # "code": 200, # "data": [ # { # "id": 1171, # "currency": "xrp", # "hash": "ed03094b84eafbe4bc16e7ef766ee959885ee5bcb265872baaa9c64e1cf86c2b", # "chain": "", # "amount": 7.457467, # "address": "rae93V8d2mdoUQHwBDBdM4NHCMehRJAsbm", # "memo": "100040", # "fee": 0, # "state": "safe", # "created_date": "2020-04-20 11:23:00", # "finished_date": "2020-04-20 13:23:00" # }, # ] # } # data = self.safe_list(response, 'data', []) return self.parse_transactions(data, currency, since, limit, {'type': type}) def fetch_deposits(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]: """ fetch all deposits made to an account :param str code: unified currency code :param int [since]: the earliest time in ms to fetch deposits for :param int [limit]: the maximum number of deposits structures to retrieve :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: a list of `transaction structures ` """ return self.fetch_transactions_by_type('deposit', code, since, limit, params) def fetch_withdrawals(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Transaction]: """ fetch all withdrawals made from an account :param str code: unified currency code :param int [since]: the earliest time in ms to fetch withdrawals for :param int [limit]: the maximum number of withdrawals structures to retrieve :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: a list of `transaction structures ` """ return self.fetch_transactions_by_type('withdrawal', code, since, limit, params) def parse_transaction_status(self, status: Str): # deposit state includes: 1(in deposit), 2(to be confirmed), 3(successfully deposited), 4(stopped) # withdrawal state includes: 1(application in progress), 2(to be confirmed), 3(completed), 4(rejected) statuses: dict = { '1': 'pending', # in Progress '2': 'pending', # to be confirmed '3': 'ok', # Completed '4': 'failed', # Rejected } return self.safe_string(statuses, status, status) def parse_transaction(self, transaction: dict, currency: Currency = None) -> Transaction: # # withdraw # # { # "code": 200, # "withdraw_id": 700 # } # # fetchDeposits, fetchWithdrawals # # { # "id": 1171, # "currency": "xrp", # "hash": "ed03094b84eafbe4bc16e7ef766ee959885ee5bcb265872baaa9c64e1cf86c2b", # "chain": "", # "amount": 7.457467, # "address": "rae93V8d2mdoUQHwBDBdM4NHCMehRJAsbm", # "memo": "100040", # "fee": 0, # "state": "safe", # "created_date": "2020-04-20 11:23:00", # "finished_date": "2020-04-20 13:23:00" # } # id = self.safe_string_2(transaction, 'id', 'withdraw_id') address = self.safe_string(transaction, 'address') tag = self.safe_string(transaction, 'memo') txid = self.safe_string(transaction, 'hash') currencyId = self.safe_string_upper(transaction, 'currency') code = self.safe_currency_code(currencyId, currency) timestamp = self.parse8601(self.safe_string(transaction, 'created_date')) updated = self.parse8601(self.safe_string(transaction, 'finished_date')) status = self.parse_transaction_status(self.safe_string(transaction, 'state')) amount = self.safe_number(transaction, 'amount') feeCost = self.safe_number(transaction, 'fee') fee = None if feeCost is not None: fee = {'currency': code, 'cost': feeCost} network = self.safe_string(transaction, 'chain') return { 'info': transaction, 'id': id, 'txid': txid, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'network': network, 'address': address, 'addressTo': address, 'addressFrom': None, 'tag': tag, 'tagTo': tag, 'tagFrom': None, 'type': None, 'amount': amount, 'currency': code, 'status': status, 'updated': updated, 'internal': None, 'comment': None, 'fee': fee, } def parse_transfer_status(self, status: Str) -> Str: statuses: dict = { '0': 'ok', } return self.safe_string(statuses, status, status) def parse_transfer(self, transfer: dict, currency: Currency = None) -> TransferEntry: # # transfer between spot, margin and OTC # # { # "code": 0 # } # # transfer between spot and swap # # { # "code": 0, # "data": { # "type": 2, # "currency": "USDT", # "transfer_amount": "5" # } # } # # fetchTransfers # # { # "transfer_id": 130524, # "type": 1, # "currency": "USDT", # "amount": "24", # "timestamp": 1666505659000 # } # fromAccount = None toAccount = None data = self.safe_dict(transfer, 'data', transfer) type = self.safe_integer(data, 'type') if type == 1: fromAccount = 'spot' toAccount = 'swap' elif type == 2: fromAccount = 'swap' toAccount = 'spot' timestamp = self.safe_integer(transfer, 'timestamp') return { 'info': transfer, 'id': self.safe_string(transfer, 'transfer_id'), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'currency': self.safe_currency_code(self.safe_string(data, 'currency'), currency), 'amount': self.safe_number_2(data, 'amount', 'transfer_amount'), 'fromAccount': fromAccount, 'toAccount': toAccount, 'status': self.parse_transfer_status(self.safe_string(transfer, 'code')), } def transfer(self, code: str, amount: float, fromAccount: str, toAccount: str, params={}) -> TransferEntry: """ transfer currency internally between wallets on the same account https://docs.digifinex.com/en-ww/spot/v3/rest.html#transfer-assets-among-accounts https://docs.digifinex.com/en-ww/swap/v2/rest.html#accounttransfer :param str code: unified currency code :param float amount: amount to transfer :param str fromAccount: 'spot', 'swap', 'margin', 'OTC' - account to transfer from :param str toAccount: 'spot', 'swap', 'margin', 'OTC' - account to transfer to :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `transfer structure ` """ self.load_markets() currency = self.currency(code) currencyId = currency['id'] accountsByType = self.safe_value(self.options, 'accountsByType', {}) fromId = self.safe_string(accountsByType, fromAccount, fromAccount) toId = self.safe_string(accountsByType, toAccount, toAccount) request = {} fromSwap = (fromAccount == 'swap') toSwap = (toAccount == 'swap') response = None amountString = self.currency_to_precision(code, amount) if fromSwap or toSwap: if (fromId != '1') and (toId != '1'): raise ExchangeError(self.id + ' transfer() supports transferring between spot and swap, spot and margin, spot and OTC only') request['type'] = 1 if toSwap else 2 # 1 = spot to swap, 2 = swap to spot request['currency'] = currencyId request['transfer_amount'] = amountString # # { # "code": 0, # "data": { # "type": 2, # "currency": "USDT", # "transfer_amount": "5" # } # } # response = self.privateSwapPostAccountTransfer(self.extend(request, params)) else: request['currency_mark'] = currencyId request['num'] = amountString request['from'] = fromId # 1 = SPOT, 2 = MARGIN, 3 = OTC request['to'] = toId # 1 = SPOT, 2 = MARGIN, 3 = OTC # # { # "code": 0 # } # response = self.privateSpotPostTransfer(self.extend(request, params)) return self.parse_transfer(response, currency) def withdraw(self, code: str, amount: float, address: str, tag: Str = None, params={}) -> Transaction: """ make a withdrawal :param str code: unified currency code :param float amount: the amount to withdraw :param str address: the address to withdraw to :param str tag: :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `transaction structure ` """ tag, params = self.handle_withdraw_tag_and_params(tag, params) self.check_address(address) self.load_markets() currency = self.currency(code) request: dict = { # 'chain': 'ERC20', 'OMNI', 'TRC20', # required for USDT 'address': address, 'amount': self.currency_to_precision(code, amount), 'currency': currency['id'], } if tag is not None: request['memo'] = tag response = self.privateSpotPostWithdrawNew(self.extend(request, params)) # # { # "code": 200, # "withdraw_id": 700 # } # return self.parse_transaction(response, currency) def fetch_borrow_interest(self, code: Str = None, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[BorrowInterest]: self.load_markets() request: dict = {} market = None if symbol is not None: market = self.market(symbol) request['symbol'] = market['id'] response = self.privateSpotGetMarginPositions(self.extend(request, params)) # # { # "margin": "45.71246418952618", # "code": 0, # "margin_rate": "7.141978570340037", # "positions": [ # { # "amount": 0.0006103, # "side": "go_long", # "entry_price": 31428.72, # "liquidation_rate": 0.3, # "liquidation_price": 10225.335481159, # "unrealized_roe": -0.0076885829266987, # "symbol": "BTC_USDT", # "unrealized_pnl": -0.049158102631999, # "leverage_ratio": 3 # } # ], # "unrealized_pnl": "-0.049158102631998504" # } # rows = self.safe_value(response, 'positions') interest = self.parse_borrow_interests(rows, market) return self.filter_by_currency_since_limit(interest, code, since, limit) def parse_borrow_interest(self, info: dict, market: Market = None) -> BorrowInterest: # # { # "amount": 0.0006103, # "side": "go_long", # "entry_price": 31428.72, # "liquidation_rate": 0.3, # "liquidation_price": 10225.335481159, # "unrealized_roe": -0.0076885829266987, # "symbol": "BTC_USDT", # "unrealized_pnl": -0.049158102631999, # "leverage_ratio": 3 # } # marketId = self.safe_string(info, 'symbol') amountString = self.safe_string(info, 'amount') leverageString = self.safe_string(info, 'leverage_ratio') amountInvested = Precise.string_div(amountString, leverageString) amountBorrowed = Precise.string_sub(amountString, amountInvested) currency = None if (market is None) else market['base'] symbol = self.safe_symbol(marketId, market) return { 'info': info, 'symbol': symbol, 'currency': currency, 'interest': None, 'interestRate': 0.001, # all interest rates on digifinex are 0.1% 'amountBorrowed': self.parse_number(amountBorrowed), 'marginMode': None, 'timestamp': None, 'datetime': None, } def fetch_cross_borrow_rate(self, code: str, params={}) -> CrossBorrowRate: """ fetch the rate of interest to borrow a currency for margin trading https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-assets :param str code: unified currency code :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `borrow rate structure ` """ self.load_markets() request: dict = {} response = self.privateSpotGetMarginAssets(self.extend(request, params)) # # { # "list": [ # { # "valuation_rate": 1, # "total": 1.92012186174, # "free": 1.92012186174, # "currency": "USDT" # }, # ], # "total": 45.133305540922, # "code": 0, # "unrealized_pnl": 0, # "free": 45.133305540922, # "equity": 45.133305540922 # } # data = self.safe_value(response, 'list', []) result = [] for i in range(0, len(data)): entry = data[i] if self.safe_string(entry, 'currency') == code: result = entry currency = self.currency(code) return self.parse_borrow_rate(result, currency) def fetch_cross_borrow_rates(self, params={}) -> CrossBorrowRates: """ fetch the borrow interest rates of all currencies https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-assets :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a list of `borrow rate structures ` """ self.load_markets() response = self.privateSpotGetMarginAssets(params) # # { # "list": [ # { # "valuation_rate": 1, # "total": 1.92012186174, # "free": 1.92012186174, # "currency": "USDT" # }, # ], # "total": 45.133305540922, # "code": 0, # "unrealized_pnl": 0, # "free": 45.133305540922, # "equity": 45.133305540922 # } # result = self.safe_value(response, 'list', []) return self.parse_borrow_rates(result, 'currency') def parse_borrow_rate(self, info, currency: Currency = None): # # { # "valuation_rate": 1, # "total": 1.92012186174, # "free": 1.92012186174, # "currency": "USDT" # } # timestamp = self.milliseconds() currencyId = self.safe_string(info, 'currency') return { 'currency': self.safe_currency_code(currencyId, currency), 'rate': 0.001, # all interest rates on digifinex are 0.1% 'period': 86400000, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'info': info, } def parse_borrow_rates(self, info, codeKey): # # { # "valuation_rate": 1, # "total": 1.92012186174, # "free": 1.92012186174, # "currency": "USDT" # }, # result: dict = {} for i in range(0, len(info)): item = info[i] currency = self.safe_string(item, codeKey) code = self.safe_currency_code(currency) borrowRate = self.parse_borrow_rate(item) result[code] = borrowRate return result def fetch_funding_rate(self, symbol: str, params={}) -> FundingRate: """ fetch the current funding rate https://docs.digifinex.com/en-ww/swap/v2/rest.html#currentfundingrate :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `funding rate structure ` """ self.load_markets() market = self.market(symbol) if not market['swap']: raise BadSymbol(self.id + ' fetchFundingRate() supports swap contracts only') request: dict = { 'instrument_id': market['id'], } response = self.publicSwapGetPublicFundingRate(self.extend(request, params)) # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "funding_rate": "-0.00012", # "funding_time": 1662710400000, # "next_funding_rate": "0.0001049907085171607", # "next_funding_time": 1662739200000 # } # } # data = self.safe_dict(response, 'data', {}) return self.parse_funding_rate(data, market) def fetch_funding_interval(self, symbol: str, params={}) -> FundingRate: """ fetch the current funding rate interval https://docs.digifinex.com/en-ww/swap/v2/rest.html#currentfundingrate :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `funding rate structure ` """ return self.fetch_funding_rate(symbol, params) def parse_funding_rate(self, contract, market: Market = None) -> FundingRate: # # { # "instrument_id": "BTCUSDTPERP", # "funding_rate": "-0.00012", # "funding_time": 1662710400000, # "next_funding_rate": "0.0001049907085171607", # "next_funding_time": 1662739200000 # } # marketId = self.safe_string(contract, 'instrument_id') timestamp = self.safe_integer(contract, 'funding_time') nextTimestamp = self.safe_integer(contract, 'next_funding_time') fundingTimeString = self.safe_string(contract, 'funding_time') nextFundingTimeString = self.safe_string(contract, 'next_funding_time') millisecondsInterval = Precise.string_sub(nextFundingTimeString, fundingTimeString) return { 'info': contract, 'symbol': self.safe_symbol(marketId, market), 'markPrice': None, 'indexPrice': None, 'interestRate': None, 'estimatedSettlePrice': None, 'timestamp': None, 'datetime': None, 'fundingRate': self.safe_number(contract, 'funding_rate'), 'fundingTimestamp': timestamp, 'fundingDatetime': self.iso8601(timestamp), 'nextFundingRate': self.safe_number(contract, 'next_funding_rate'), 'nextFundingTimestamp': nextTimestamp, 'nextFundingDatetime': self.iso8601(nextTimestamp), 'previousFundingRate': None, 'previousFundingTimestamp': None, 'previousFundingDatetime': None, 'interval': self.parse_funding_interval(millisecondsInterval), } def parse_funding_interval(self, interval): intervals: dict = { '3600000': '1h', '14400000': '4h', '28800000': '8h', '57600000': '16h', '86400000': '24h', } return self.safe_string(intervals, interval, interval) def fetch_funding_rate_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}): """ fetches historical funding rate prices :param str symbol: unified symbol of the market to fetch the funding rate history for :param int [since]: timestamp in ms of the earliest funding rate to fetch :param int [limit]: the maximum amount of `funding rate structures ` to fetch :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: a list of `funding rate structures ` """ if symbol is None: raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument') self.load_markets() market = self.market(symbol) if not market['swap']: raise BadSymbol(self.id + ' fetchFundingRateHistory() supports swap contracts only') request: dict = { 'instrument_id': market['id'], } if since is not None: request['start_timestamp'] = since if limit is not None: request['limit'] = limit response = self.publicSwapGetPublicFundingRateHistory(self.extend(request, params)) # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "funding_rates": [ # { # "rate": "-0.00375", # "time": 1607673600000 # }, # ... # ] # } # } # data = self.safe_value(response, 'data', {}) result = self.safe_value(data, 'funding_rates', []) rates = [] for i in range(0, len(result)): entry = result[i] marketId = self.safe_string(data, 'instrument_id') symbolInner = self.safe_symbol(marketId) timestamp = self.safe_integer(entry, 'time') rates.append({ 'info': entry, 'symbol': symbolInner, 'fundingRate': self.safe_number(entry, 'rate'), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), }) sorted = self.sort_by(rates, 'timestamp') return self.filter_by_symbol_since_limit(sorted, symbol, since, limit) def fetch_trading_fee(self, symbol: str, params={}) -> TradingFeeInterface: """ fetch the trading fees for a market https://docs.digifinex.com/en-ww/swap/v2/rest.html#tradingfee :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `fee structure ` """ self.load_markets() market = self.market(symbol) if not market['swap']: raise BadRequest(self.id + ' fetchTradingFee() supports swap markets only') request: dict = { 'instrument_id': market['id'], } response = self.privateSwapGetAccountTradingFeeRate(self.extend(request, params)) # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "taker_fee_rate": "0.0005", # "maker_fee_rate": "0.0003" # } # } # data = self.safe_value(response, 'data', {}) return self.parse_trading_fee(data, market) def parse_trading_fee(self, fee: dict, market: Market = None) -> TradingFeeInterface: # # { # "instrument_id": "BTCUSDTPERP", # "taker_fee_rate": "0.0005", # "maker_fee_rate": "0.0003" # } # marketId = self.safe_string(fee, 'instrument_id') symbol = self.safe_symbol(marketId, market) return { 'info': fee, 'symbol': symbol, 'maker': self.safe_number(fee, 'maker_fee_rate'), 'taker': self.safe_number(fee, 'taker_fee_rate'), 'percentage': None, 'tierBased': None, } def fetch_positions(self, symbols: Strings = None, params={}) -> List[Position]: """ fetch all open positions https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-positions https://docs.digifinex.com/en-ww/swap/v2/rest.html#positions :param str[]|None symbols: list of unified market symbols :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: a list of `position structures ` """ self.load_markets() symbols = self.market_symbols(symbols) request: dict = {} market = None marketType = None if symbols is not None: symbol = None if isinstance(symbols, list): symbolsLength = len(symbols) if symbolsLength > 1: raise BadRequest(self.id + ' fetchPositions() symbols argument cannot contain more than 1 symbol') symbol = symbols[0] else: symbol = symbols market = self.market(symbol) marketType, params = self.handle_market_type_and_params('fetchPositions', market, params) marginMode, query = self.handle_margin_mode_and_params('fetchPositions', params) if marginMode is not None: marketType = 'margin' if market is not None: marketIdRequest = 'instrument_id' if (marketType == 'swap') else 'symbol' request[marketIdRequest] = market['id'] response = None if marketType == 'spot' or marketType == 'margin': response = self.privateSpotGetMarginPositions(self.extend(request, query)) elif marketType == 'swap': response = self.privateSwapGetAccountPositions(self.extend(request, query)) else: raise NotSupported(self.id + ' fetchPositions() not support self market type') # # swap # # { # "code": 0, # "data": [ # { # "instrument_id": "BTCUSDTPERP", # "margin_mode": "crossed", # "avail_position": "1", # "avg_cost": "18369.3", # "last": "18404.7", # "leverage": "20", # "liquidation_price": "451.12820512820264", # "maint_margin_ratio": "0.005", # "margin": "0.918465", # "position": "1", # "realized_pnl": "0", # "unrealized_pnl": "0.03410000000000224", # "unrealized_pnl_rate": "0.03712716325608732", # "side": "long", # "open_outstanding": "0", # "risk_score": "0.495049504950495", # "margin_ratio": "0.4029464788983229", # "timestamp": 1667960497145 # }, # ... # ] # } # # margin # # { # "margin": "77.71534772983289", # "code": 0, # "margin_rate": "10.284503769497306", # "positions": [ # { # "amount": 0.0010605, # "side": "go_long", # "entry_price": 18321.39, # "liquidation_rate": 0.3, # "liquidation_price": -52754.371758471, # "unrealized_roe": -0.002784390267332, # "symbol": "BTC_USDT", # "unrealized_pnl": -0.010820048189999, # "leverage_ratio": 5 # }, # ... # ], # "unrealized_pnl": "-0.10681600018999979" # } # positionRequest = 'data' if (marketType == 'swap') else 'positions' positions = self.safe_value(response, positionRequest, []) result = [] for i in range(0, len(positions)): result.append(self.parse_position(positions[i], market)) return self.filter_by_array_positions(result, 'symbol', symbols, False) def fetch_position(self, symbol: str, params={}): """ https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-positions https://docs.digifinex.com/en-ww/swap/v2/rest.html#positions fetch data on a single open contract trade position :param str symbol: unified market symbol of the market the position is held in :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `position structure ` """ self.load_markets() market = self.market(symbol) request: dict = {} marketType = None marketType, params = self.handle_market_type_and_params('fetchPosition', market, params) marginMode, query = self.handle_margin_mode_and_params('fetchPosition', params) if marginMode is not None: marketType = 'margin' marketIdRequest = 'instrument_id' if (marketType == 'swap') else 'symbol' request[marketIdRequest] = market['id'] response = None if marketType == 'spot' or marketType == 'margin': response = self.privateSpotGetMarginPositions(self.extend(request, query)) elif marketType == 'swap': response = self.privateSwapGetAccountPositions(self.extend(request, query)) else: raise NotSupported(self.id + ' fetchPosition() not support self market type') # # swap # # { # "code": 0, # "data": [ # { # "instrument_id": "BTCUSDTPERP", # "margin_mode": "crossed", # "avail_position": "1", # "avg_cost": "18369.3", # "last": "18388.9", # "leverage": "20", # "liquidation_price": "383.38712921065553", # "maint_margin_ratio": "0.005", # "margin": "0.918465", # "position": "1", # "realized_pnl": "0", # "unrealized_pnl": "0.021100000000004115", # "unrealized_pnl_rate": "0.02297311274790451", # "side": "long", # "open_outstanding": "0", # "risk_score": "0.4901960784313725", # "margin_ratio": "0.40486964045976204", # "timestamp": 1667960241758 # } # ] # } # # margin # # { # "margin": "77.71534772983289", # "code": 0, # "margin_rate": "10.284503769497306", # "positions": [ # { # "amount": 0.0010605, # "side": "go_long", # "entry_price": 18321.39, # "liquidation_rate": 0.3, # "liquidation_price": -52754.371758471, # "unrealized_roe": -0.002784390267332, # "symbol": "BTC_USDT", # "unrealized_pnl": -0.010820048189999, # "leverage_ratio": 5 # } # ], # "unrealized_pnl": "-0.10681600018999979" # } # dataRequest = 'data' if (marketType == 'swap') else 'positions' data = self.safe_value(response, dataRequest, []) position = self.parse_position(data[0], market) if marketType == 'swap': return position else: position['collateral'] = self.safe_number(response, 'margin') position['marginRatio'] = self.safe_number(response, 'margin_rate') return position def parse_position(self, position: dict, market: Market = None): # # swap # # { # "instrument_id": "BTCUSDTPERP", # "margin_mode": "crossed", # "avail_position": "1", # "avg_cost": "18369.3", # "last": "18388.9", # "leverage": "20", # "liquidation_price": "383.38712921065553", # "maint_margin_ratio": "0.005", # "margin": "0.918465", # "position": "1", # "realized_pnl": "0", # "unrealized_pnl": "0.021100000000004115", # "unrealized_pnl_rate": "0.02297311274790451", # "side": "long", # "open_outstanding": "0", # "risk_score": "0.4901960784313725", # "margin_ratio": "0.40486964045976204", # "timestamp": 1667960241758 # } # # margin # # { # "amount": 0.0010605, # "side": "go_long", # "entry_price": 18321.39, # "liquidation_rate": 0.3, # "liquidation_price": -52754.371758471, # "unrealized_roe": -0.002784390267332, # "symbol": "BTC_USDT", # "unrealized_pnl": -0.010820048189999, # "leverage_ratio": 5 # } # marketId = self.safe_string_2(position, 'instrument_id', 'symbol') market = self.safe_market(marketId, market) symbol = market['symbol'] marginMode = self.safe_string(position, 'margin_mode') if marginMode is not None: marginMode = 'cross' if (marginMode == 'crossed') else 'isolated' else: marginMode = 'crossed' timestamp = self.safe_integer(position, 'timestamp') side = self.safe_string(position, 'side') if side == 'go_long': side = 'long' elif side == 'go_short': side = 'short' return self.safe_position({ 'info': position, 'id': None, 'symbol': symbol, 'notional': self.safe_number(position, 'amount'), 'marginMode': marginMode, 'liquidationPrice': self.safe_number(position, 'liquidation_price'), 'entryPrice': self.safe_number_2(position, 'avg_cost', 'entry_price'), 'unrealizedPnl': self.safe_number(position, 'unrealized_pnl'), 'contracts': self.safe_number(position, 'avail_position'), 'contractSize': self.safe_number(market, 'contractSize'), 'markPrice': self.safe_number(position, 'last'), 'side': side, 'hedged': None, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'maintenanceMargin': self.safe_number(position, 'margin'), 'maintenanceMarginPercentage': self.safe_number(position, 'maint_margin_ratio'), 'collateral': None, 'initialMargin': None, 'initialMarginPercentage': None, 'leverage': self.safe_number_2(position, 'leverage', 'leverage_ratio'), 'marginRatio': self.safe_number(position, 'margin_ratio'), 'percentage': None, 'stopLossPrice': None, 'takeProfitPrice': None, }) def set_leverage(self, leverage: int, symbol: Str = None, params={}): """ set the level of leverage for a market https://docs.digifinex.com/en-ww/swap/v2/rest.html#setleverage :param float leverage: the rate of leverage :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :param str [params.marginMode]: either 'cross' or 'isolated', default is cross :param str [params.side]: either 'long' or 'short', required for isolated markets only :returns dict: response from the exchange """ if symbol is None: raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument') self.load_markets() market = self.market(symbol) if market['type'] != 'swap': raise BadSymbol(self.id + ' setLeverage() supports swap contracts only') if (leverage < 1) or (leverage > 100): raise BadRequest(self.id + ' leverage should be between 1 and 100') request: dict = { 'instrument_id': market['id'], 'leverage': leverage, } defaultMarginMode = self.safe_string_2(self.options, 'marginMode', 'defaultMarginMode') marginMode = self.safe_string_lower_2(params, 'marginMode', 'defaultMarginMode', defaultMarginMode) if marginMode is not None: marginMode = 'crossed' if (marginMode == 'cross') else 'isolated' request['margin_mode'] = marginMode params = self.omit(params, ['marginMode', 'defaultMarginMode']) if marginMode == 'isolated': side = self.safe_string(params, 'side') if side is not None: request['side'] = side params = self.omit(params, 'side') else: self.check_required_argument('setLeverage', side, 'side', ['long', 'short']) return self.privateSwapPostAccountLeverage(self.extend(request, params)) # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "leverage": 30, # "margin_mode": "crossed", # "side": "both" # } # } # def fetch_transfers(self, code: Str = None, since: Int = None, limit: Int = None, params={}) -> List[TransferEntry]: """ fetch the transfer history, only transfers between spot and swap accounts are supported https://docs.digifinex.com/en-ww/swap/v2/rest.html#transferrecord :param str code: unified currency code of the currency transferred :param int [since]: the earliest time in ms to fetch transfers for :param int [limit]: the maximum number of transfers to retrieve :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: a list of `transfer structures ` """ self.load_markets() currency = None request: dict = {} if code is not None: currency = self.safe_currency_code(code) request['currency'] = currency['id'] if since is not None: request['start_timestamp'] = since if limit is not None: request['limit'] = limit # default 20 max 100 response = self.privateSwapGetAccountTransferRecord(self.extend(request, params)) # # { # "code": 0, # "data": [ # { # "transfer_id": 130524, # "type": 1, # "currency": "USDT", # "amount": "24", # "timestamp": 1666505659000 # }, # ... # ] # } # transfers = self.safe_list(response, 'data', []) return self.parse_transfers(transfers, currency, since, limit) def fetch_leverage_tiers(self, symbols: Strings = None, params={}) -> LeverageTiers: """ https://docs.digifinex.com/en-ww/swap/v2/rest.html#instruments retrieve information on the maximum leverage, for different trade sizes :param str[]|None symbols: a list of unified market symbols :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a dictionary of `leverage tiers structures `, indexed by market symbols """ self.load_markets() response = self.publicSwapGetPublicInstruments(params) # # { # "code": 0, # "data": [ # { # "instrument_id": "BTCUSDTPERP", # "type": "REAL", # "contract_type": "PERPETUAL", # "base_currency": "BTC", # "quote_currency": "USDT", # "clear_currency": "USDT", # "contract_value": "0.001", # "contract_value_currency": "BTC", # "is_inverse": False, # "is_trading": True, # "status": "ONLINE", # "price_precision": 1, # "tick_size": "0.1", # "min_order_amount": 1, # "open_max_limits": [ # { # "leverage": "50", # "max_limit": "1000000" # }, # ] # }, # ] # } # data = self.safe_value(response, 'data', []) symbols = self.market_symbols(symbols) return self.parse_leverage_tiers(data, symbols, 'instrument_id') def fetch_market_leverage_tiers(self, symbol: str, params={}) -> List[LeverageTier]: """ retrieve information on the maximum leverage, for different trade sizes for a single market https://docs.digifinex.com/en-ww/swap/v2/rest.html#instrument :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a `leverage tiers structure ` """ self.load_markets() market = self.market(symbol) if not market['swap']: raise BadRequest(self.id + ' fetchMarketLeverageTiers() supports swap markets only') request: dict = { 'instrument_id': market['id'], } response = self.publicSwapGetPublicInstrument(self.extend(request, params)) # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "type": "REAL", # "contract_type": "PERPETUAL", # "base_currency": "BTC", # "quote_currency": "USDT", # "clear_currency": "USDT", # "contract_value": "0.001", # "contract_value_currency": "BTC", # "is_inverse": False, # "is_trading": True, # "status": "ONLINE", # "price_precision": 1, # "tick_size": "0.1", # "min_order_amount": 1, # "open_max_limits": [ # { # "leverage": "50", # "max_limit": "1000000" # } # ] # } # } # data = self.safe_value(response, 'data', {}) return self.parse_market_leverage_tiers(data, market) def parse_market_leverage_tiers(self, info, market: Market = None) -> List[LeverageTier]: # # { # "instrument_id": "BTCUSDTPERP", # "type": "REAL", # "contract_type": "PERPETUAL", # "base_currency": "BTC", # "quote_currency": "USDT", # "clear_currency": "USDT", # "contract_value": "0.001", # "contract_value_currency": "BTC", # "is_inverse": False, # "is_trading": True, # "status": "ONLINE", # "price_precision": 1, # "tick_size": "0.1", # "min_order_amount": 1, # "open_max_limits": [ # { # "leverage": "50", # "max_limit": "1000000" # } # ] # } # tiers = [] brackets = self.safe_value(info, 'open_max_limits', {}) for i in range(0, len(brackets)): tier = brackets[i] marketId = self.safe_string(info, 'instrument_id') market = self.safe_market(marketId, market) tiers.append({ 'tier': self.sum(i, 1), 'symbol': self.safe_symbol(marketId, market, None, 'swap'), 'currency': market['settle'], 'minNotional': None, 'maxNotional': self.safe_number(tier, 'max_limit'), 'maintenanceMarginRate': None, 'maxLeverage': self.safe_number(tier, 'leverage'), 'info': tier, }) return tiers def handle_margin_mode_and_params(self, methodName, params={}, defaultValue=None): """ @ignore marginMode specified by params["marginMode"], self.options["marginMode"], self.options["defaultMarginMode"], params["margin"] = True or self.options["defaultType"] = 'margin' :param dict [params]: extra parameters specific to the exchange API endpoint :returns Array: the marginMode in lowercase """ defaultType = self.safe_string(self.options, 'defaultType') isMargin = self.safe_bool(params, 'margin', False) marginMode = None marginMode, params = super(digifinex, self).handle_margin_mode_and_params(methodName, params, defaultValue) if marginMode is not None: if marginMode != 'cross': raise NotSupported(self.id + ' only cross margin is supported') else: if (defaultType == 'margin') or (isMargin is True): marginMode = 'cross' return [marginMode, params] def fetch_deposit_withdraw_fees(self, codes: Strings = None, params={}): """ fetch deposit and withdraw fees https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-currency-deposit-and-withdrawal-information :param str[]|None codes: not used by fetchDepositWithdrawFees() :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a list of `fee structures ` """ self.load_markets() response = self.publicSpotGetCurrencies(params) # # { # "data": [ # { # "deposit_status": 0, # "min_withdraw_fee": 5, # "withdraw_fee_currency": "USDT", # "chain": "OMNI", # "withdraw_fee_rate": 0, # "min_withdraw_amount": 10, # "currency": "USDT", # "withdraw_status": 0, # "min_deposit_amount": 10 # }, # { # "deposit_status": 1, # "min_withdraw_fee": 5, # "withdraw_fee_currency": "USDT", # "chain": "ERC20", # "withdraw_fee_rate": 0, # "min_withdraw_amount": 10, # "currency": "USDT", # "withdraw_status": 1, # "min_deposit_amount": 10 # }, # ], # "code": 200, # } # data = self.safe_list(response, 'data') return self.parse_deposit_withdraw_fees(data, codes) def parse_deposit_withdraw_fees(self, response, codes=None, currencyIdKey=None): # # [ # { # "deposit_status": 0, # "min_withdraw_fee": 5, # "withdraw_fee_currency": "USDT", # "chain": "OMNI", # "withdraw_fee_rate": 0, # "min_withdraw_amount": 10, # "currency": "USDT", # "withdraw_status": 0, # "min_deposit_amount": 10 # }, # { # "deposit_status": 1, # "min_withdraw_fee": 5, # "withdraw_fee_currency": "USDT", # "chain": "ERC20", # "withdraw_fee_rate": 0, # "min_withdraw_amount": 10, # "currency": "USDT", # "withdraw_status": 1, # "min_deposit_amount": 10 # }, # ] # depositWithdrawFees: dict = {} codes = self.market_codes(codes) for i in range(0, len(response)): entry = response[i] currencyId = self.safe_string(entry, 'currency') code = self.safe_currency_code(currencyId) if (codes is None) or (self.in_array(code, codes)): depositWithdrawFee = self.safe_value(depositWithdrawFees, code) if depositWithdrawFee is None: depositWithdrawFees[code] = self.deposit_withdraw_fee({}) depositWithdrawFees[code]['info'] = [] depositWithdrawInfo = depositWithdrawFees[code]['info'] depositWithdrawInfo.append(entry) networkId = self.safe_string(entry, 'chain') withdrawFee = self.safe_value(entry, 'min_withdraw_fee') withdrawResult: dict = { 'fee': withdrawFee, 'percentage': False if (withdrawFee is not None) else None, } depositResult: dict = { 'fee': None, 'percentage': None, } if networkId is not None: networkCode = self.network_id_to_code(networkId) depositWithdrawFees[code]['networks'][networkCode] = { 'withdraw': withdrawResult, 'deposit': depositResult, } else: depositWithdrawFees[code]['withdraw'] = withdrawResult depositWithdrawFees[code]['deposit'] = depositResult depositWithdrawCodes = list(depositWithdrawFees.keys()) for i in range(0, len(depositWithdrawCodes)): code = depositWithdrawCodes[i] currency = self.currency(code) depositWithdrawFees[code] = self.assign_default_deposit_withdraw_fees(depositWithdrawFees[code], currency) return depositWithdrawFees def add_margin(self, symbol: str, amount: float, params={}) -> MarginModification: """ add margin to a position https://docs.digifinex.com/en-ww/swap/v2/rest.html#positionmargin :param str symbol: unified market symbol :param float amount: amount of margin to add :param dict [params]: extra parameters specific to the exchange API endpoint :param str params['side']: the position side: 'long' or 'short' :returns dict: a `margin structure ` """ side = self.safe_string(params, 'side') self.check_required_argument('addMargin', side, 'side', ['long', 'short']) return self.modify_margin_helper(symbol, amount, 1, params) def reduce_margin(self, symbol: str, amount: float, params={}) -> MarginModification: """ remove margin from a position https://docs.digifinex.com/en-ww/swap/v2/rest.html#positionmargin :param str symbol: unified market symbol :param float amount: the amount of margin to remove :param dict [params]: extra parameters specific to the exchange API endpoint :param str params['side']: the position side: 'long' or 'short' :returns dict: a `margin structure ` """ side = self.safe_string(params, 'side') self.check_required_argument('reduceMargin', side, 'side', ['long', 'short']) return self.modify_margin_helper(symbol, amount, 2, params) def modify_margin_helper(self, symbol: str, amount, type, params={}) -> MarginModification: self.load_markets() side = self.safe_string(params, 'side') market = self.market(symbol) request: dict = { 'instrument_id': market['id'], 'amount': self.number_to_string(amount), 'type': type, 'side': side, } response = self.privateSwapPostAccountPositionMargin(self.extend(request, params)) # # { # "code": 0, # "data": { # "instrument_id": "BTCUSDTPERP", # "side": "long", # "type": 1, # "amount": "3.6834" # } # } # code = self.safe_integer(response, 'code') status = 'ok' if (code == 0) else 'failed' data = self.safe_value(response, 'data', {}) return self.extend(self.parse_margin_modification(data, market), { 'status': status, }) def parse_margin_modification(self, data: dict, market: Market = None) -> MarginModification: # # { # "instrument_id": "BTCUSDTPERP", # "side": "long", # "type": 1, # "amount": "3.6834" # } # marketId = self.safe_string(data, 'instrument_id') rawType = self.safe_integer(data, 'type') return { 'info': data, 'symbol': self.safe_symbol(marketId, market, None, 'swap'), 'type': 'add' if (rawType == 1) else 'reduce', 'marginMode': 'isolated', 'amount': self.safe_number(data, 'amount'), 'total': None, 'code': market['settle'], 'status': None, 'timestamp': None, 'datetime': None, } def fetch_funding_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}): """ fetch the history of funding payments paid and received on self account https://docs.digifinex.com/en-ww/swap/v2/rest.html#funding-fee :param str [symbol]: unified market symbol :param int [since]: the earliest time in ms to fetch funding history for :param int [limit]: the maximum number of funding history structures to retrieve :param dict [params]: extra parameters specific to the exchange API endpoint :param int [params.until]: timestamp in ms of the latest funding payment :returns dict: a `funding history structure ` """ self.load_markets() request: dict = {} request, params = self.handle_until_option('end_timestamp', request, params) market = None if symbol is not None: market = self.market(symbol) request['instrument_id'] = market['id'] if limit is not None: request['limit'] = limit if since is not None: request['start_timestamp'] = since response = self.privateSwapGetAccountFundingFee(self.extend(request, params)) # # { # "code": 0, # "data": [ # { # "instrument_id": "BTCUSDTPERP", # "currency": "USDT", # "amount": "-0.000342814", # "timestamp": 1698768009440 # } # ] # } # data = self.safe_list(response, 'data', []) return self.parse_incomes(data, market, since, limit) def parse_income(self, income, market: Market = None): # # { # "instrument_id": "BTCUSDTPERP", # "currency": "USDT", # "amount": "-0.000342814", # "timestamp": 1698768009440 # } # marketId = self.safe_string(income, 'instrument_id') currencyId = self.safe_string(income, 'currency') timestamp = self.safe_integer(income, 'timestamp') return { 'info': income, 'symbol': self.safe_symbol(marketId, market, None, 'swap'), 'code': self.safe_currency_code(currencyId), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'id': None, 'amount': self.safe_number(income, 'amount'), } def set_margin_mode(self, marginMode: str, symbol: Str = None, params={}): """ set margin mode to 'cross' or 'isolated' https://docs.digifinex.com/en-ww/swap/v2/rest.html#positionmode :param str marginMode: 'cross' or 'isolated' :param str symbol: unified market symbol :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: response from the exchange """ if symbol is None: raise ArgumentsRequired(self.id + ' setMarginMode() requires a symbol argument') self.load_markets() market = self.market(symbol) marginMode = marginMode.lower() if marginMode == 'cross': marginMode = 'crossed' request: dict = { 'instrument_id': market['id'], 'margin_mode': marginMode, } return self.privateSwapPostAccountPositionMode(self.extend(request, params)) def sign(self, path, api=[], method='GET', params={}, headers=None, body=None): signed = api[0] == 'private' endpoint = api[1] pathPart = '/v3' if (endpoint == 'spot') else '/swap/v2' request = '/' + self.implode_params(path, params) payload = pathPart + request url = self.urls['api']['rest'] + payload query = self.omit(params, self.extract_params(path)) urlencoded = None if signed and (pathPart == '/swap/v2') and (method == 'POST'): urlencoded = json.dumps(params) else: urlencoded = self.urlencode(self.keysort(query)) if signed: auth = None nonce = None if pathPart == '/swap/v2': nonce = str(self.milliseconds()) auth = nonce + method + payload if method == 'GET': if urlencoded: auth += '?' + urlencoded elif method == 'POST': auth += urlencoded else: nonce = str(self.nonce()) auth = urlencoded signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256) if method == 'GET': if urlencoded: url += '?' + urlencoded elif method == 'POST': headers = { 'Content-Type': 'application/x-www-form-urlencoded', } if urlencoded: body = urlencoded headers = { 'ACCESS-KEY': self.apiKey, 'ACCESS-SIGN': signature, 'ACCESS-TIMESTAMP': nonce, } else: if urlencoded: url += '?' + urlencoded return {'url': url, 'method': method, 'body': body, 'headers': headers} def handle_errors(self, statusCode: int, statusText: str, url: str, method: str, responseHeaders: dict, responseBody, response, requestHeaders, requestBody): if not response: return None # fall back to default error handler code = self.safe_string(response, 'code') if (code == '0') or (code == '200'): return None # no error feedback = self.id + ' ' + responseBody if code is None: raise BadResponse(feedback) unknownError = [ExchangeError, feedback] ExceptionClass, message = self.safe_value(self.exceptions['exact'], code, unknownError) raise ExceptionClass(message)