UNPKG

ccxt

Version:

A cryptocurrency trading API with more than 100 exchanges in JavaScript / TypeScript / Python / C# / PHP / Go

1,040 lines (1,037 loc) • 74.7 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var luno$1 = require('./abstract/luno.js'); var errors = require('./base/errors.js'); var Precise = require('./base/Precise.js'); var number = require('./base/functions/number.js'); // ---------------------------------------------------------------------------- // --------------------------------------------------------------------------- /** * @class luno * @augments Exchange */ class luno extends luno$1["default"] { describe() { return this.deepExtend(super.describe(), { 'id': 'luno', 'name': 'Luno', 'countries': ['GB', 'SG', 'ZA'], // 300 calls per minute = 5 calls per second = 1000ms / 5 = 200ms between requests 'rateLimit': 200, 'version': '1', 'pro': true, 'has': { 'CORS': undefined, 'spot': true, 'margin': false, 'swap': false, 'future': false, 'option': false, 'addMargin': false, 'borrowCrossMargin': false, 'borrowIsolatedMargin': false, 'borrowMargin': false, 'cancelOrder': true, 'closeAllPositions': false, 'closePosition': false, 'createDepositAddress': true, 'createOrder': true, 'createReduceOnlyOrder': false, 'fetchAccounts': true, 'fetchAllGreeks': false, 'fetchBalance': true, 'fetchBorrowInterest': false, 'fetchBorrowRate': false, 'fetchBorrowRateHistories': false, 'fetchBorrowRateHistory': false, 'fetchBorrowRates': false, 'fetchBorrowRatesPerSymbol': false, 'fetchClosedOrders': true, 'fetchCrossBorrowRate': false, 'fetchCrossBorrowRates': false, 'fetchCurrencies': true, 'fetchDepositAddress': true, 'fetchFundingHistory': false, 'fetchFundingInterval': false, 'fetchFundingIntervals': false, 'fetchFundingRate': false, 'fetchFundingRateHistory': false, 'fetchFundingRates': false, 'fetchGreeks': false, 'fetchIndexOHLCV': false, 'fetchIsolatedBorrowRate': false, 'fetchIsolatedBorrowRates': false, 'fetchIsolatedPositions': false, 'fetchLedger': true, 'fetchLeverage': false, 'fetchLeverages': false, 'fetchLeverageTiers': false, 'fetchLiquidations': false, 'fetchLongShortRatio': false, 'fetchLongShortRatioHistory': false, 'fetchMarginAdjustmentHistory': false, 'fetchMarginMode': false, 'fetchMarginModes': false, 'fetchMarketLeverageTiers': false, 'fetchMarkets': true, 'fetchMarkOHLCV': false, 'fetchMarkPrice': false, 'fetchMarkPrices': false, 'fetchMyLiquidations': false, 'fetchMySettlementHistory': false, 'fetchMyTrades': true, 'fetchOHLCV': true, 'fetchOpenInterest': false, 'fetchOpenInterestHistory': false, 'fetchOpenInterests': false, 'fetchOpenOrders': true, 'fetchOption': false, 'fetchOptionChain': false, 'fetchOrder': true, 'fetchOrderBook': true, 'fetchOrders': true, 'fetchPosition': false, 'fetchPositionForSymbolWs': false, 'fetchPositionHistory': false, 'fetchPositionMode': false, 'fetchPositions': false, 'fetchPositionsForSymbol': false, 'fetchPositionsForSymbolWs': false, 'fetchPositionsHistory': false, 'fetchPositionsRisk': false, 'fetchPremiumIndexOHLCV': false, 'fetchSettlementHistory': false, 'fetchTicker': true, 'fetchTickers': true, 'fetchTrades': true, 'fetchTradingFee': true, 'fetchTradingFees': false, 'fetchUnderlyingAssets': false, 'fetchVolatilityHistory': false, 'reduceMargin': false, 'repayCrossMargin': false, 'repayIsolatedMargin': false, 'setLeverage': false, 'setMargin': false, 'setMarginMode': false, 'setPositionMode': false, }, 'urls': { 'referral': 'https://www.luno.com/invite/44893A', 'logo': 'https://user-images.githubusercontent.com/1294454/27766607-8c1a69d8-5ede-11e7-930c-540b5eb9be24.jpg', 'api': { 'public': 'https://api.luno.com/api', 'private': 'https://api.luno.com/api', 'exchange': 'https://api.luno.com/api/exchange', 'exchangePrivate': 'https://api.luno.com/api/exchange', }, 'www': 'https://www.luno.com', 'doc': [ 'https://www.luno.com/en/developers/api', 'https://npmjs.org/package/bitx', 'https://github.com/bausmeier/node-bitx', ], }, 'api': { 'exchange': { 'get': { 'markets': 1, }, }, 'exchangePrivate': { 'get': { 'candles': 1, 'move': 1, 'move/list_moves': 1, 'transfers': 1, }, 'post': { 'convert': 1, 'move': 1, }, }, 'public': { 'get': { 'orderbook': 1, 'orderbook_top': 1, 'ticker': 1, 'tickers': 1, 'trades': 1, }, }, 'private': { 'get': { 'accounts/{id}/pending': 1, 'accounts/{id}/transactions': 1, 'balance': 1, 'beneficiaries': 1, 'send/networks': 1, 'fee_info': 1, 'funding_address': 1, 'listorders': 1, 'listtrades': 1, 'send_fee': 1, 'orders/{id}': 1, 'withdrawals': 1, 'withdrawals/{id}': 1, 'transfers': 1, // not found in current docs, use GET /api/exchange/1/transfers 'users/linked': 1, // GET /api/exchange/2/listorders // GET /api/exchange/2/orders/{id} // GET /api/exchange/3/order }, 'post': { 'accounts': 1, 'address/validate': 1, 'postorder': 1, 'marketorder': 1, 'stoporder': 1, 'funding_address': 1, 'withdrawals': 1, 'send': 1, 'oauth2/grant': 1, // deprecated for new applications 'beneficiaries': 1, }, 'put': { 'accounts/{id}/name': 1, }, 'delete': { 'withdrawals/{id}': 1, 'beneficiaries/{id}': 1, }, }, }, 'timeframes': { '1m': 60, '5m': 300, '15m': 900, '30m': 1800, '1h': 3600, '3h': 10800, '4h': 14400, '1d': 86400, '3d': 259200, '1w': 604800, }, 'fees': { 'trading': { 'tierBased': true, // based on volume from your primary currency (not the same for everyone) 'percentage': true, 'taker': this.parseNumber('0.001'), 'maker': this.parseNumber('0'), }, }, 'exceptions': { 'exact': { 'ErrAccountIsMigrating': errors.OperationRejected, // Account migration in progress 'ErrAccountLimit': errors.OperationRejected, // You can't add another wallet with this currency 'ErrAccountNotFound': errors.ExchangeError, // Cannot find that account 'ErrAccountsNotDifferent': errors.BadRequest, // Debit and credit accounts must be different 'ErrActiveCryptoRequestExists': errors.OperationRejected, // Send request pending. Please try again after it has completed. 'ErrAddressCreateRateLimitReached': errors.RateLimitExceeded, // Receive address create rate limit reached. Please try again later. 'ErrAddressLimitReached': errors.OperationRejected, // Receive address limit reached. 'ErrAmountTooBig': errors.BadRequest, // The specified amount is higher than the maximum allowed. 'ErrAmountTooSmall': errors.BadRequest, // The specified amount is lower than the minimum allowed. 'ErrApiKeyRevoked': errors.AuthenticationError, // Your API key has been revoked. 'ErrBeneficiaryNotFound': errors.ExchangeError, // Beneficiary not Found 'ErrBlockedSendsCurrency': errors.OperationRejected, // Sends are currently disabled for this currency 'ErrCannotStopUnknownOrNonPendingOrder': errors.InvalidOrder, // Cannot stop unknown or non-pending order. 'ErrCannotTradeWhileQuoteActive': errors.OperationRejected, // Cannot trade while you have any active quotes. 'ErrConvertPairNotSupported': errors.BadRequest, // The requested pair is not supported for conversion. 'ErrConvertRateLimited': errors.RateLimitExceeded, // You have exceeded the conversion rate limit for this pair. Please try again later. 'ErrCounterDenominationNotAllowed': errors.InvalidOrder, // Amount contains too many decimal places 'ErrCreditAccountNotTransactional': errors.BadRequest, // The specified credit-account must be transactional 'ErrCustomRefNotAllowed': errors.BadRequest, // Custom reference not allowed 'ErrDeadlineExceeded': errors.RequestTimeout, // Could not complete before the deadline 'ErrDebitAccountNotTransactional': errors.BadRequest, // Debit account not transactional 'ErrDescriptionTooLong': errors.BadRequest, // Your transaction reference is too long. The maximum length is 256 characters. 'ErrDifferentCurrencies': errors.BadRequest, // Debit and credit accounts have different currencies 'ErrDisallowedTarget': errors.InvalidAddress, // Given address not allowed. 'ErrDuplicateClientMoveID': errors.OperationRejected, // Duplicate client move id 'ErrDuplicateClientOrderID': errors.DuplicateOrderId, // Duplicate client order id 'ErrDuplicateExternalID': errors.OperationRejected, // A withdrawal with an identical external id already exists. 'ErrERC20AddressAlreadyAssigned': errors.OperationRejected, // You can only create 1 ERC-20 receive address per token 'ErrERC20AssignNonDefault': errors.BadRequest, // You can only assign ERC-20 receive addresses to your default account 'ErrFundsMoveNotFound': errors.ExchangeError, // Funds move not found 'ErrIdempotencyKeyConflict': errors.OperationRejected, // A request with this idempotency_key has already been processed. 'ErrIdempotencyKeyRequestMismatch': errors.BadRequest, // A request with this idempotency_key has a mismatched request 'ErrIncompatibleBeneficiary': errors.BadRequest, // Beneficiary is incompatible with the requested withdrawal. 'ErrIncorrectPin': errors.AuthenticationError, // Invalid pin specified 'ErrInsufficientBalance': errors.InsufficientFunds, // Insufficient balance. 'ErrInsufficientFunds': errors.InsufficientFunds, // Account has insufficient funds 'ErrInsufficientPerms': errors.PermissionDenied, // You do not have the required permissions to perform this action 'ErrInternal': errors.ExchangeNotAvailable, // Something went wrong. We're looking into it. 'ErrInvalidAccount': errors.BadRequest, // Account is invalid 'ErrInvalidAccountID': errors.BadRequest, // Invalid account ID specified 'ErrInvalidAccountNumber': errors.BadRequest, // Account number is invalid 'ErrInvalidAmount': errors.BadRequest, // Invalid amount specified 'ErrInvalidArguments': errors.BadRequest, // If any request parameters have invalid values this error will be returned. This error should also include a list of the offending fields to help identify and fix any issues. 'ErrInvalidBaseVolume': errors.InvalidOrder, // Invalid base volume for sell order. 'ErrInvalidBranchCode': errors.BadRequest, // Bank branch code is invalid. 'ErrInvalidClientOrderId': errors.InvalidOrder, // Invalid client order id 'ErrInvalidCounterVolume': errors.InvalidOrder, // Invalid counter volume for buy order. 'ErrInvalidCurrency': errors.BadRequest, // Invalid currency specified 'ErrInvalidDetails': errors.BadRequest, // Bank account details invalid 'ErrInvalidMarketPair': errors.BadSymbol, // Market pair is invalid 'ErrInvalidOrderRef': errors.InvalidOrder, // Order reference is invalid 'ErrInvalidOrderSide': errors.InvalidOrder, // Order side is invalid 'ErrInvalidParameters': errors.BadRequest, // Invalid parameters 'ErrInvalidPrice': errors.InvalidOrder, // Invalid order price. 'ErrInvalidRequestType': errors.BadRequest, // Invalid withdrawal request type specified. 'ErrInvalidSourceAccount': errors.BadRequest, // Invalid source account 'ErrInvalidStopDirection': errors.InvalidOrder, // Stop direction is invalid. 'ErrInvalidStopPrice': errors.InvalidOrder, // Invalid order stop price. 'ErrInvalidVolume': errors.InvalidOrder, // Invalid order volume. 'ErrLimitOutOfRange': errors.BadRequest, // List limit is out of allowed range 'ErrMarketNotAllowed': errors.PermissionDenied, // This market is not enabled for you. 'ErrMarketUnavailable': errors.ExchangeError, // Market not available 'ErrMaxActiveFiatRequestsExists': errors.OperationRejected, // Too many withdrawals in progress. Cancel one or try again later. 'ErrMissingIdempotencyKey': errors.BadRequest, // idempotency_key is required. 'ErrNoAddressesAssigned': errors.InvalidAddress, // No funding addresses linked to default account 'ErrNoTradesToInferStopDirection': errors.InvalidOrder, // Could not place Stop Limit Order, no trades to determine direction 'ErrNotEnoughLiquidity': errors.InvalidOrder, // Market order price would vary too much from the market rate - use a limit order instead 'ErrNotFound': errors.ExchangeError, // No result found 'ErrOrderCanceled': errors.InvalidOrder, // Your post-only order was cancelled before trading 'ErrOrderNotFound': errors.OrderNotFound, // Cannot find that order 'ErrPostOnlyMode': errors.InvalidOrder, // Market is in post-only mode 'ErrPostOnlyNotAllowed': errors.InvalidOrder, // IOC and FOK time-in-force types are not supported as post-only orders 'ErrPriceDenominationNotAllowed': errors.InvalidOrder, // Price contains too many decimal places 'ErrPriceTooHigh': errors.InvalidOrder, // Price is above the maximum 'ErrPriceTooLow': errors.InvalidOrder, // Price is below the minimum 'ErrRejectedBeneficiary': errors.OperationRejected, // Cannot request withdrawal to rejected beneficiary. 'ErrRequestTypeDoesNotSupportFastWithdrawals': errors.BadRequest, // The specified request type does not support fast withdrawals. 'ErrStopPriceTooHigh': errors.InvalidOrder, // Stop price is too high. 'ErrStopPriceTooLow': errors.InvalidOrder, // Stop price is too low. 'ErrTooManyRequests': errors.RateLimitExceeded, // You are exceeding the allowed request rate limit 'ErrTooManyRowsRequested': errors.BadRequest, // Too many rows requested 'ErrTravelRule': errors.ManualInteractionNeeded, // Please ensure that you've initiated a once-off crypto send for this specific wallet address via the website or mobile app and included relevant Travel Rule information before trying again via the send API. [Click here](https://www.luno.com/help/articles/421340781836897) for more information on the Travel Rule. 'ErrUnauthorised': errors.AuthenticationError, // You are not authorised to access this route 'ErrUnderMaintenance': errors.OnMaintenance, // The market is currently undergoing maintenance 'ErrUpdateRequired': errors.ExchangeError, // Luno app update required 'ErrUserBlockedForCancelWithdrawal': errors.PermissionDenied, // User blocked from cancelling withdrawals 'ErrUserNotVerifiedForCurrency': errors.AccountNotEnabled, // You are not verified for this currency 'ErrValueTooHigh': errors.InvalidOrder, // Order value too high 'ErrVerificationLevelTooLow': errors.AccountNotEnabled, // You must verify your identity using the Luno app before you can send crypto. 'ErrVolumeDenominationNotAllowed': errors.InvalidOrder, // Volume contains too many decimal places 'ErrVolumeTooHigh': errors.InvalidOrder, // Volume is above the maximum 'ErrVolumeTooLow': errors.InvalidOrder, // Volume is below the minimum 'ErrWithdrawalBlocked': errors.PermissionDenied, // To increase your withdraw limit add more information to your profile in settings. 'ErrWithdrawalNotFound': errors.ExchangeError, // Cannot find that withdrawal }, }, 'precisionMode': number.TICK_SIZE, 'features': { 'spot': { 'sandbox': false, 'fetchCurrencies': { 'private': true, }, 'createOrder': { 'marginMode': false, 'triggerPrice': true, // todo 'triggerPriceType': undefined, 'triggerDirection': true, // todo 'stopLossPrice': false, // todo 'takeProfitPrice': false, // todo 'attachedStopLossTakeProfit': undefined, 'timeInForce': { 'IOC': true, 'FOK': true, 'PO': true, 'GTD': false, }, 'hedged': false, 'trailing': false, 'leverage': false, 'marketBuyByCost': true, 'marketBuyRequiresPrice': false, 'selfTradePrevention': false, 'iceberg': false, }, 'createOrders': undefined, 'fetchMyTrades': { 'marginMode': false, 'limit': 1000, 'daysBack': 100000, // todo 'untilDays': 100000, // todo 'symbolRequired': true, }, 'fetchOrder': { 'marginMode': false, 'trigger': false, 'trailing': false, 'symbolRequired': false, }, 'fetchOpenOrders': { 'marginMode': false, 'limit': 1000, 'trigger': false, 'trailing': false, 'symbolRequired': false, }, 'fetchOrders': { 'marginMode': false, 'limit': 1000, 'daysBack': 100000, 'untilDays': undefined, 'trigger': false, 'trailing': false, 'symbolRequired': false, }, 'fetchClosedOrders': { 'marginMode': false, 'limit': 1000, 'daysBack': 100000, 'daysBackCanceled': 1, 'untilDays': undefined, 'trigger': false, 'trailing': false, 'symbolRequired': false, }, 'fetchOHLCV': { 'limit': undefined, }, }, 'swap': { 'linear': undefined, 'inverse': undefined, }, 'future': { 'linear': undefined, 'inverse': undefined, }, }, 'rollingWindowSize': 60000.0, }); } /** * @method * @name luno#fetchCurrencies * @description fetches all available currencies on an exchange * @see https://www.luno.com/en/developers/api#tag/Send/operation/ListSupportedNetworks * @param {dict} [params] extra parameters specific to the exchange API endpoint * @returns {dict} an associative dictionary of currencies */ async fetchCurrencies(params = {}) { if (!this.checkRequiredCredentials(false)) { return {}; } const response = await this.privateGetSendNetworks(params); // // { // "networks": [ // { // "id": 0, // "name": "Ethereum", // "native_currency": "ETH" // }, // ... // ] // } // const currenciesData = this.safeList(response, 'data', []); const grouped = this.groupBy(currenciesData, 'native_currency'); const values = Object.values(grouped); return this.parseCurrencies(values); } parseCurrency(rawCurrency) { const id = this.safeString(rawCurrency[0], 'native_currency'); // first item is guaranteed const code = this.safeCurrencyCode(id); const networks = {}; for (let i = 0; i < rawCurrency.length; i++) { const networkEntry = rawCurrency[i]; const networkId = this.safeString(networkEntry, 'name'); const networkCode = this.networkIdToCode(networkId, code); if (networkCode !== undefined) { networks[networkCode] = { 'id': networkId, 'network': networkCode, 'limits': { 'withdraw': { 'min': undefined, 'max': undefined, }, 'deposit': { 'min': undefined, 'max': undefined, }, }, 'active': undefined, 'deposit': undefined, 'withdraw': undefined, 'fee': undefined, 'precision': undefined, 'info': networkEntry, }; } } return this.safeCurrencyStructure({ 'id': id, 'code': code, 'precision': undefined, 'type': undefined, 'name': undefined, 'active': undefined, 'deposit': undefined, 'withdraw': undefined, 'fee': undefined, 'limits': { 'withdraw': { 'min': undefined, 'max': undefined, }, 'deposit': { 'min': undefined, 'max': undefined, }, }, 'networks': networks, 'info': rawCurrency, }); } /** * @method * @name luno#fetchMarkets * @description retrieves data on all markets for luno * @see https://www.luno.com/en/developers/api#tag/Market/operation/Markets * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} an array of objects representing market data */ async fetchMarkets(params = {}) { const response = await this.exchangeGetMarkets(params); // // { // "markets":[ // { // "market_id":"BCHXBT", // "trading_status":"ACTIVE", // "base_currency":"BCH", // "counter_currency":"XBT", // "min_volume":"0.01", // "max_volume":"100.00", // "volume_scale":2, // "min_price":"0.0001", // "max_price":"1.00", // "price_scale":6, // "fee_scale":8, // }, // ] // } // const result = []; const markets = this.safeValue(response, 'markets', []); for (let i = 0; i < markets.length; i++) { const market = markets[i]; const id = this.safeString(market, 'market_id'); const baseId = this.safeString(market, 'base_currency'); const quoteId = this.safeString(market, 'counter_currency'); const base = this.safeCurrencyCode(baseId); const quote = this.safeCurrencyCode(quoteId); const status = this.safeString(market, 'trading_status'); result.push({ 'id': id, 'symbol': base + '/' + quote, 'base': base, 'quote': quote, 'settle': undefined, 'baseId': baseId, 'quoteId': quoteId, 'settleId': undefined, 'type': 'spot', 'spot': true, 'margin': false, 'swap': false, 'future': false, 'option': false, 'active': (status === 'ACTIVE'), 'contract': false, 'linear': undefined, 'inverse': undefined, 'contractSize': undefined, 'expiry': undefined, 'expiryDatetime': undefined, 'strike': undefined, 'optionType': undefined, 'precision': { 'amount': this.parseNumber(this.parsePrecision(this.safeString(market, 'volume_scale'))), 'price': this.parseNumber(this.parsePrecision(this.safeString(market, 'price_scale'))), }, 'limits': { 'leverage': { 'min': undefined, 'max': undefined, }, 'amount': { 'min': this.safeNumber(market, 'min_volume'), 'max': this.safeNumber(market, 'max_volume'), }, 'price': { 'min': this.safeNumber(market, 'min_price'), 'max': this.safeNumber(market, 'max_price'), }, 'cost': { 'min': undefined, 'max': undefined, }, }, 'created': undefined, 'info': market, }); } return result; } /** * @method * @name luno#fetchAccounts * @description fetch all the accounts associated with a profile * @see https://www.luno.com/en/developers/api#tag/Accounts/operation/getBalances * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a dictionary of [account structures]{@link https://docs.ccxt.com/?id=account-structure} indexed by the account type */ async fetchAccounts(params = {}) { const response = await this.privateGetBalance(params); const wallets = this.safeValue(response, 'balance', []); const result = []; for (let i = 0; i < wallets.length; i++) { const account = wallets[i]; const accountId = this.safeString(account, 'account_id'); const currencyId = this.safeString(account, 'asset'); const code = this.safeCurrencyCode(currencyId); result.push({ 'id': accountId, 'type': undefined, 'code': code, 'info': account, }); } return result; } parseBalance(response) { const wallets = this.safeValue(response, 'balance', []); const result = { 'info': response, 'timestamp': undefined, 'datetime': undefined, }; for (let i = 0; i < wallets.length; i++) { const wallet = wallets[i]; const currencyId = this.safeString(wallet, 'asset'); const code = this.safeCurrencyCode(currencyId); const reserved = this.safeString(wallet, 'reserved'); const unconfirmed = this.safeString(wallet, 'unconfirmed'); const balance = this.safeString(wallet, 'balance'); const reservedUnconfirmed = Precise["default"].stringAdd(reserved, unconfirmed); const balanceUnconfirmed = Precise["default"].stringAdd(balance, unconfirmed); if ((code !== undefined) && (code in result)) { result[code]['used'] = Precise["default"].stringAdd(result[code]['used'], reservedUnconfirmed); result[code]['total'] = Precise["default"].stringAdd(result[code]['total'], balanceUnconfirmed); } else if (code !== undefined) { const account = this.account(); account['used'] = reservedUnconfirmed; account['total'] = balanceUnconfirmed; result[code] = account; } } return this.safeBalance(result); } /** * @method * @name luno#fetchBalance * @description query for balance and get the amount of funds available for trading or funds locked in orders * @see https://www.luno.com/en/developers/api#tag/Accounts/operation/getBalances * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure} */ async fetchBalance(params = {}) { if (this.markets === undefined) { await this.loadMarkets(); } const response = await this.privateGetBalance(params); // // { // "balance": [ // {'account_id': '119...1336','asset': 'XBT','balance': '0.00','reserved': '0.00',"unconfirmed": "0.00"}, // {'account_id': '66...289','asset': 'XBT','balance': '0.00','reserved': '0.00',"unconfirmed": "0.00"}, // {'account_id': '718...5300','asset': 'ETH','balance': '0.00','reserved': '0.00',"unconfirmed": "0.00"}, // {'account_id': '818...7072','asset': 'ZAR','balance': '0.001417','reserved': '0.00',"unconfirmed": "0.00"}]} // ] // } // return this.parseBalance(response); } /** * @method * @name luno#fetchOrderBook * @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data * @see https://www.luno.com/en/developers/api#tag/Market/operation/GetOrderBookFull * @see https://www.luno.com/en/developers/api#tag/Market/operation/GetOrderBook * @param {string} 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 {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure} */ async fetchOrderBook(symbol, limit = undefined, params = {}) { if (this.markets === undefined) { await this.loadMarkets(); } const market = this.market(symbol); const request = { 'pair': market['id'], }; let response = undefined; if (limit !== undefined && limit <= 100) { response = await this.publicGetOrderbookTop(this.extend(request, params)); } else { response = await this.publicGetOrderbook(this.extend(request, params)); } const timestamp = this.safeInteger(response, 'timestamp'); return this.parseOrderBook(response, market['symbol'], timestamp, 'bids', 'asks', 'price', 'volume'); } parseOrderStatus(status) { const statuses = { // todo add other statuses 'PENDING': 'open', }; return this.safeString(statuses, status, status); } parseOrder(order, market = undefined) { // // { // "base": "string", // "completed_timestamp": "string", // "counter": "string", // "creation_timestamp": "string", // "expiration_timestamp": "string", // "fee_base": "string", // "fee_counter": "string", // "limit_price": "string", // "limit_volume": "string", // "order_id": "string", // "pair": "string", // "state": "PENDING", // "type": "BID" // } // const timestamp = this.safeInteger(order, 'creation_timestamp'); let status = this.parseOrderStatus(this.safeString(order, 'state')); status = (status === 'open') ? status : status; let side = undefined; const orderType = this.safeString(order, 'type'); if ((orderType === 'ASK') || (orderType === 'SELL')) { side = 'sell'; } else if ((orderType === 'BID') || (orderType === 'BUY')) { side = 'buy'; } const marketId = this.safeString(order, 'pair'); market = this.safeMarket(marketId, market); const price = this.safeString(order, 'limit_price'); const amount = this.safeString(order, 'limit_volume'); const quoteFee = this.safeNumber(order, 'fee_counter'); const baseFee = this.safeNumber(order, 'fee_base'); const filled = this.safeString(order, 'base'); const cost = this.safeString(order, 'counter'); let fee = undefined; if (quoteFee !== undefined) { fee = { 'cost': quoteFee, 'currency': market['quote'], }; } else if (baseFee !== undefined) { fee = { 'cost': baseFee, 'currency': market['base'], }; } const id = this.safeString(order, 'order_id'); return this.safeOrder({ 'id': id, 'clientOrderId': undefined, 'datetime': this.iso8601(timestamp), 'timestamp': timestamp, 'lastTradeTimestamp': undefined, 'status': status, 'symbol': market['symbol'], 'type': undefined, 'timeInForce': undefined, 'postOnly': undefined, 'side': side, 'price': price, 'triggerPrice': undefined, 'amount': amount, 'filled': filled, 'cost': cost, 'remaining': undefined, 'trades': undefined, 'fee': fee, 'info': order, 'average': undefined, }, market); } /** * @method * @name luno#fetchOrder * @description fetches information on an order made by the user * @see https://www.luno.com/en/developers/api#tag/Orders/operation/GetOrder * @param {string} id order id * @param {string} symbol not used by luno fetchOrder * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure} */ async fetchOrder(id, symbol = undefined, params = {}) { if (this.markets === undefined) { await this.loadMarkets(); } const request = { 'id': id, }; const response = await this.privateGetOrdersId(this.extend(request, params)); return this.parseOrder(response); } async fetchOrdersByState(state, symbol = undefined, since = undefined, limit = undefined, params = {}) { if (this.markets === undefined) { await this.loadMarkets(); } const request = {}; let market = undefined; if (state !== undefined) { request['state'] = state; } if (symbol !== undefined) { market = this.market(symbol); request['pair'] = market['id']; } const response = await this.privateGetListorders(this.extend(request, params)); const orders = this.safeList(response, 'orders', []); return this.parseOrders(orders, market, since, limit); } /** * @method * @name luno#fetchOrders * @description fetches information on multiple orders made by the user * @see https://www.luno.com/en/developers/api#tag/Orders/operation/ListOrders * @param {string} 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 {object} [params] extra parameters specific to the exchange API endpoint * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure} */ async fetchOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) { return await this.fetchOrdersByState(undefined, symbol, since, limit, params); } /** * @method * @name luno#fetchOpenOrders * @description fetch all unfilled currently open orders * @see https://www.luno.com/en/developers/api#tag/Orders/operation/ListOrders * @param {string} 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 {object} [params] extra parameters specific to the exchange API endpoint * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure} */ async fetchOpenOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) { return await this.fetchOrdersByState('PENDING', symbol, since, limit, params); } /** * @method * @name luno#fetchClosedOrders * @description fetches information on multiple closed orders made by the user * @see https://www.luno.com/en/developers/api#tag/Orders/operation/ListOrders * @param {string} 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 {object} [params] extra parameters specific to the exchange API endpoint * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure} */ async fetchClosedOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) { return await this.fetchOrdersByState('COMPLETE', symbol, since, limit, params); } parseTicker(ticker, market = undefined) { // { // "pair":"XBTAUD", // "timestamp":1642201439301, // "bid":"59972.30000000", // "ask":"59997.99000000", // "last_trade":"59997.99000000", // "rolling_24_hour_volume":"1.89510000", // "status":"ACTIVE" // } const timestamp = this.safeInteger(ticker, 'timestamp'); const marketId = this.safeString(ticker, 'pair'); const symbol = this.safeSymbol(marketId, market); const last = this.safeString(ticker, 'last_trade'); return this.safeTicker({ 'symbol': symbol, 'timestamp': timestamp, 'datetime': this.iso8601(timestamp), 'high': undefined, 'low': undefined, 'bid': this.safeString(ticker, 'bid'), 'bidVolume': undefined, 'ask': this.safeString(ticker, 'ask'), 'askVolume': undefined, 'vwap': undefined, 'open': undefined, 'close': last, 'last': last, 'previousClose': undefined, 'change': undefined, 'percentage': undefined, 'average': undefined, 'baseVolume': this.safeString(ticker, 'rolling_24_hour_volume'), 'quoteVolume': undefined, 'info': ticker, }, market); } /** * @method * @name luno#fetchTickers * @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market * @see https://www.luno.com/en/developers/api#tag/Market/operation/GetTickers * @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure} */ async fetchTickers(symbols = undefined, params = {}) { if (this.markets === undefined) { await this.loadMarkets(); } symbols = this.marketSymbols(symbols); const response = await this.publicGetTickers(params); const tickers = this.indexBy(response['tickers'], 'pair'); const ids = Object.keys(tickers); const result = {}; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const market = this.safeMarket(id); const symbol = market['symbol']; const ticker = tickers[id]; result[symbol] = this.parseTicker(ticker, market); } return this.filterByArrayTickers(result, 'symbol', symbols); } /** * @method * @name luno#fetchTicker * @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market * @see https://www.luno.com/en/developers/api#tag/Market/operation/GetTicker * @param {string} symbol unified symbol of the market to fetch the ticker for * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure} */ async fetchTicker(symbol, params = {}) { if (this.markets === undefined) { await this.loadMarkets(); } const market = this.market(symbol); const request = { 'pair': market['id'], }; const response = await this.publicGetTicker(this.extend(request, params)); // { // "pair":"XBTAUD", // "timestamp":1642201439301, // "bid":"59972.30000000", // "ask":"59997.99000000", // "last_trade":"59997.99000000", // "rolling_24_hour_volume":"1.89510000", // "status":"ACTIVE" // } return this.parseTicker(response, market); } parseTrade(trade, market = undefined) { // // fetchTrades (public) // // { // "sequence":276989, // "timestamp":1648651276949, // "price":"35773.20000000", // "volume":"0.00300000", // "is_buy":false // } // // fetchMyTrades (private) // // { // "pair":"LTCXBT", // "sequence":3256813, // "order_id":"BXEX6XHHDT5EGW2", // "type":"ASK", // "timestamp":1648652135235, // "price":"0.002786", // "volume":"0.10", // "base":"0.10", // "counter":"0.0002786", // "fee_base":"0.0001", // "fee_counter":"0.00", // "is_buy":false, // "client_order_id":"" // } // // For public trade data (is_buy === True) indicates 'buy' side but for private trade data // is_buy indicates maker or taker. The value of "type" (ASK/BID) indicate sell/buy side. // Private trade data includes ID field which public trade data does not. const orderId = this.safeString(trade, 'order_id'); const id = this.safeString(trade, 'sequence'); let takerOrMaker = undefined; let side = undefined; if (orderId !== undefined) { const type = this.safeString(trade, 'type'); if ((type === 'ASK') || (type === 'SELL')) { side = 'sell'; } else if ((type === 'BID') || (type === 'BUY')) { side = 'buy'; } if (side === 'sell' && trade['is_buy']) { takerOrMaker = 'maker'; } else if (side === 'buy' && !trade['is_buy']) { takerOrMaker = 'maker'; } else { takerOrMaker = 'taker'; } } else { side = trade['is_buy'] ? 'buy' : 'sell'; } const feeBaseString = this.safeString(trade, 'fee_base'); const feeCounterString = this.safeString(trade, 'fee_counter'); let feeCurrency = undefined; let feeCost = undefined; if (feeBaseString !== undefined) { if (!Precise["default"].stringEquals(feeBaseString, '0.0')) { feeCurrency = this.safeString(market, 'base'); feeCost = feeBaseString; } } else if (feeCounterString !== undefined) { if (!Precise["default"].stringEquals(feeCounterString, '0.0')) { feeCurrency = this.safeString(market, 'quote'); feeCost = feeCounterString; } } const timestamp = this.safeInteger(trade, 'timestamp'); return this.safeTrade({ 'info': trade, 'id': id, 'timestamp': timestamp, 'datetime': this.iso8601(timestamp), 'symbol': this.safeString(market, 'symbol'), 'order': orderId, 'type': undefined, 'side': side, 'takerOrMaker': takerOrMaker, 'price': this.safeString(trade, 'price'), 'amount': this.safeString2(trade, 'volume', 'base'), // Does not include potential fee costs 'cost': this.safeString(trade, 'counter'), 'fee': { 'cost': feeCost, 'currency':