Current Folder
This commit is contained in:
1 parent
8b3382289b
commit
cfcada880d
4379 files changed
No files matched your search
-861
@@ -1,861 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const Exchange = require ('./base/Exchange');
|
||||
const { ExchangeError, ArgumentsRequired, ExchangeNotAvailable, InsufficientFunds, OrderNotFound, DDoSProtection, InvalidOrder, AuthenticationError } = require ('./base/errors');
|
||||
|
||||
module.exports = class tidex extends Exchange {
|
||||
describe () {
|
||||
return this.deepExtend (super.describe (), {
|
||||
'id': 'tidex',
|
||||
'name': 'Tidex',
|
||||
'countries': [ 'UK' ],
|
||||
'rateLimit': 2000,
|
||||
'version': '3',
|
||||
'userAgent': this.userAgents['chrome'],
|
||||
'has': {
|
||||
'CORS': false,
|
||||
'createMarketOrder': false,
|
||||
'fetchOrderBooks': true,
|
||||
'fetchOrder': true,
|
||||
'fetchOrders': 'emulated',
|
||||
'fetchOpenOrders': true,
|
||||
'fetchClosedOrders': 'emulated',
|
||||
'fetchTickers': true,
|
||||
'fetchMyTrades': true,
|
||||
'withdraw': true,
|
||||
'fetchCurrencies': true,
|
||||
},
|
||||
'urls': {
|
||||
'logo': 'https://user-images.githubusercontent.com/1294454/30781780-03149dc4-a12e-11e7-82bb-313b269d24d4.jpg',
|
||||
'api': {
|
||||
'web': 'https://gate.tidex.com/api',
|
||||
'public': 'https://api.tidex.com/api/3',
|
||||
'private': 'https://api.tidex.com/tapi',
|
||||
},
|
||||
'www': 'https://tidex.com',
|
||||
'doc': 'https://tidex.com/exchange/public-api',
|
||||
'referral': 'https://tidex.com/exchange/?ref=57f5638d9cd7',
|
||||
'fees': [
|
||||
'https://tidex.com/exchange/assets-spec',
|
||||
'https://tidex.com/exchange/pairs-spec',
|
||||
],
|
||||
},
|
||||
'api': {
|
||||
'web': {
|
||||
'get': [
|
||||
'currency',
|
||||
'pairs',
|
||||
'tickers',
|
||||
'orders',
|
||||
'ordershistory',
|
||||
'trade-data',
|
||||
'trade-data/{id}',
|
||||
],
|
||||
},
|
||||
'public': {
|
||||
'get': [
|
||||
'info',
|
||||
'ticker/{pair}',
|
||||
'depth/{pair}',
|
||||
'trades/{pair}',
|
||||
],
|
||||
},
|
||||
'private': {
|
||||
'post': [
|
||||
'getInfoExt',
|
||||
'getInfo',
|
||||
'Trade',
|
||||
'ActiveOrders',
|
||||
'OrderInfo',
|
||||
'CancelOrder',
|
||||
'TradeHistory',
|
||||
'CoinDepositAddress',
|
||||
'WithdrawCoin',
|
||||
'CreateCoupon',
|
||||
'RedeemCoupon',
|
||||
],
|
||||
},
|
||||
},
|
||||
'fees': {
|
||||
'trading': {
|
||||
'tierBased': false,
|
||||
'percentage': true,
|
||||
'taker': 0.1 / 100,
|
||||
'maker': 0.1 / 100,
|
||||
},
|
||||
},
|
||||
'commonCurrencies': {
|
||||
'DSH': 'DASH',
|
||||
'EMGO': 'MGO',
|
||||
'MGO': 'WMGO',
|
||||
},
|
||||
'exceptions': {
|
||||
'exact': {
|
||||
'803': InvalidOrder, // "Count could not be less than 0.001." (selling below minAmount)
|
||||
'804': InvalidOrder, // "Count could not be more than 10000." (buying above maxAmount)
|
||||
'805': InvalidOrder, // "price could not be less than X." (minPrice violation on buy & sell)
|
||||
'806': InvalidOrder, // "price could not be more than X." (maxPrice violation on buy & sell)
|
||||
'807': InvalidOrder, // "cost could not be less than X." (minCost violation on buy & sell)
|
||||
'831': InsufficientFunds, // "Not enougth X to create buy order." (buying with balance.quote < order.cost)
|
||||
'832': InsufficientFunds, // "Not enougth X to create sell order." (selling with balance.base < order.amount)
|
||||
'833': OrderNotFound, // "Order with id X was not found." (cancelling non-existent, closed and cancelled order)
|
||||
},
|
||||
'broad': {
|
||||
'Invalid pair name': ExchangeError, // {"success":0,"error":"Invalid pair name: btc_eth"}
|
||||
'invalid api key': AuthenticationError,
|
||||
'invalid sign': AuthenticationError,
|
||||
'api key dont have trade permission': AuthenticationError,
|
||||
'invalid parameter': InvalidOrder,
|
||||
'invalid order': InvalidOrder,
|
||||
'Requests too often': DDoSProtection,
|
||||
'not available': ExchangeNotAvailable,
|
||||
'data unavailable': ExchangeNotAvailable,
|
||||
'external service unavailable': ExchangeNotAvailable,
|
||||
},
|
||||
},
|
||||
'options': {
|
||||
'fetchTickersMaxLength': 2048,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async fetchCurrencies (params = {}) {
|
||||
const response = await this.webGetCurrency (params);
|
||||
const result = {};
|
||||
for (let i = 0; i < response.length; i++) {
|
||||
const currency = response[i];
|
||||
const id = this.safeString (currency, 'symbol');
|
||||
const precision = currency['amountPoint'];
|
||||
const code = this.safeCurrencyCode (id);
|
||||
let active = currency['visible'] === true;
|
||||
const canWithdraw = currency['withdrawEnable'] === true;
|
||||
const canDeposit = currency['depositEnable'] === true;
|
||||
if (!canWithdraw || !canDeposit) {
|
||||
active = false;
|
||||
}
|
||||
const name = this.safeString (currency, 'name');
|
||||
result[code] = {
|
||||
'id': id,
|
||||
'code': code,
|
||||
'name': name,
|
||||
'active': active,
|
||||
'precision': precision,
|
||||
'funding': {
|
||||
'withdraw': {
|
||||
'active': canWithdraw,
|
||||
'fee': currency['withdrawFee'],
|
||||
},
|
||||
'deposit': {
|
||||
'active': canDeposit,
|
||||
'fee': 0.0,
|
||||
},
|
||||
},
|
||||
'limits': {
|
||||
'amount': {
|
||||
'min': undefined,
|
||||
'max': Math.pow (10, precision),
|
||||
},
|
||||
'price': {
|
||||
'min': Math.pow (10, -precision),
|
||||
'max': Math.pow (10, precision),
|
||||
},
|
||||
'cost': {
|
||||
'min': undefined,
|
||||
'max': undefined,
|
||||
},
|
||||
'withdraw': {
|
||||
'min': this.safeFloat (currency, 'withdrawMinAmount'),
|
||||
'max': undefined,
|
||||
},
|
||||
'deposit': {
|
||||
'min': this.safeFloat (currency, 'depositMinAmount'),
|
||||
'max': undefined,
|
||||
},
|
||||
},
|
||||
'info': currency,
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
calculateFee (symbol, type, side, amount, price, takerOrMaker = 'taker', params = {}) {
|
||||
const market = this.markets[symbol];
|
||||
let key = 'quote';
|
||||
const rate = market[takerOrMaker];
|
||||
let cost = parseFloat (this.costToPrecision (symbol, amount * rate));
|
||||
if (side === 'sell') {
|
||||
cost *= price;
|
||||
} else {
|
||||
key = 'base';
|
||||
}
|
||||
return {
|
||||
'type': takerOrMaker,
|
||||
'currency': market[key],
|
||||
'rate': rate,
|
||||
'cost': cost,
|
||||
};
|
||||
}
|
||||
|
||||
async fetchMarkets (params = {}) {
|
||||
const response = await this.publicGetInfo (params);
|
||||
const markets = response['pairs'];
|
||||
const keys = Object.keys (markets);
|
||||
const result = [];
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const id = keys[i];
|
||||
const market = markets[id];
|
||||
const [ baseId, quoteId ] = id.split ('_');
|
||||
const base = this.safeCurrencyCode (baseId);
|
||||
const quote = this.safeCurrencyCode (quoteId);
|
||||
const symbol = base + '/' + quote;
|
||||
const precision = {
|
||||
'amount': this.safeInteger (market, 'decimal_places'),
|
||||
'price': this.safeInteger (market, 'decimal_places'),
|
||||
};
|
||||
const limits = {
|
||||
'amount': {
|
||||
'min': this.safeFloat (market, 'min_amount'),
|
||||
'max': this.safeFloat (market, 'max_amount'),
|
||||
},
|
||||
'price': {
|
||||
'min': this.safeFloat (market, 'min_price'),
|
||||
'max': this.safeFloat (market, 'max_price'),
|
||||
},
|
||||
'cost': {
|
||||
'min': this.safeFloat (market, 'min_total'),
|
||||
},
|
||||
};
|
||||
const hidden = this.safeInteger (market, 'hidden');
|
||||
const active = (hidden === 0);
|
||||
result.push ({
|
||||
'id': id,
|
||||
'symbol': symbol,
|
||||
'base': base,
|
||||
'quote': quote,
|
||||
'baseId': baseId,
|
||||
'quoteId': quoteId,
|
||||
'active': active,
|
||||
'taker': market['fee'] / 100,
|
||||
'precision': precision,
|
||||
'limits': limits,
|
||||
'info': market,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async fetchBalance (params = {}) {
|
||||
await this.loadMarkets ();
|
||||
const response = await this.privatePostGetInfoExt (params);
|
||||
const balances = this.safeValue (response, 'return');
|
||||
const result = { 'info': balances };
|
||||
const funds = this.safeValue (balances, 'funds', {});
|
||||
const currencyIds = Object.keys (funds);
|
||||
for (let i = 0; i < currencyIds.length; i++) {
|
||||
const currencyId = currencyIds[i];
|
||||
const code = this.safeCurrencyCode (currencyId);
|
||||
const balance = this.safeValue (funds, currencyId, {});
|
||||
const account = this.account ();
|
||||
account['free'] = this.safeFloat (balance, 'value');
|
||||
account['used'] = this.safeFloat (balance, 'inOrders');
|
||||
result[code] = account;
|
||||
}
|
||||
return this.parseBalance (result);
|
||||
}
|
||||
|
||||
async fetchOrderBook (symbol, limit = undefined, params = {}) {
|
||||
await this.loadMarkets ();
|
||||
const market = this.market (symbol);
|
||||
const request = {
|
||||
'pair': market['id'],
|
||||
};
|
||||
if (limit !== undefined) {
|
||||
request['limit'] = limit; // default = 150, max = 2000
|
||||
}
|
||||
const response = await this.publicGetDepthPair (this.extend (request, params));
|
||||
const market_id_in_reponse = (market['id'] in response);
|
||||
if (!market_id_in_reponse) {
|
||||
throw new ExchangeError (this.id + ' ' + market['symbol'] + ' order book is empty or not available');
|
||||
}
|
||||
const orderbook = response[market['id']];
|
||||
return this.parseOrderBook (orderbook);
|
||||
}
|
||||
|
||||
async fetchOrderBooks (symbols = undefined, limit = undefined, params = {}) {
|
||||
await this.loadMarkets ();
|
||||
let ids = undefined;
|
||||
if (symbols === undefined) {
|
||||
ids = this.ids.join ('-');
|
||||
// max URL length is 2083 symbols, including http schema, hostname, tld, etc...
|
||||
if (ids.length > 2048) {
|
||||
const numIds = this.ids.length;
|
||||
throw new ExchangeError (this.id + ' has ' + numIds.toString () + ' symbols exceeding max URL length, you are required to specify a list of symbols in the first argument to fetchOrderBooks');
|
||||
}
|
||||
} else {
|
||||
ids = this.marketIds (symbols);
|
||||
ids = ids.join ('-');
|
||||
}
|
||||
const request = {
|
||||
'pair': ids,
|
||||
};
|
||||
if (limit !== undefined) {
|
||||
request['limit'] = limit; // default = 150, max = 2000
|
||||
}
|
||||
const response = await this.publicGetDepthPair (this.extend (request, params));
|
||||
const result = {};
|
||||
ids = Object.keys (response);
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const id = ids[i];
|
||||
let symbol = id;
|
||||
if (id in this.markets_by_id) {
|
||||
symbol = this.markets_by_id[id]['symbol'];
|
||||
}
|
||||
result[symbol] = this.parseOrderBook (response[id]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
parseTicker (ticker, market = undefined) {
|
||||
//
|
||||
// { high: 0.03497582,
|
||||
// low: 0.03248474,
|
||||
// avg: 0.03373028,
|
||||
// vol: 120.11485715062999,
|
||||
// vol_cur: 3572.24914074,
|
||||
// last: 0.0337611,
|
||||
// buy: 0.0337442,
|
||||
// sell: 0.03377798,
|
||||
// updated: 1537522009 }
|
||||
//
|
||||
let timestamp = this.safeTimestamp (ticker, 'updated');
|
||||
let symbol = undefined;
|
||||
if (market !== undefined) {
|
||||
symbol = market['symbol'];
|
||||
if (!market['active']) {
|
||||
timestamp = undefined;
|
||||
}
|
||||
}
|
||||
const last = this.safeFloat (ticker, 'last');
|
||||
return {
|
||||
'symbol': symbol,
|
||||
'timestamp': timestamp,
|
||||
'datetime': this.iso8601 (timestamp),
|
||||
'high': this.safeFloat (ticker, 'high'),
|
||||
'low': this.safeFloat (ticker, 'low'),
|
||||
'bid': this.safeFloat (ticker, 'buy'),
|
||||
'bidVolume': undefined,
|
||||
'ask': this.safeFloat (ticker, 'sell'),
|
||||
'askVolume': undefined,
|
||||
'vwap': undefined,
|
||||
'open': undefined,
|
||||
'close': last,
|
||||
'last': last,
|
||||
'previousClose': undefined,
|
||||
'change': undefined,
|
||||
'percentage': undefined,
|
||||
'average': this.safeFloat (ticker, 'avg'),
|
||||
'baseVolume': this.safeFloat (ticker, 'vol_cur'),
|
||||
'quoteVolume': this.safeFloat (ticker, 'vol'),
|
||||
'info': ticker,
|
||||
};
|
||||
}
|
||||
|
||||
async fetchTickers (symbols = undefined, params = {}) {
|
||||
await this.loadMarkets ();
|
||||
let ids = this.ids;
|
||||
if (symbols === undefined) {
|
||||
const numIds = ids.length;
|
||||
ids = ids.join ('-');
|
||||
// max URL length is 2048 symbols, including http schema, hostname, tld, etc...
|
||||
if (ids.length > this.options['fetchTickersMaxLength']) {
|
||||
const maxLength = this.safeInteger (this.options, 'fetchTickersMaxLength', 2048);
|
||||
throw new ArgumentsRequired (this.id + ' has ' + numIds.toString () + ' markets exceeding max URL length for this endpoint (' + maxLength.toString () + ' characters), please, specify a list of symbols of interest in the first argument to fetchTickers');
|
||||
}
|
||||
} else {
|
||||
ids = this.marketIds (symbols);
|
||||
ids = ids.join ('-');
|
||||
}
|
||||
const request = {
|
||||
'pair': ids,
|
||||
};
|
||||
const response = await this.publicGetTickerPair (this.extend (request, params));
|
||||
const result = {};
|
||||
const keys = Object.keys (response);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const id = keys[i];
|
||||
let symbol = id;
|
||||
let market = undefined;
|
||||
if (id in this.markets_by_id) {
|
||||
market = this.markets_by_id[id];
|
||||
symbol = market['symbol'];
|
||||
}
|
||||
result[symbol] = this.parseTicker (response[id], market);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async fetchTicker (symbol, params = {}) {
|
||||
const tickers = await this.fetchTickers ([ symbol ], params);
|
||||
return tickers[symbol];
|
||||
}
|
||||
|
||||
parseTrade (trade, market = undefined) {
|
||||
const timestamp = this.safeTimestamp (trade, 'timestamp');
|
||||
let side = this.safeString (trade, 'type');
|
||||
if (side === 'ask') {
|
||||
side = 'sell';
|
||||
} else if (side === 'bid') {
|
||||
side = 'buy';
|
||||
}
|
||||
const price = this.safeFloat2 (trade, 'rate', 'price');
|
||||
const id = this.safeString2 (trade, 'trade_id', 'tid');
|
||||
const orderId = this.safeString (trade, 'order_id');
|
||||
if ('pair' in trade) {
|
||||
const marketId = this.safeString (trade, 'pair');
|
||||
market = this.safeValue (this.markets_by_id, marketId, market);
|
||||
}
|
||||
let symbol = undefined;
|
||||
if (market !== undefined) {
|
||||
symbol = market['symbol'];
|
||||
}
|
||||
const amount = this.safeFloat (trade, 'amount');
|
||||
const type = 'limit'; // all trades are still limit trades
|
||||
let takerOrMaker = undefined;
|
||||
let fee = undefined;
|
||||
const feeCost = this.safeFloat (trade, 'commission');
|
||||
if (feeCost !== undefined) {
|
||||
const feeCurrencyId = this.safeString (trade, 'commissionCurrency');
|
||||
const feeCurrencyCode = this.safeCurrencyCode (feeCurrencyId);
|
||||
fee = {
|
||||
'cost': feeCost,
|
||||
'currency': feeCurrencyCode,
|
||||
};
|
||||
}
|
||||
const isYourOrder = this.safeValue (trade, 'is_your_order');
|
||||
if (isYourOrder !== undefined) {
|
||||
takerOrMaker = 'taker';
|
||||
if (isYourOrder) {
|
||||
takerOrMaker = 'maker';
|
||||
}
|
||||
if (fee === undefined) {
|
||||
fee = this.calculateFee (symbol, type, side, amount, price, takerOrMaker);
|
||||
}
|
||||
}
|
||||
let cost = undefined;
|
||||
if (amount !== undefined) {
|
||||
if (price !== undefined) {
|
||||
cost = amount * price;
|
||||
}
|
||||
}
|
||||
return {
|
||||
'id': id,
|
||||
'order': orderId,
|
||||
'timestamp': timestamp,
|
||||
'datetime': this.iso8601 (timestamp),
|
||||
'symbol': symbol,
|
||||
'type': type,
|
||||
'side': side,
|
||||
'takerOrMaker': takerOrMaker,
|
||||
'price': price,
|
||||
'amount': amount,
|
||||
'cost': cost,
|
||||
'fee': fee,
|
||||
'info': trade,
|
||||
};
|
||||
}
|
||||
|
||||
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
|
||||
await this.loadMarkets ();
|
||||
const market = this.market (symbol);
|
||||
const request = {
|
||||
'pair': market['id'],
|
||||
};
|
||||
if (limit !== undefined) {
|
||||
request['limit'] = limit;
|
||||
}
|
||||
const response = await this.publicGetTradesPair (this.extend (request, params));
|
||||
if (Array.isArray (response)) {
|
||||
const numElements = response.length;
|
||||
if (numElements === 0) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return this.parseTrades (response[market['id']], market, since, limit);
|
||||
}
|
||||
|
||||
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
|
||||
if (type === 'market') {
|
||||
throw new ExchangeError (this.id + ' allows limit orders only');
|
||||
}
|
||||
await this.loadMarkets ();
|
||||
const market = this.market (symbol);
|
||||
const request = {
|
||||
'pair': market['id'],
|
||||
'type': side,
|
||||
'amount': this.amountToPrecision (symbol, amount),
|
||||
'rate': this.priceToPrecision (symbol, price),
|
||||
};
|
||||
price = parseFloat (price);
|
||||
amount = parseFloat (amount);
|
||||
const response = await this.privatePostTrade (this.extend (request, params));
|
||||
let id = undefined;
|
||||
let status = 'open';
|
||||
let filled = 0.0;
|
||||
let remaining = amount;
|
||||
if ('return' in response) {
|
||||
id = this.safeString (response['return'], 'order_id');
|
||||
if (id === '0') {
|
||||
id = this.safeString (response['return'], 'init_order_id');
|
||||
status = 'closed';
|
||||
}
|
||||
filled = this.safeFloat (response['return'], 'received', 0.0);
|
||||
remaining = this.safeFloat (response['return'], 'remains', amount);
|
||||
}
|
||||
const timestamp = this.milliseconds ();
|
||||
const order = {
|
||||
'id': id,
|
||||
'timestamp': timestamp,
|
||||
'datetime': this.iso8601 (timestamp),
|
||||
'lastTradeTimestamp': undefined,
|
||||
'status': status,
|
||||
'symbol': symbol,
|
||||
'type': type,
|
||||
'side': side,
|
||||
'price': price,
|
||||
'cost': price * filled,
|
||||
'amount': amount,
|
||||
'remaining': remaining,
|
||||
'filled': filled,
|
||||
'fee': undefined,
|
||||
// 'trades': this.parseTrades (order['trades'], market),
|
||||
'info': response,
|
||||
'clientOrderId': undefined,
|
||||
'average': undefined,
|
||||
'trades': undefined,
|
||||
};
|
||||
this.orders[id] = order;
|
||||
return order;
|
||||
}
|
||||
|
||||
async cancelOrder (id, symbol = undefined, params = {}) {
|
||||
await this.loadMarkets ();
|
||||
const request = {
|
||||
'order_id': parseInt (id),
|
||||
};
|
||||
const response = await this.privatePostCancelOrder (this.extend (request, params));
|
||||
if (id in this.orders) {
|
||||
this.orders[id]['status'] = 'canceled';
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
parseOrderStatus (status) {
|
||||
const statuses = {
|
||||
'0': 'open',
|
||||
'1': 'closed',
|
||||
'2': 'canceled',
|
||||
'3': 'canceled', // or partially-filled and still open? https://github.com/ccxt/ccxt/issues/1594
|
||||
};
|
||||
return this.safeString (statuses, status, status);
|
||||
}
|
||||
|
||||
parseOrder (order, market = undefined) {
|
||||
const id = this.safeString (order, 'id');
|
||||
const status = this.parseOrderStatus (this.safeString (order, 'status'));
|
||||
const timestamp = this.safeTimestamp (order, 'timestamp_created');
|
||||
let symbol = undefined;
|
||||
if (market === undefined) {
|
||||
const marketId = this.safeString (order, 'pair');
|
||||
if (marketId in this.markets_by_id) {
|
||||
market = this.markets_by_id[marketId];
|
||||
}
|
||||
}
|
||||
if (market !== undefined) {
|
||||
symbol = market['symbol'];
|
||||
}
|
||||
let remaining = undefined;
|
||||
let amount = undefined;
|
||||
const price = this.safeFloat (order, 'rate');
|
||||
let filled = undefined;
|
||||
let cost = undefined;
|
||||
if ('start_amount' in order) {
|
||||
amount = this.safeFloat (order, 'start_amount');
|
||||
remaining = this.safeFloat (order, 'amount');
|
||||
} else {
|
||||
remaining = this.safeFloat (order, 'amount');
|
||||
if (id in this.orders) {
|
||||
amount = this.orders[id]['amount'];
|
||||
}
|
||||
}
|
||||
if (amount !== undefined) {
|
||||
if (remaining !== undefined) {
|
||||
filled = amount - remaining;
|
||||
cost = price * filled;
|
||||
}
|
||||
}
|
||||
const fee = undefined;
|
||||
return {
|
||||
'info': order,
|
||||
'id': id,
|
||||
'symbol': symbol,
|
||||
'timestamp': timestamp,
|
||||
'datetime': this.iso8601 (timestamp),
|
||||
'lastTradeTimestamp': undefined,
|
||||
'type': 'limit',
|
||||
'side': order['type'],
|
||||
'price': price,
|
||||
'cost': cost,
|
||||
'amount': amount,
|
||||
'remaining': remaining,
|
||||
'filled': filled,
|
||||
'status': status,
|
||||
'fee': fee,
|
||||
'clientOrderId': undefined,
|
||||
'average': undefined,
|
||||
'trades': undefined,
|
||||
};
|
||||
}
|
||||
|
||||
parseOrders (orders, market = undefined, since = undefined, limit = undefined, params = {}) {
|
||||
const result = [];
|
||||
const ids = Object.keys (orders);
|
||||
let symbol = undefined;
|
||||
if (market !== undefined) {
|
||||
symbol = market['symbol'];
|
||||
}
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const id = ids[i];
|
||||
const order = this.extend ({ 'id': id }, orders[id]);
|
||||
result.push (this.extend (this.parseOrder (order, market), params));
|
||||
}
|
||||
return this.filterBySymbolSinceLimit (result, symbol, since, limit);
|
||||
}
|
||||
|
||||
async fetchOrder (id, symbol = undefined, params = {}) {
|
||||
await this.loadMarkets ();
|
||||
const request = {
|
||||
'order_id': parseInt (id),
|
||||
};
|
||||
const response = await this.privatePostOrderInfo (this.extend (request, params));
|
||||
id = id.toString ();
|
||||
const newOrder = this.parseOrder (this.extend ({ 'id': id }, response['return'][id]));
|
||||
const oldOrder = (id in this.orders) ? this.orders[id] : {};
|
||||
this.orders[id] = this.extend (oldOrder, newOrder);
|
||||
return this.orders[id];
|
||||
}
|
||||
|
||||
updateCachedOrders (openOrders, symbol) {
|
||||
// update local cache with open orders
|
||||
// this will add unseen orders and overwrite existing ones
|
||||
for (let j = 0; j < openOrders.length; j++) {
|
||||
const id = openOrders[j]['id'];
|
||||
this.orders[id] = openOrders[j];
|
||||
}
|
||||
const openOrdersIndexedById = this.indexBy (openOrders, 'id');
|
||||
const cachedOrderIds = Object.keys (this.orders);
|
||||
for (let k = 0; k < cachedOrderIds.length; k++) {
|
||||
// match each cached order to an order in the open orders array
|
||||
// possible reasons why a cached order may be missing in the open orders array:
|
||||
// - order was closed or canceled -> update cache
|
||||
// - symbol mismatch (e.g. cached BTC/USDT, fetched ETH/USDT) -> skip
|
||||
const cachedOrderId = cachedOrderIds[k];
|
||||
let cachedOrder = this.orders[cachedOrderId];
|
||||
if (!(cachedOrderId in openOrdersIndexedById)) {
|
||||
// cached order is not in open orders array
|
||||
// if we fetched orders by symbol and it doesn't match the cached order -> won't update the cached order
|
||||
if (symbol !== undefined && symbol !== cachedOrder['symbol']) {
|
||||
continue;
|
||||
}
|
||||
// cached order is absent from the list of open orders -> mark the cached order as closed
|
||||
if (cachedOrder['status'] === 'open') {
|
||||
cachedOrder = this.extend (cachedOrder, {
|
||||
'status': 'closed', // likewise it might have been canceled externally (unnoticed by "us")
|
||||
'cost': undefined,
|
||||
'filled': cachedOrder['amount'],
|
||||
'remaining': 0.0,
|
||||
});
|
||||
if (cachedOrder['cost'] === undefined) {
|
||||
if (cachedOrder['filled'] !== undefined) {
|
||||
cachedOrder['cost'] = cachedOrder['filled'] * cachedOrder['price'];
|
||||
}
|
||||
}
|
||||
this.orders[cachedOrderId] = cachedOrder;
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.toArray (this.orders);
|
||||
}
|
||||
|
||||
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
|
||||
if ('fetchOrdersRequiresSymbol' in this.options) {
|
||||
if (this.options['fetchOrdersRequiresSymbol']) {
|
||||
if (symbol === undefined) {
|
||||
throw new ArgumentsRequired (this.id + ' fetchOrders requires a `symbol` argument');
|
||||
}
|
||||
}
|
||||
}
|
||||
await this.loadMarkets ();
|
||||
const request = {};
|
||||
let market = undefined;
|
||||
if (symbol !== undefined) {
|
||||
market = this.market (symbol);
|
||||
request['pair'] = market['id'];
|
||||
}
|
||||
const response = await this.privatePostActiveOrders (this.extend (request, params));
|
||||
// it can only return 'open' orders (i.e. no way to fetch 'closed' orders)
|
||||
const orders = this.safeValue (response, 'return', []);
|
||||
const openOrders = this.parseOrders (orders, market);
|
||||
const allOrders = this.updateCachedOrders (openOrders, symbol);
|
||||
const result = this.filterBySymbol (allOrders, symbol);
|
||||
return this.filterBySinceLimit (result, since, limit);
|
||||
}
|
||||
|
||||
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
|
||||
const orders = await this.fetchOrders (symbol, since, limit, params);
|
||||
return this.filterBy (orders, 'status', 'open');
|
||||
}
|
||||
|
||||
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
|
||||
const orders = await this.fetchOrders (symbol, since, limit, params);
|
||||
return this.filterBy (orders, 'status', 'closed');
|
||||
}
|
||||
|
||||
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
|
||||
await this.loadMarkets ();
|
||||
let market = undefined;
|
||||
// some derived classes use camelcase notation for request fields
|
||||
const request = {
|
||||
// 'from': 123456789, // trade ID, from which the display starts numerical 0 (test result: liqui ignores this field)
|
||||
// 'count': 1000, // the number of trades for display numerical, default = 1000
|
||||
// 'from_id': trade ID, from which the display starts numerical 0
|
||||
// 'end_id': trade ID on which the display ends numerical ∞
|
||||
// 'order': 'ASC', // sorting, default = DESC (test result: liqui ignores this field, most recent trade always goes last)
|
||||
// 'since': 1234567890, // UTC start time, default = 0 (test result: liqui ignores this field)
|
||||
// 'end': 1234567890, // UTC end time, default = ∞ (test result: liqui ignores this field)
|
||||
// 'pair': 'eth_btc', // default = all markets
|
||||
};
|
||||
if (symbol !== undefined) {
|
||||
market = this.market (symbol);
|
||||
request['pair'] = market['id'];
|
||||
}
|
||||
if (limit !== undefined) {
|
||||
request['count'] = parseInt (limit);
|
||||
}
|
||||
if (since !== undefined) {
|
||||
request['since'] = parseInt (since / 1000);
|
||||
}
|
||||
const response = await this.privatePostTradeHistory (this.extend (request, params));
|
||||
const trades = this.safeValue (response, 'return', []);
|
||||
return this.parseTrades (trades, market, since, limit);
|
||||
}
|
||||
|
||||
async withdraw (code, amount, address, tag = undefined, params = {}) {
|
||||
this.checkAddress (address);
|
||||
await this.loadMarkets ();
|
||||
const currency = this.currency (code);
|
||||
const request = {
|
||||
'coinName': currency['id'],
|
||||
'amount': parseFloat (amount),
|
||||
'address': address,
|
||||
};
|
||||
// no docs on the tag, yet...
|
||||
if (tag !== undefined) {
|
||||
throw new ExchangeError (this.id + ' withdraw() does not support the tag argument yet due to a lack of docs on withdrawing with tag/memo on behalf of the exchange.');
|
||||
}
|
||||
const response = await this.privatePostWithdrawCoin (this.extend (request, params));
|
||||
return {
|
||||
'info': response,
|
||||
'id': response['return']['tId'],
|
||||
};
|
||||
}
|
||||
|
||||
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
|
||||
let url = this.urls['api'][api];
|
||||
const query = this.omit (params, this.extractParams (path));
|
||||
if (api === 'private') {
|
||||
this.checkRequiredCredentials ();
|
||||
const nonce = this.nonce ();
|
||||
body = this.urlencode (this.extend ({
|
||||
'nonce': nonce,
|
||||
'method': path,
|
||||
}, query));
|
||||
const signature = this.hmac (this.encode (body), this.encode (this.secret), 'sha512');
|
||||
headers = {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Key': this.apiKey,
|
||||
'Sign': signature,
|
||||
};
|
||||
} else if (api === 'public') {
|
||||
url += '/' + this.implodeParams (path, params);
|
||||
if (Object.keys (query).length) {
|
||||
url += '?' + this.urlencode (query);
|
||||
}
|
||||
} else {
|
||||
url += '/' + this.implodeParams (path, params);
|
||||
if (method === 'GET') {
|
||||
if (Object.keys (query).length) {
|
||||
url += '?' + this.urlencode (query);
|
||||
}
|
||||
} else {
|
||||
if (Object.keys (query).length) {
|
||||
body = this.json (query);
|
||||
headers = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
|
||||
}
|
||||
|
||||
handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
|
||||
if (response === undefined) {
|
||||
return; // fallback to default error handler
|
||||
}
|
||||
if ('success' in response) {
|
||||
//
|
||||
// 1 - The exchange only returns the integer 'success' key from their private API
|
||||
//
|
||||
// { "success": 1, ... } httpCode === 200
|
||||
// { "success": 0, ... } httpCode === 200
|
||||
//
|
||||
// 2 - However, derived exchanges can return non-integers
|
||||
//
|
||||
// It can be a numeric string
|
||||
// { "sucesss": "1", ... }
|
||||
// { "sucesss": "0", ... }, httpCode >= 200 (can be 403, 502, etc)
|
||||
//
|
||||
// Or just a string
|
||||
// { "success": "true", ... }
|
||||
// { "success": "false", ... }, httpCode >= 200
|
||||
//
|
||||
// Or a boolean
|
||||
// { "success": true, ... }
|
||||
// { "success": false, ... }, httpCode >= 200
|
||||
//
|
||||
// 3 - Oversimplified, Python PEP8 forbids comparison operator (===) of different types
|
||||
//
|
||||
// 4 - We do not want to copy-paste and duplicate the code of this handler to other exchanges derived from Liqui
|
||||
//
|
||||
// To cover points 1, 2, 3 and 4 combined this handler should work like this:
|
||||
//
|
||||
let success = this.safeValue (response, 'success', false);
|
||||
if (typeof success === 'string') {
|
||||
if ((success === 'true') || (success === '1')) {
|
||||
success = true;
|
||||
} else {
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
if (!success) {
|
||||
const code = this.safeString (response, 'code');
|
||||
const message = this.safeString (response, 'error');
|
||||
const feedback = this.id + ' ' + body;
|
||||
this.throwExactlyMatchedException (this.exceptions['exact'], code, feedback);
|
||||
this.throwExactlyMatchedException (this.exceptions['exact'], message, feedback);
|
||||
this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback);
|
||||
throw new ExchangeError (feedback); // unknown message
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user