ccxt
Version:
1,221 lines (1,219 loc) • 80.7 kB
JavaScript
'use strict';
var idex$1 = require('./abstract/idex.js');
var number = require('./base/functions/number.js');
var errors = require('./base/errors.js');
var Precise = require('./base/Precise.js');
var sha256 = require('./static_dependencies/noble-hashes/sha256.js');
var sha3 = require('./static_dependencies/noble-hashes/sha3.js');
var secp256k1 = require('./static_dependencies/noble-curves/secp256k1.js');
var crypto = require('./base/functions/crypto.js');
// ----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
/**
* @class idex
* @augments Exchange
*/
class idex extends idex$1 {
describe() {
return this.deepExtend(super.describe(), {
'id': 'idex',
'name': 'IDEX',
'countries': ['US'],
'rateLimit': 1000,
'version': 'v3',
'pro': true,
'dex': true,
'certified': false,
'requiresWeb3': true,
'has': {
'CORS': undefined,
'spot': true,
'margin': false,
'swap': false,
'future': false,
'option': false,
'addMargin': false,
'cancelAllOrders': true,
'cancelOrder': true,
'cancelOrders': false,
'closeAllPositions': false,
'closePosition': false,
'createDepositAddress': false,
'createOrder': true,
'createReduceOnlyOrder': false,
'createStopLimitOrder': true,
'createStopMarketOrder': true,
'createStopOrder': true,
'fetchBalance': true,
'fetchBorrowRateHistories': false,
'fetchBorrowRateHistory': false,
'fetchClosedOrders': true,
'fetchCrossBorrowRate': false,
'fetchCrossBorrowRates': false,
'fetchCurrencies': true,
'fetchDeposit': true,
'fetchDepositAddress': true,
'fetchDepositAddresses': false,
'fetchDepositAddressesByNetwork': false,
'fetchDeposits': true,
'fetchFundingHistory': false,
'fetchFundingRate': false,
'fetchFundingRateHistory': false,
'fetchFundingRates': false,
'fetchIndexOHLCV': false,
'fetchIsolatedBorrowRate': false,
'fetchIsolatedBorrowRates': false,
'fetchLeverage': false,
'fetchLeverageTiers': false,
'fetchMarginMode': false,
'fetchMarkets': true,
'fetchMarkOHLCV': false,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenInterestHistory': false,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': false,
'fetchPosition': false,
'fetchPositionHistory': false,
'fetchPositionMode': false,
'fetchPositions': false,
'fetchPositionsForSymbol': false,
'fetchPositionsHistory': false,
'fetchPositionsRisk': false,
'fetchPremiumIndexOHLCV': false,
'fetchStatus': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': false,
'fetchTradingFees': true,
'fetchTransactions': false,
'fetchWithdrawal': true,
'fetchWithdrawals': true,
'reduceMargin': false,
'sandbox': true,
'setLeverage': false,
'setMarginMode': false,
'setPositionMode': false,
'transfer': false,
'withdraw': true,
},
'timeframes': {
'1m': '1m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'6h': '6h',
'1d': '1d',
},
'urls': {
'test': {
'MATIC': 'https://api-sandbox-matic.idex.io',
},
'logo': 'https://user-images.githubusercontent.com/51840849/94481303-2f222100-01e0-11eb-97dd-bc14c5943a86.jpg',
'api': {
'MATIC': 'https://api-matic.idex.io',
},
'www': 'https://idex.io',
'doc': [
'https://api-docs-v3.idex.io/',
],
},
'api': {
'public': {
'get': {
'ping': 1,
'time': 1,
'exchange': 1,
'assets': 1,
'markets': 1,
'tickers': 1,
'candles': 1,
'trades': 1,
'orderbook': 1,
},
},
'private': {
'get': {
'user': 1,
'wallets': 1,
'balances': 1,
'orders': 0.1,
'fills': 0.1,
'deposits': 1,
'withdrawals': 1,
'wsToken': 1,
},
'post': {
'wallets': 1,
'orders': 0.1,
'orders/test': 0.1,
'withdrawals': 1,
},
'delete': {
'orders': 0.1,
},
},
},
'options': {
'defaultTimeInForce': 'gtc',
'defaultSelfTradePrevention': 'cn',
'network': 'MATIC',
},
'features': {
'spot': {
'sandbox': false,
'createOrder': {
'marginMode': false,
'triggerPrice': true,
// todo: revise
'triggerPriceType': {
'last': true,
'mark': true,
'index': true,
},
'triggerDirection': false,
'stopLossPrice': false,
'takeProfitPrice': false,
'attachedStopLossTakeProfit': undefined,
'timeInForce': {
'IOC': true,
'FOK': true,
'PO': true,
'GTD': false,
},
'hedged': false,
'selfTradePrevention': true,
'trailing': false,
'leverage': false,
'marketBuyByCost': false,
'marketBuyRequiresPrice': false,
'iceberg': false,
},
'createOrders': undefined,
'fetchMyTrades': {
'marginMode': false,
'limit': 1000,
'daysBack': 100000,
'untilDays': 100000,
'symbolRequired': false,
},
'fetchOrder': {
'marginMode': false,
'trigger': false,
'trailing': false,
'symbolRequired': false,
},
'fetchOpenOrders': {
'marginMode': false,
'limit': 1000,
'trigger': false,
'trailing': false,
'symbolRequired': false,
},
'fetchOrders': undefined,
'fetchClosedOrders': {
'marginMode': false,
'limit': 1000,
'daysBack': 1000000,
'daysBackCanceled': 1,
'untilDays': 1000000,
'trigger': false,
'trailing': false,
'symbolRequired': false,
},
'fetchOHLCV': {
'limit': 1000,
},
},
'swap': {
'linear': undefined,
'inverse': undefined,
},
'future': {
'linear': undefined,
'inverse': undefined,
},
},
'exceptions': {
'exact': {
'INVALID_ORDER_QUANTITY': errors.InvalidOrder,
'INSUFFICIENT_FUNDS': errors.InsufficientFunds,
'SERVICE_UNAVAILABLE': errors.ExchangeNotAvailable,
'EXCEEDED_RATE_LIMIT': errors.DDoSProtection,
'INVALID_PARAMETER': errors.BadRequest,
'WALLET_NOT_ASSOCIATED': errors.InvalidAddress,
'INVALID_WALLET_SIGNATURE': errors.AuthenticationError,
},
},
'requiredCredentials': {
'walletAddress': true,
'privateKey': true,
'apiKey': true,
'secret': true,
},
'precisionMode': number.TICK_SIZE,
'paddingMode': number.PAD_WITH_ZERO,
'commonCurrencies': {},
});
}
priceToPrecision(symbol, price) {
//
// we override priceToPrecision to fix the following issue
// https://github.com/ccxt/ccxt/issues/13367
// {"code":"INVALID_PARAMETER","message":"invalid value provided for request parameter \"price\": all quantities and prices must be below 100 billion, above 0, need to be provided as strings, and always require 4 decimals ending with 4 zeroes"}
//
const market = this.market(symbol);
price = this.decimalToPrecision(price, number.ROUND, market['precision']['price'], this.precisionMode);
return this.decimalToPrecision(price, number.TRUNCATE, market['precision']['quote'], number.TICK_SIZE, number.PAD_WITH_ZERO);
}
/**
* @method
* @name idex#fetchMarkets
* @description retrieves data on all markets for idex
* @see https://api-docs-v3.idex.io/#get-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.publicGetMarkets(params);
//
// [
// {
// "market": "ETH-USDC",
// "type": "hybrid",
// "status": "activeHybrid",
// "baseAsset": "ETH",
// "baseAssetPrecision": "8",
// "quoteAsset": "USDC",
// "quoteAssetPrecision": "8",
// "makerFeeRate": "0.0000",
// "takerFeeRate": "0.2500",
// "takerIdexFeeRate": "0.0500",
// "takerLiquidityProviderFeeRate": "0.2000",
// "tickSize": "0.01000000"
// },
// ]
//
const response2 = await this.publicGetExchange();
//
// {
// "timeZone": "UTC",
// "serverTime": "1654460599952",
// "maticDepositContractAddress": "0x3253a7e75539edaeb1db608ce6ef9aa1ac9126b6",
// "maticCustodyContractAddress": "0x3bcc4eca0a40358558ca8d1bcd2d1dbde63eb468",
// "maticUsdPrice": "0.60",
// "gasPrice": "180",
// "volume24hUsd": "10015814.46",
// "totalVolumeUsd": "1589273533.28",
// "totalTrades": "1534904",
// "totalValueLockedUsd": "12041929.44",
// "idexStakingValueLockedUsd": "20133816.98",
// "idexTokenAddress": "0x9Cb74C8032b007466865f060ad2c46145d45553D",
// "idexUsdPrice": "0.07",
// "idexMarketCapUsd": "48012346.00",
// "makerFeeRate": "0.0000",
// "takerFeeRate": "0.0025",
// "takerIdexFeeRate": "0.0005",
// "takerLiquidityProviderFeeRate": "0.0020",
// "makerTradeMinimum": "10.00000000",
// "takerTradeMinimum": "1.00000000",
// "withdrawMinimum": "0.50000000",
// "liquidityAdditionMinimum": "0.50000000",
// "liquidityRemovalMinimum": "0.40000000",
// "blockConfirmationDelay": "64"
// }
//
const maker = this.safeNumber(response2, 'makerFeeRate');
const taker = this.safeNumber(response2, 'takerFeeRate');
const makerMin = this.safeString(response2, 'makerTradeMinimum');
const takerMin = this.safeString(response2, 'takerTradeMinimum');
const minCostETH = this.parseNumber(Precise["default"].stringMin(makerMin, takerMin));
const result = [];
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const marketId = this.safeString(entry, 'market');
const baseId = this.safeString(entry, 'baseAsset');
const quoteId = this.safeString(entry, 'quoteAsset');
const base = this.safeCurrencyCode(baseId);
const quote = this.safeCurrencyCode(quoteId);
const basePrecision = this.parseNumber(this.parsePrecision(this.safeString(entry, 'baseAssetPrecision')));
const quotePrecision = this.parseNumber(this.parsePrecision(this.safeString(entry, 'quoteAssetPrecision')));
const status = this.safeString(entry, 'status');
let minCost = undefined;
if (quote === 'ETH') {
minCost = minCostETH;
}
result.push({
'id': marketId,
'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 !== 'inactive'),
'contract': false,
'linear': undefined,
'inverse': undefined,
'taker': taker,
'maker': maker,
'contractSize': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': basePrecision,
'price': this.safeNumber(entry, 'tickSize'),
'base': basePrecision,
'quote': quotePrecision,
},
'limits': {
'leverage': {
'min': undefined,
'max': undefined,
},
'amount': {
'min': basePrecision,
'max': undefined,
},
'price': {
'min': quotePrecision,
'max': undefined,
},
'cost': {
'min': minCost,
'max': undefined,
},
},
'created': undefined,
'info': entry,
});
}
return result;
}
/**
* @method
* @name idex#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://api-docs-v3.idex.io/#get-tickers
* @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 = {}) {
await this.loadMarkets();
const market = this.market(symbol);
const request = {
'market': market['id'],
};
// [
// {
// "market": "DIL-ETH",
// "time": 1598367493008,
// "open": "0.09695361",
// "high": "0.10245881",
// "low": "0.09572507",
// "close": "0.09917079",
// "closeQuantity": "0.71320950",
// "baseVolume": "309.17380612",
// "quoteVolume": "30.57633981",
// "percentChange": "2.28",
// "numTrades": 205,
// "ask": "0.09910476",
// "bid": "0.09688340",
// "sequence": 3902
// }
// ]
const response = await this.publicGetTickers(this.extend(request, params));
const ticker = this.safeDict(response, 0);
return this.parseTicker(ticker, market);
}
/**
* @method
* @name idex#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://api-docs-v3.idex.io/#get-tickers
* @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 = {}) {
await this.loadMarkets();
// [
// {
// "market": "DIL-ETH",
// "time": 1598367493008,
// "open": "0.09695361",
// "high": "0.10245881",
// "low": "0.09572507",
// "close": "0.09917079",
// "closeQuantity": "0.71320950",
// "baseVolume": "309.17380612",
// "quoteVolume": "30.57633981",
// "percentChange": "2.28",
// "numTrades": 205,
// "ask": "0.09910476",
// "bid": "0.09688340",
// "sequence": 3902
// }, ...
// ]
const response = await this.publicGetTickers(params);
return this.parseTickers(response, symbols);
}
parseTicker(ticker, market = undefined) {
// {
// "market": "DIL-ETH",
// "time": 1598367493008,
// "open": "0.09695361",
// "high": "0.10245881",
// "low": "0.09572507",
// "close": "0.09917079",
// "closeQuantity": "0.71320950",
// "baseVolume": "309.17380612",
// "quoteVolume": "30.57633981",
// "percentChange": "2.28",
// "numTrades": 205,
// "ask": "0.09910476",
// "bid": "0.09688340",
// "sequence": 3902
// }
const marketId = this.safeString(ticker, 'market');
market = this.safeMarket(marketId, market, '-');
const symbol = market['symbol'];
const timestamp = this.safeInteger(ticker, 'time');
const close = this.safeString(ticker, 'close');
return this.safeTicker({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601(timestamp),
'high': this.safeString(ticker, 'high'),
'low': this.safeString(ticker, 'low'),
'bid': this.safeString(ticker, 'bid'),
'bidVolume': undefined,
'ask': this.safeString(ticker, 'ask'),
'askVolume': undefined,
'vwap': undefined,
'open': this.safeString(ticker, 'open'),
'close': close,
'last': close,
'previousClose': undefined,
'change': undefined,
'percentage': this.safeString(ticker, 'percentChange'),
'average': undefined,
'baseVolume': this.safeString(ticker, 'baseVolume'),
'quoteVolume': this.safeString(ticker, 'quoteVolume'),
'info': ticker,
}, market);
}
/**
* @method
* @name idex#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://api-docs-v3.idex.io/#get-candles
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} 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 {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
async fetchOHLCV(symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets();
const market = this.market(symbol);
const request = {
'market': market['id'],
'interval': timeframe,
};
if (since !== undefined) {
request['start'] = since;
}
if (limit !== undefined) {
request['limit'] = Math.min(limit, 1000);
}
const response = await this.publicGetCandles(this.extend(request, params));
if (Array.isArray(response)) {
// [
// {
// "start": 1598345580000,
// "open": "0.09771286",
// "high": "0.09771286",
// "low": "0.09771286",
// "close": "0.09771286",
// "volume": "1.45340410",
// "sequence": 3853
// }, ...
// ]
return this.parseOHLCVs(response, market, timeframe, since, limit);
}
else {
// {"nextTime":1595536440000}
return [];
}
}
parseOHLCV(ohlcv, market = undefined) {
// {
// "start": 1598345580000,
// "open": "0.09771286",
// "high": "0.09771286",
// "low": "0.09771286",
// "close": "0.09771286",
// "volume": "1.45340410",
// "sequence": 3853
// }
const timestamp = this.safeInteger(ohlcv, 'start');
const open = this.safeNumber(ohlcv, 'open');
const high = this.safeNumber(ohlcv, 'high');
const low = this.safeNumber(ohlcv, 'low');
const close = this.safeNumber(ohlcv, 'close');
const volume = this.safeNumber(ohlcv, 'volume');
return [timestamp, open, high, low, close, volume];
}
/**
* @method
* @name idex#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://api-docs-v3.idex.io/#get-trades
* @param {string} 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 {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades}
*/
async fetchTrades(symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets();
const market = this.market(symbol);
const request = {
'market': market['id'],
};
if (since !== undefined) {
request['start'] = since;
}
if (limit !== undefined) {
request['limit'] = Math.min(limit, 1000);
}
// [
// {
// "fillId": "b5467d00-b13e-3fa9-8216-dd66735550fc",
// "price": "0.09771286",
// "quantity": "1.45340410",
// "quoteQuantity": "0.14201627",
// "time": 1598345638994,
// "makerSide": "buy",
// "sequence": 3853
// }, ...
// ]
const response = await this.publicGetTrades(this.extend(request, params));
return this.parseTrades(response, market, since, limit);
}
parseTrade(trade, market = undefined) {
//
// public trades
// {
// "fillId":"a4883704-850b-3c4b-8588-020b5e4c62f1",
// "price":"0.20377008",
// "quantity":"47.58448728",
// "quoteQuantity":"9.69629509",
// "time":1642091300873,
// "makerSide":"buy",
// "type":"hybrid", // one of either: "orderBook", "hybrid", or "pool"
// "sequence":31876
// }
//
// private trades
// {
// "fillId":"83429066-9334-3582-b710-78858b2f0d6b",
// "price":"0.20717368",
// "quantity":"15.00000000",
// "quoteQuantity":"3.10760523",
// "orderBookQuantity":"0.00000003",
// "orderBookQuoteQuantity":"0.00000001",
// "poolQuantity":"14.99999997",
// "poolQuoteQuantity":"3.10760522",
// "time":1642083351215,
// "makerSide":"sell",
// "sequence":31795,
// "market":"IDEX-USDC",
// "orderId":"4fe993f0-747b-11ec-bd08-79d4a0b6e47c",
// "side":"buy",
// "fee":"0.03749989",
// "feeAsset":"IDEX",
// "gas":"0.40507261",
// "liquidity":"taker",
// "type":"hybrid",
// "txId":"0x69f6d82a762d12e3201efd0b3e9cc1969351e3c6ea3cf07c47c66bf24a459815",
// "txStatus":"mined"
// }
//
const id = this.safeString(trade, 'fillId');
const priceString = this.safeString(trade, 'price');
const amountString = this.safeString(trade, 'quantity');
const costString = this.safeString(trade, 'quoteQuantity');
const timestamp = this.safeInteger(trade, 'time');
const marketId = this.safeString(trade, 'market');
const symbol = this.safeSymbol(marketId, market, '-');
// this code handles the duality of public vs private trades
const makerSide = this.safeString(trade, 'makerSide');
const oppositeSide = (makerSide === 'buy') ? 'sell' : 'buy';
const side = this.safeString(trade, 'side', oppositeSide);
const takerOrMaker = this.safeString(trade, 'liquidity', 'taker');
const feeCostString = this.safeString(trade, 'fee');
let fee = undefined;
if (feeCostString !== undefined) {
const feeCurrencyId = this.safeString(trade, 'feeAsset');
fee = {
'cost': feeCostString,
'currency': this.safeCurrencyCode(feeCurrencyId),
};
}
const orderId = this.safeString(trade, 'orderId');
return this.safeTrade({
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601(timestamp),
'symbol': symbol,
'id': id,
'order': orderId,
'type': 'limit',
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': costString,
'fee': fee,
}, market);
}
/**
* @method
* @name idex#fetchTradingFees
* @description fetch the trading fees for multiple markets
* @see https://api-docs-v3.idex.io/#get-api-account
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [fee structures]{@link https://docs.ccxt.com/#/?id=fee-structure} indexed by market symbols
*/
async fetchTradingFees(params = {}) {
this.checkRequiredCredentials();
await this.loadMarkets();
const nonce = this.uuidv1();
const request = {
'nonce': nonce,
};
let response = undefined;
response = await this.privateGetUser(this.extend(request, params));
//
// {
// "depositEnabled": true,
// "orderEnabled": true,
// "cancelEnabled": true,
// "withdrawEnabled": true,
// "totalPortfolioValueUsd": "0.00",
// "makerFeeRate": "0.0000",
// "takerFeeRate": "0.0025",
// "takerIdexFeeRate": "0.0005",
// "takerLiquidityProviderFeeRate": "0.0020"
// }
//
const maker = this.safeNumber(response, 'makerFeeRate');
const taker = this.safeNumber(response, 'takerFeeRate');
const result = {};
for (let i = 0; i < this.symbols.length; i++) {
const symbol = this.symbols[i];
result[symbol] = {
'info': response,
'symbol': symbol,
'maker': maker,
'taker': taker,
'percentage': true,
'tierBased': false,
};
}
return result;
}
/**
* @method
* @name idex#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://api-docs-v3.idex.io/#get-order-books
* @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} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure} indexed by market symbols
*/
async fetchOrderBook(symbol, limit = undefined, params = {}) {
await this.loadMarkets();
const market = this.market(symbol);
const request = {
'market': market['id'],
'level': 2,
};
if (limit !== undefined) {
request['limit'] = limit;
}
// {
// "sequence": 36416753,
// "bids": [
// [ '0.09672815', "8.22284267", 1 ],
// [ '0.09672814', "1.83685554", 1 ],
// [ '0.09672143', "4.10962617", 1 ],
// [ '0.09658884', "4.03863759", 1 ],
// [ '0.09653781', "3.35730684", 1 ],
// [ '0.09624660', "2.54163586", 1 ],
// [ '0.09617490', "1.93065030", 1 ]
// ],
// "asks": [
// [ '0.09910476', "3.22840154", 1 ],
// [ '0.09940587', "3.39796593", 1 ],
// [ '0.09948189', "4.25088898", 1 ],
// [ '0.09958362', "2.42195784", 1 ],
// [ '0.09974393', "4.25234367", 1 ],
// [ '0.09995250', "3.40192141", 1 ]
// ]
// }
const response = await this.publicGetOrderbook(this.extend(request, params));
const nonce = this.safeInteger(response, 'sequence');
return {
'symbol': symbol,
'timestamp': undefined,
'datetime': undefined,
'nonce': nonce,
'bids': this.parseSide(response, 'bids'),
'asks': this.parseSide(response, 'asks'),
};
}
parseSide(book, side) {
const bookSide = this.safeValue(book, side, []);
const result = [];
for (let i = 0; i < bookSide.length; i++) {
const order = bookSide[i];
const price = this.safeNumber(order, 0);
const amount = this.safeNumber(order, 1);
const orderCount = this.safeInteger(order, 2);
result.push([price, amount, orderCount]);
}
const descending = side === 'bids';
return this.sortBy(result, 0, descending);
}
/**
* @method
* @name idex#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://api-docs-v3.idex.io/#get-assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
async fetchCurrencies(params = {}) {
const response = await this.publicGetAssets(params);
//
// [
// {
// "name": "Ethereum",
// "symbol": "ETH",
// "contractAddress": "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
// "assetDecimals": "18",
// "exchangeDecimals": "8",
// "maticPrice": "3029.38503483"
// },
// ]
//
const result = {};
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const name = this.safeString(entry, 'name');
const currencyId = this.safeString(entry, 'symbol');
const code = this.safeCurrencyCode(currencyId);
const precision = this.parseNumber(this.parsePrecision(this.safeString(entry, 'exchangeDecimals')));
result[code] = {
'id': currencyId,
'code': code,
'info': entry,
'type': undefined,
'name': name,
'active': undefined,
'deposit': undefined,
'withdraw': undefined,
'fee': undefined,
'precision': precision,
'limits': {
'amount': { 'min': precision, 'max': undefined },
'withdraw': { 'min': precision, 'max': undefined },
},
};
}
return result;
}
parseBalance(response) {
const result = {
'info': response,
'timestamp': undefined,
'datetime': undefined,
};
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const currencyId = this.safeString(entry, 'asset');
const code = this.safeCurrencyCode(currencyId);
const account = this.account();
account['total'] = this.safeString(entry, 'quantity');
account['free'] = this.safeString(entry, 'availableForTrade');
account['used'] = this.safeString(entry, 'locked');
result[code] = account;
}
return this.safeBalance(result);
}
/**
* @method
* @name idex#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://api-docs-v3.idex.io/#get-balances
* @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 = {}) {
this.checkRequiredCredentials();
await this.loadMarkets();
const nonce1 = this.uuidv1();
const request = {
'nonce': nonce1,
'wallet': this.walletAddress,
};
// [
// {
// "asset": "DIL",
// "quantity": "0.00000000",
// "availableForTrade": "0.00000000",
// "locked": "0.00000000",
// "usdValue": null
// }, ...
// ]
const extendedRequest = this.extend(request, params);
if (extendedRequest['wallet'] === undefined) {
throw new errors.BadRequest(this.id + ' fetchBalance() wallet is undefined, set this.walletAddress or "address" in params');
}
let response = undefined;
try {
response = await this.privateGetBalances(extendedRequest);
}
catch (e) {
if (e instanceof errors.InvalidAddress) {
const walletAddress = extendedRequest['wallet'];
await this.associateWallet(walletAddress);
response = await this.privateGetBalances(extendedRequest);
}
else {
throw e;
}
}
return this.parseBalance(response);
}
/**
* @method
* @name idex#fetchMyTrades
* @description fetch all trades made by the user
* @see https://api-docs-v3.idex.io/#get-fills
* @param {string} 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 {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure}
*/
async fetchMyTrades(symbol = undefined, since = undefined, limit = undefined, params = {}) {
this.checkRequiredCredentials();
await this.loadMarkets();
let market = undefined;
const request = {
'nonce': this.uuidv1(),
'wallet': this.walletAddress,
};
if (symbol !== undefined) {
market = this.market(symbol);
request['market'] = market['id'];
}
if (since !== undefined) {
request['start'] = since;
}
if (limit !== undefined) {
request['limit'] = limit;
}
// [
// {
// "fillId": "48582d10-b9bb-3c4b-94d3-e67537cf2472",
// "price": "0.09905990",
// "quantity": "0.40000000",
// "quoteQuantity": "0.03962396",
// "time": 1598873478762,
// "makerSide": "sell",
// "sequence": 5053,
// "market": "DIL-ETH",
// "orderId": "7cdc8e90-eb7d-11ea-9e60-4118569f6e63",
// "side": "buy",
// "fee": "0.00080000",
// "feeAsset": "DIL",
// "gas": "0.00857497",
// "liquidity": "taker",
// "txId": "0xeaa02b112c0b8b61bc02fa1776a2b39d6c614e287c1af90df0a2e591da573e65",
// "txStatus": "mined"
// }
// ]
const extendedRequest = this.extend(request, params);
if (extendedRequest['wallet'] === undefined) {
throw new errors.BadRequest(this.id + ' fetchMyTrades() walletAddress is undefined, set this.walletAddress or "address" in params');
}
let response = undefined;
try {
response = await this.privateGetFills(extendedRequest);
}
catch (e) {
if (e instanceof errors.InvalidAddress) {
const walletAddress = extendedRequest['wallet'];
await this.associateWallet(walletAddress);
response = await this.privateGetFills(extendedRequest);
}
else {
throw e;
}
}
return this.parseTrades(response, market, since, limit);
}
/**
* @method
* @name idex#fetchOrder
* @description fetches information on an order made by the user
* @see https://api-docs-v3.idex.io/#get-orders
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @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 = {}) {
const request = {
'orderId': id,
};
return await this.fetchOrdersHelper(symbol, undefined, undefined, this.extend(request, params));
}
/**
* @method
* @name idex#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://api-docs-v3.idex.io/#get-orders
* @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 = {}) {
const request = {
'closed': false,
};
return await this.fetchOrdersHelper(symbol, since, limit, this.extend(request, params));
}
/**
* @method
* @name idex#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://api-docs-v3.idex.io/#get-orders
* @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 = {}) {
const request = {
'closed': true,
};
return await this.fetchOrdersHelper(symbol, since, limit, this.extend(request, params));
}
async fetchOrdersHelper(symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets();
const request = {
'nonce': this.uuidv1(),
'wallet': this.walletAddress,
};
let market = undefined;
if (symbol !== undefined) {
market = this.market(symbol);
request['market'] = market['id'];
}
if (since !== undefined) {
request['start'] = since;
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetOrders(this.extend(request, params));
// fetchClosedOrders / fetchOpenOrders
// [
// {
// "market": "DIL-ETH",
// "orderId": "7cdc8e90-eb7d-11ea-9e60-4118569f6e63",
// "wallet": "0x0AB991497116f7F5532a4c2f4f7B1784488628e1",
// "time": 1598873478650,
// "status": "filled",
// "type": "limit",
// "side": "buy",
// "originalQuantity": "0.40000000",
// "executedQuantity": "0.40000000",
// "cumulativeQuoteQuantity": "0.03962396",
// "avgExecutionPrice": "0.09905990",
// "price": "1.00000000",
// "fills": [
// {
// "fillId": "48582d10-b9bb-3c4b-94d3-e67537cf2472",
// "price": "0.09905990",
// "quantity": "0.40000000",
// "quoteQuantity": "0.03962396",
// "time": 1598873478650,
// "makerSide": "sell",
// "sequence": 5053,
// "fee": "0.00080000",
// "feeAsset": "DIL",
// "gas": "0.00857497",
// "liquidity": "taker",
// "txId": "0xeaa02b112c0b8b61bc02fa1776a2b39d6c614e287c1af90df0a2e591da573e65",
// "txStatus": "mined"
// }
// ]
// }
// ]
// fetchOrder
// { market: "DIL-ETH",
// "orderId": "7cdc8e90-eb7d-11ea-9e60-4118569f6e63",
// "wallet": "0x0AB991497116f7F5532a4c2f4f7B1784488628e1",
// "time": 1598873478650,
// "status": "filled",
// "type": "limit",
// "side": "buy",
// "originalQuantity": "0.40000000",
// "executedQuantity": "0.40000000",
// "cumulativeQuoteQuantity": "0.03962396",
// "avgExecutionPrice": "0.09905990",
// "price": "1.00000000",
// "fills":
// [ { fillId: "48582d10-b9bb-3c4b-94d3-e67537cf2472",
// "price": "0.09905990",
// "quantity": "0.40000000",
// "quoteQuantity": "0.03962396",
// "time": 1598873478650,
// "makerSide": "sell",
// "sequence": 5053,
// "fee": "0.00080000",
// "feeAsset": "DIL",
// "gas": "0.00857497",
// "liquidity": "taker",
// "txId": "0xeaa02b112c0b8b61bc02fa1776a2b39d6c614e287c1af90df0a2e591da573e65",
// "txStatus": "mined" } ] }
if (Array.isArray(response)) {
return this.parseOrders(response, market, since, limit);
}
else {
return this.parseOrder(response, market);
}
}
parseOrderStatus(status) {
// https://docs.idex.io/#order-states-amp-lifecycle
const statuses = {
'active': 'open',
'partiallyFilled': 'open',
'rejected': 'canceled',
'filled': 'closed',
};
return this.safeString(statuses, status, status);
}
parseOrder(order, market = undefined) {
//
// {
// "market": "DIL-ETH",
// "orderId": "7cdc8e90-eb7d-11ea-9e60-4118569f6e63",
// "wallet": "0x0AB991497116f7F5532a4c2f4f7B1784488628e1",
// "time": 1598873478650,
// "status": "filled",
// "type": "limit",
// "side": "buy",
// "originalQuantity": "0.40000000",
// "executedQuantity": "0.40000000",
// "cumulativeQuoteQuantity": "0.03962396",
// "avgExecutionPrice": "0.09905990",
// "price": "1.00000000",
// "fills": [
// {
// "fillId": "48582d10-b9bb-3c4b-94d3-e67537cf2472",
// "price": "0.09905990",
// "quantity": "0.40000000",
// "quoteQuantity": "0.03962396",
// "time": 1598873478650,
// "makerSide": "sell",
// "sequence": 5053,
// "fee": "0.00080000",
// "feeAsset": "DIL",
// "gas": "0.00857497",
// "liquidity": "taker",
// "txId": "0xeaa02b112c0b8b61bc02fa1776a2b39d6c614e287c1af90df0a2e591da573e65",
// "txStatus": "mined"
// }
// ]
// }
//
const timestamp = this.safeInteger(order, 'time');
const fills = this.safeValue(order, 'fills', []);
const id = this.safeString(order, 'orderId');
const clientOrderId = this.safeString(order, 'clientOrderId');
const marketId = this.safeString(order, 'market');
const side = this.safeString(order, 'side');
const symbol = this.safeSymbol(marketId, market, '-');
const type = this.safeString(order, 'type');
const amount = this.safeString(order, 'originalQuantity');
const filled = this.safeString(order, 'executedQuantity');
const average = this.safeString(order, 'avgExecutionPrice');
const price = this.safeString(order, 'price');
const rawStatus = this.safeString(order, 'status');
const timeInForce = this.safeStringUpper(order, 'timeInForce');
const status = this.parseOrderStatus(rawStatus);
return this.safeOrder({
'info': order,
'id': id,
'clientOrderId': clientOrderId,
'timestamp': timestamp,
'datetime': this.iso8601(timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': type,
'timeInForce': timeInForce,
'postOnly': undefined,
'side': side,
'price': price,
'triggerPrice': undefined,
'amount': amount,
'cost': undefined,
'average': average,
'filled': filled,
'remaining': undefined,
'status': status,
'fee': undefined,
'trades': fills,
}, market);
}
async associateWallet(walletAddress, params = {}) {
const nonce = this.uuidv1();
const noPrefix = this.remove0xPrefix(walletAddress);
const byteArray = [
this.base16ToBinary(nonce),
this.base16ToBinary(noPrefix),
];
const binary = this.binaryConcatArray(byteArray);
const hash = this.hash(binary, sha3.keccak_256, 'hex');
const signature = this.signMessageString(hash, this.privateKey);
// {
// "address": "0x0AB991497116f7F5532a4c2f4f7B1784488628e1",
// "totalPortfolioValueUsd"