sfccxt
Version:
A JavaScript / Python / PHP cryptocurrency trading library with support for 130+ exchanges
1,166 lines (1,144 loc) • 96.8 kB
JavaScript
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeNotAvailable, ExchangeError, DDoSProtection, BadSymbol, InvalidOrder, ArgumentsRequired, AuthenticationError, OrderNotFound, PermissionDenied, InsufficientFunds, BadRequest, NotSupported } = require ('./base/errors');
const { TICK_SIZE } = require ('./base/functions/number');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class whitebit extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'whitebit',
'name': 'WhiteBit',
'version': 'v2',
'countries': [ 'EE' ],
'rateLimit': 500,
'has': {
'CORS': undefined,
'spot': true,
'margin': true,
'swap': false,
'future': false,
'option': false,
'borrowMargin': false,
'cancelAllOrders': false,
'cancelOrder': true,
'cancelOrders': false,
'createDepositAddress': undefined,
'createLimitOrder': undefined,
'createMarketOrder': undefined,
'createOrder': true,
'createStopLimitOrder': true,
'createStopMarketOrder': true,
'createStopOrder': true,
'editOrder': undefined,
'fetchBalance': true,
'fetchBidsAsks': undefined,
'fetchBorrowRate': false,
'fetchBorrowRateHistories': false,
'fetchBorrowRateHistory': false,
'fetchBorrowRates': false,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDeposit': true,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchDepositWithdrawFee': 'emulated',
'fetchDepositWithdrawFees': true,
'fetchFundingHistory': false,
'fetchFundingRate': false,
'fetchFundingRateHistory': false,
'fetchFundingRates': false,
'fetchIndexOHLCV': false,
'fetchMarginMode': false,
'fetchMarkets': true,
'fetchMarkOHLCV': false,
'fetchOHLCV': true,
'fetchOpenInterestHistory': false,
'fetchOpenOrders': true,
'fetchOrderBook': true,
'fetchOrderTrades': true,
'fetchPositionMode': false,
'fetchPremiumIndexOHLCV': false,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': false,
'fetchTradingFees': true,
'fetchTransactionFees': true,
'repayMargin': false,
'setLeverage': true,
'transfer': true,
'withdraw': true,
},
'timeframes': {
'1m': '1m',
'3m': '3m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'4h': '4h',
'6h': '6h',
'8h': '8h',
'12h': '12h',
'1d': '1d',
'3d': '3d',
'1w': '1w',
'1M': '1M',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/66732963-8eb7dd00-ee66-11e9-849b-10d9282bb9e0.jpg',
'api': {
'v1': {
'public': 'https://whitebit.com/api/v1/public',
'private': 'https://whitebit.com/api/v1',
},
'v2': {
'public': 'https://whitebit.com/api/v2/public',
},
'v4': {
'public': 'https://whitebit.com/api/v4/public',
'private': 'https://whitebit.com/api/v4',
},
},
'www': 'https://www.whitebit.com',
'doc': 'https://github.com/whitebit-exchange/api-docs',
'fees': 'https://whitebit.com/fee-schedule',
'referral': 'https://whitebit.com/referral/d9bdf40e-28f2-4b52-b2f9-cd1415d82963',
},
'api': {
'web': {
'get': [
'v1/healthcheck',
],
},
'v1': {
'public': {
'get': [
'markets',
'tickers',
'ticker',
'symbols',
'depth/result',
'history',
'kline',
],
},
'private': {
'post': [
'account/balance',
'order/new',
'order/cancel',
'orders',
'account/order_history',
'account/executed_history',
'account/executed_history/all',
'account/order',
],
},
},
'v2': {
'public': {
'get': [
'markets',
'ticker',
'assets',
'fee',
'depth/{market}',
'trades/{market}',
],
},
},
'v4': {
'public': {
'get': [
'assets',
'collateral/markets',
'fee',
'orderbook/{market}',
'ticker',
'trades/{market}',
'time',
'ping',
],
},
'private': {
'post': [
'collateral-account/balance',
'collateral-account/positions/history',
'collateral-account/leverage',
'collateral-account/positions/open',
'collateral-account/summary',
'main-account/address',
'main-account/balance',
'main-account/create-new-address',
'main-account/codes',
'main-account/codes/apply',
'main-account/codes/my',
'main-account/codes/history',
'main-account/fiat-deposit-url',
'main-account/history',
'main-account/withdraw',
'main-account/withdraw-pay',
'main-account/transfer',
'trade-account/balance',
'trade-account/executed-history',
'trade-account/order',
'trade-account/order/history',
'order/collateral/limit',
'order/collateral/market',
'order/collateral/trigger_market',
'order/new',
'order/market',
'order/stock_market',
'order/stop_limit',
'order/stop_market',
'order/cancel',
'orders',
'profile/websocket_token',
],
},
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'taker': this.parseNumber ('0.001'),
'maker': this.parseNumber ('0.001'),
},
},
'options': {
'fiatCurrencies': [ 'EUR', 'USD', 'RUB', 'UAH' ],
'accountsByType': {
'main': 'main',
'spot': 'spot',
'margin': 'collateral',
'trade': 'spot',
},
'networksById': {
'BEP20': 'BSC',
},
},
'precisionMode': TICK_SIZE,
'exceptions': {
'exact': {
'Unauthorized request.': AuthenticationError, // {"code":10,"message":"Unauthorized request."}
'The market format is invalid.': BadSymbol, // {"code":0,"message":"Validation failed","errors":{"market":["The market format is invalid."]}}
'Market is not available': BadSymbol, // {"success":false,"message":{"market":["Market is not available"]},"result":[]}
'Invalid payload.': BadRequest, // {"code":9,"message":"Invalid payload."}
'Amount must be greater than 0': InvalidOrder, // {"code":0,"message":"Validation failed","errors":{"amount":["Amount must be greater than 0"]}}
'Not enough balance.': InsufficientFunds, // {"code":10,"message":"Inner validation failed","errors":{"amount":["Not enough balance."]}}
'The order id field is required.': InvalidOrder, // {"code":0,"message":"Validation failed","errors":{"orderId":["The order id field is required."]}}
'Not enough balance': InsufficientFunds, // {"code":0,"message":"Validation failed","errors":{"amount":["Not enough balance"]}}
'This action is unauthorized.': PermissionDenied, // {"code":0,"message":"This action is unauthorized."}
'This API Key is not authorized to perform this action.': PermissionDenied, // {"code":4,"message":"This API Key is not authorized to perform this action."}
'Unexecuted order was not found.': OrderNotFound, // {"code":2,"message":"Inner validation failed","errors":{"order_id":["Unexecuted order was not found."]}}
'The selected from is invalid.': BadRequest, // {"code":0,"message":"Validation failed","errors":{"from":["The selected from is invalid."]}}
'503': ExchangeNotAvailable, // {"response":null,"status":503,"errors":{"message":[""]},"notification":null,"warning":null,"_token":null},
'422': OrderNotFound, // {"response":null,"status":422,"errors":{"orderId":["Finished order id 1295772653 not found on your account"]},"notification":null,"warning":"Finished order id 1295772653 not found on your account","_token":null}
},
'broad': {
'Given amount is less than min amount': InvalidOrder, // {"code":0,"message":"Validation failed","errors":{"amount":["Given amount is less than min amount 200000"],"total":["Total is less than 5.05"]}}
'Total is less than': InvalidOrder, // {"code":0,"message":"Validation failed","errors":{"amount":["Given amount is less than min amount 200000"],"total":["Total is less than 5.05"]}}
'fee must be no less than': InvalidOrder, // {"code":0,"message":"Validation failed","errors":{"amount":["Total amount + fee must be no less than 5.05505"]}}
'Enable your key in API settings': PermissionDenied, // {"code":2,"message":"This action is unauthorized. Enable your key in API settings"}
'You don\'t have such amount for transfer': InsufficientFunds, // {"code":3,"message":"Inner validation failed","errors":{"amount":["You don't have such amount for transfer (available 0.44523433, in amount: 2)"]}}
},
},
});
}
async fetchMarkets (params = {}) {
/**
* @method
* @name whitebit#fetchMarkets
* @description retrieves data on all markets for whitebit
* @see https://github.com/whitebit-exchange/api-docs/blob/main/docs/Public/http-v2.md#market-info
* @see https://github.com/whitebit-exchange/api-docs/blob/main/docs/Public/http-v4.md#collateral-markets-list
* @param {object} params extra parameters specific to the exchange api endpoint
* @returns {[object]} an array of objects representing market data
*/
let promises = [ this.v4PublicGetCollateralMarkets (params), this.v2PublicGetMarkets (params) ];
//
// Spot
//
// {
// "success": true,
// "message": "",
// "result": [
// {
// "name": "C98_USDT",
// "stock": "C98",
// "money": "USDT",
// "stockPrec": "3",
// "moneyPrec": "5",
// "feePrec": "6",
// "makerFee": "0.001",
// "takerFee": "0.001",
// "minAmount": "2.5",
// "minTotal": "5.05",
// "tradesEnabled": true
// },
// ...
// ]
// }
//
//
// Margin
//
// [
// "ADA_BTC",
// "ADA_USDT",
// "APE_USDT",
// ...
// ]
//
promises = await Promise.all (promises);
const marginMarketsResponse = promises[0];
const response = promises[1];
const markets = this.safeValue (response, 'result', []);
const marginMarkets = this.safeValue (marginMarketsResponse, 'result', []);
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'name');
const baseId = this.safeString (market, 'stock');
const quoteId = this.safeString (market, 'money');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const active = this.safeValue (market, 'tradesEnabled');
const isMargin = this.inArray (id, marginMarkets);
const entry = {
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': undefined,
'baseId': baseId,
'quoteId': quoteId,
'settleId': undefined,
'type': 'spot',
'spot': true,
'margin': isMargin,
'swap': false,
'future': false,
'option': false,
'active': active,
'contract': false,
'linear': undefined,
'inverse': undefined,
'taker': this.safeNumber (market, 'makerFee'),
'maker': this.safeNumber (market, 'takerFee'),
'contractSize': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': this.parseNumber (this.parsePrecision (this.safeString (market, 'stockPrec'))),
'price': this.parseNumber (this.parsePrecision (this.safeString (market, 'moneyPrec'))),
},
'limits': {
'leverage': {
'min': undefined,
'max': undefined,
},
'amount': {
'min': this.safeNumber (market, 'minAmount'),
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber (market, 'minTotal'),
'max': undefined,
},
},
'info': market,
};
result.push (entry);
}
return result;
}
async fetchCurrencies (params = {}) {
/**
* @method
* @name whitebit#fetchCurrencies
* @description fetches all available currencies on an exchange
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {object} an associative dictionary of currencies
*/
const response = await this.v4PublicGetAssets (params);
//
// "BTC": {
// "name": "Bitcoin",
// "unified_cryptoasset_id": 1,
// "can_withdraw": true,
// "can_deposit": true,
// "min_withdraw": "0.001",
// "max_withdraw": "2",
// "maker_fee": "0.1",
// "taker_fee": "0.1",
// "min_deposit": "0.0001",
// "max_deposit": "0",
// },
//
const ids = Object.keys (response);
const result = {};
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const currency = response[id];
// breaks down in Python due to utf8 encoding issues on the exchange side
// const name = this.safeString (currency, 'name');
const canDeposit = this.safeValue (currency, 'can_deposit', true);
const canWithdraw = this.safeValue (currency, 'can_withdraw', true);
const active = canDeposit && canWithdraw;
const code = this.safeCurrencyCode (id);
result[code] = {
'id': id,
'code': code,
'info': currency, // the original payload
'name': undefined, // see the comment above
'active': active,
'deposit': canDeposit,
'withdraw': canWithdraw,
'fee': undefined,
'precision': undefined,
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
'withdraw': {
'min': this.safeNumber (currency, 'min_withdraw'),
'max': this.safeNumber (currency, 'max_withdraw'),
},
},
};
}
return result;
}
async fetchTransactionFees (codes = undefined, params = {}) {
/**
* @method
* @name whitebit#fetchTransactionFees
* @description *DEPRECATED* please use fetchDepositWithdrawFees instead
* @param {[string]|undefined} codes not used by fetchTransactionFees ()
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/en/latest/manual.html#fee-structure}
*/
await this.loadMarkets ();
const response = await this.v4PublicGetFee (params);
//
// {
// "1INCH":{
// "is_depositable":true,
// "is_withdrawal":true,
// "ticker":"1INCH",
// "name":"1inch",
// "providers":[
// ],
// "withdraw":{
// "max_amount":"0",
// "min_amount":"21.5",
// "fixed":"17.5",
// "flex":null
// },
// "deposit":{
// "max_amount":"0",
// "min_amount":"19.5",
// "fixed":null,
// "flex":null
// }
// },
// {...}
// }
//
const currenciesIds = Object.keys (response);
const withdrawFees = {};
const depositFees = {};
for (let i = 0; i < currenciesIds.length; i++) {
const currency = currenciesIds[i];
const data = response[currency];
const code = this.safeCurrencyCode (currency);
const withdraw = this.safeValue (data, 'withdraw', {});
withdrawFees[code] = this.safeString (withdraw, 'fixed');
const deposit = this.safeValue (data, 'deposit', {});
depositFees[code] = this.safeString (deposit, 'fixed');
}
return {
'withdraw': withdrawFees,
'deposit': depositFees,
'info': response,
};
}
async fetchDepositWithdrawFees (codes = undefined, params = {}) {
/**
* @method
* @name whitebit#fetchDepositWithdrawFees
* @description fetch deposit and withdraw fees
* @param {[string]|undefined} codes not used by fetchDepositWithdrawFees ()
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/en/latest/manual.html#fee-structure}
*/
await this.loadMarkets ();
const response = await this.v4PublicGetFee (params);
//
// {
// "1INCH": {
// "is_depositable": true,
// "is_withdrawal": true,
// "ticker": "1INCH",
// "name": "1inch",
// "providers": [],
// "withdraw": {
// "max_amount": "0",
// "min_amount": "21.5",
// "fixed": "17.5",
// "flex": null
// },
// "deposit": {
// "max_amount": "0",
// "min_amount": "19.5",
// "fixed": null,
// "flex": null
// }
// },
// 'WBT (ERC20)': {
// is_depositable: true,
// is_withdrawal: true,
// ticker: 'WBT',
// name: 'WhiteBIT Token',
// providers: [],
// withdraw: { max_amount: '0', min_amount: '0.7', fixed: '0.253', flex: null },
// deposit: { max_amount: '0', min_amount: '0.35', fixed: null, flex: null }
// },
// 'WBT (TRC20)': {
// is_depositable: true,
// is_withdrawal: true,
// ticker: 'WBT',
// name: 'WhiteBIT Token',
// providers: [],
// withdraw: { max_amount: '0', min_amount: '1.5', fixed: '0.075', flex: null },
// deposit: { max_amount: '0', min_amount: '0.75', fixed: null, flex: null }
// },
// ...
// }
//
return this.parseDepositWithdrawFees (response, codes);
}
parseDepositWithdrawFees (response, codes = undefined, currencyIdKey = undefined) {
//
// {
// "1INCH": {
// "is_depositable": true,
// "is_withdrawal": true,
// "ticker": "1INCH",
// "name": "1inch",
// "providers": [],
// "withdraw": {
// "max_amount": "0",
// "min_amount": "21.5",
// "fixed": "17.5",
// "flex": null
// },
// "deposit": {
// "max_amount": "0",
// "min_amount": "19.5",
// "fixed": null,
// "flex": null
// }
// },
// 'WBT (ERC20)': {
// is_depositable: true,
// is_withdrawal: true,
// ticker: 'WBT',
// name: 'WhiteBIT Token',
// providers: [],
// withdraw: { max_amount: '0', min_amount: '0.7', fixed: '0.253', flex: null },
// deposit: { max_amount: '0', min_amount: '0.35', fixed: null, flex: null }
// },
// 'WBT (TRC20)': {
// is_depositable: true,
// is_withdrawal: true,
// ticker: 'WBT',
// name: 'WhiteBIT Token',
// providers: [],
// withdraw: { max_amount: '0', min_amount: '1.5', fixed: '0.075', flex: null },
// deposit: { max_amount: '0', min_amount: '0.75', fixed: null, flex: null }
// },
// ...
// }
//
const depositWithdrawFees = {};
codes = this.marketCodes (codes);
const currencyIds = Object.keys (response);
for (let i = 0; i < currencyIds.length; i++) {
const entry = currencyIds[i];
const splitEntry = entry.split (' ');
const currencyId = splitEntry[0];
const feeInfo = response[entry];
const code = this.safeCurrencyCode (currencyId);
if ((codes === undefined) || (this.inArray (code, codes))) {
const depositWithdrawFee = this.safeValue (depositWithdrawFees, code);
if (depositWithdrawFee === undefined) {
depositWithdrawFees[code] = this.depositWithdrawFee ({});
}
depositWithdrawFees[code]['info'][entry] = feeInfo;
let networkId = this.safeString (splitEntry, 1);
const withdraw = this.safeValue (feeInfo, 'withdraw');
const deposit = this.safeValue (feeInfo, 'deposit');
const withdrawFee = this.safeNumber (withdraw, 'fixed');
const depositFee = this.safeNumber (deposit, 'fixed');
const withdrawResult = {
'fee': withdrawFee,
'percentage': (withdrawFee !== undefined) ? false : undefined,
};
const depositResult = {
'fee': depositFee,
'percentage': (depositFee !== undefined) ? false : undefined,
};
if (networkId !== undefined) {
const networkLength = networkId.length;
networkId = networkId.slice (1, networkLength - 1);
const networkCode = this.networkIdToCode (networkId);
depositWithdrawFees[code]['networks'][networkCode] = {
'withdraw': withdrawResult,
'deposit': depositResult,
};
} else {
depositWithdrawFees[code]['withdraw'] = withdrawResult;
depositWithdrawFees[code]['deposit'] = depositResult;
}
}
}
const depositWithdrawCodes = Object.keys (depositWithdrawFees);
for (let i = 0; i < depositWithdrawCodes.length; i++) {
const code = depositWithdrawCodes[i];
const currency = this.currency (code);
depositWithdrawFees[code] = this.assignDefaultDepositWithdrawFees (depositWithdrawFees[code], currency);
}
return depositWithdrawFees;
}
async fetchTradingFees (params = {}) {
/**
* @method
* @name whitebit#fetchTradingFees
* @description fetch the trading fees for multiple markets
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {object} a dictionary of [fee structures]{@link https://docs.ccxt.com/en/latest/manual.html#fee-structure} indexed by market symbols
*/
const response = await this.v4PublicGetAssets (params);
//
// {
// '1INCH': {
// name: '1inch',
// unified_cryptoasset_id: '8104',
// can_withdraw: true,
// can_deposit: true,
// min_withdraw: '33',
// max_withdraw: '0',
// maker_fee: '0.1',
// taker_fee: '0.1',
// min_deposit: '30',
// max_deposit: '0'
// },
// ...
// }
//
const result = {};
for (let i = 0; i < this.symbols.length; i++) {
const symbol = this.symbols[i];
const market = this.market (symbol);
const fee = this.safeValue (response, market['baseId'], {});
let makerFee = this.safeString (fee, 'maker_fee');
let takerFee = this.safeString (fee, 'taker_fee');
makerFee = Precise.stringDiv (makerFee, '100');
takerFee = Precise.stringDiv (takerFee, '100');
result[symbol] = {
'info': fee,
'symbol': market['symbol'],
'percentage': true,
'tierBased': false,
'maker': this.parseNumber (makerFee),
'taker': this.parseNumber (takerFee),
};
}
return result;
}
async fetchTicker (symbol, params = {}) {
/**
* @method
* @name whitebit#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/en/latest/manual.html#ticker-structure}
*/
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
};
const response = await this.v1PublicGetTicker (this.extend (request, params));
//
// {
// "success":true,
// "message":"",
// "result": {
// "bid":"0.021979",
// "ask":"0.021996",
// "open":"0.02182",
// "high":"0.022039",
// "low":"0.02161",
// "last":"0.021987",
// "volume":"2810.267",
// "deal":"61.383565474",
// "change":"0.76",
// },
// }
//
const ticker = this.safeValue (response, 'result', {});
return this.parseTicker (ticker, market);
}
parseTicker (ticker, market = undefined) {
//
// FetchTicker (v1)
//
// {
// "bid": "0.021979",
// "ask": "0.021996",
// "open": "0.02182",
// "high": "0.022039",
// "low": "0.02161",
// "last": "0.021987",
// "volume": "2810.267",
// "deal": "61.383565474",
// "change": "0.76",
// }
//
// FetchTickers (v4)
//
// "BCH_RUB": {
// "base_id": 1831,
// "quote_id": 0,
// "last_price": "32830.21",
// "quote_volume": "1494659.8024096",
// "base_volume": "46.1083",
// "isFrozen": false,
// "change": "2.12" // in percent
// }
//
market = this.safeMarket (undefined, market);
const last = this.safeString (ticker, 'last_price');
return this.safeTicker ({
'symbol': market['symbol'],
'timestamp': undefined,
'datetime': undefined,
'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': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': this.safeString (ticker, 'change'),
'average': undefined,
'baseVolume': this.safeString2 (ticker, 'base_volume', 'volume'),
'quoteVolume': this.safeString2 (ticker, 'quote_volume', 'deal'),
'info': ticker,
}, market);
}
async fetchTickers (symbols = undefined, params = {}) {
/**
* @method
* @name whitebit#fetchTickers
* @description fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
* @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 whitebit api endpoint
* @returns {object} an array of [ticker structures]{@link https://docs.ccxt.com/en/latest/manual.html#ticker-structure}
*/
await this.loadMarkets ();
symbols = this.marketSymbols (symbols);
const response = await this.v4PublicGetTicker (params);
//
// "BCH_RUB": {
// "base_id":1831,
// "quote_id":0,
// "last_price":"32830.21",
// "quote_volume":"1494659.8024096",
// "base_volume":"46.1083",
// "isFrozen":false,
// "change":"2.12"
// },
//
const marketIds = Object.keys (response);
const result = {};
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const market = this.safeMarket (marketId);
const ticker = this.parseTicker (response[marketId], market);
const symbol = ticker['symbol'];
result[symbol] = ticker;
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
/**
* @method
* @name whitebit#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int|undefined} limit the maximum amount of order book entries to return
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/en/latest/manual.html#order-book-structure} indexed by market symbols
*/
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
};
if (limit !== undefined) {
request['depth'] = limit; // default = 50, maximum = 100
}
const response = await this.v4PublicGetOrderbookMarket (this.extend (request, params));
//
// {
// "timestamp": 1594391413,
// "asks": [
// [
// "9184.41",
// "0.773162"
// ],
// [ ... ]
// ],
// "bids": [
// [
// "9181.19",
// "0.010873"
// ],
// [ ... ]
// ]
// }
//
const timestamp = this.parseNumber (Precise.stringMul (this.safeString (response, 'timestamp'), '1000'));
return this.parseOrderBook (response, symbol, timestamp);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
/**
* @method
* @name whitebit#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int|undefined} since timestamp in ms of the earliest trade to fetch
* @param {int|undefined} limit the maximum amount of trades to fetch
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {[object]} a list of [trade structures]{@link https://docs.ccxt.com/en/latest/manual.html?#public-trades}
*/
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
};
const response = await this.v4PublicGetTradesMarket (this.extend (request, params));
//
// [
// {
// "tradeID": 158056419,
// "price": "9186.13",
// "quote_volume": "0.0021",
// "base_volume": "9186.13",
// "trade_timestamp": 1594391747,
// "type": "sell"
// },
// ],
//
return this.parseTrades (response, market, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
/**
* @method
* @name whitebit#fetchMyTrades
* @description fetch all trades made by the user
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int|undefined} since timestamp in ms of the earliest trade to fetch
* @param {int|undefined} limit the maximum amount of trades to fetch
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {[object]} a list of [trade structures]{@link https://docs.ccxt.com/en/latest/manual.html?#public-trades}
*/
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['market'] = market['id'];
}
const response = await this.v4PrivatePostTradeAccountExecutedHistory (this.extend (request, params));
//
// when no symbol is provided
//
// {
// "USDC_USDT":[
// {
// "id":"1343815269",
// "clientOrderId":"",
// "time":"1641051917.532965",
// "side":"sell",
// "role":"2",
// "amount":"9.986",
// "price":"0.9995",
// "deal":"9.981007",
// "fee":"0.009981007",
// "orderId":"58166729555"
// },
// ]
// }
//
// when a symbol is provided
//
// [
// {
// 'id': 1343815269,
// 'clientOrderId': '',
// 'time': 1641051917.532965,
// 'side': 'sell',
// 'role': 2,
// 'amount': '9.986',
// 'price': '0.9995',
// 'deal': '9.981007',
// 'fee': '0.009981007',
// 'orderId': 58166729555,
// },
// ]
//
if (Array.isArray (response)) {
return this.parseTrades (response, market, since, limit);
} else {
let results = [];
const keys = Object.keys (response);
for (let i = 0; i < keys.length; i++) {
const marketId = keys[i];
const market = this.safeMarket (marketId, undefined, '_');
const rawTrades = this.safeValue (response, marketId, []);
const parsed = this.parseTrades (rawTrades, market, since, limit);
results = this.arrayConcat (results, parsed);
}
results = this.sortBy2 (results, 'timestamp', 'id');
const tail = (since === undefined);
return this.filterBySinceLimit (results, since, limit, 'timestamp', tail);
}
}
parseTrade (trade, market = undefined) {
//
// fetchTradesV4
//
// {
// "tradeID": 158056419,
// "price": "9186.13",
// "quote_volume": "0.0021",
// "base_volume": "9186.13",
// "trade_timestamp": 1594391747,
// "type": "sell"
// }
//
// orderTrades (v4Private)
//
// {
// "time": 1593342324.613711,
// "fee": "0.00000419198",
// "price": "0.00000701",
// "amount": "598",
// "id": 149156519, // trade id
// "dealOrderId": 3134995325, // orderId
// "clientOrderId": "customId11",
// "role": 2, // 1 = maker, 2 = taker
// "deal": "0.00419198" // amount in money
// }
//
// fetchMyTrades
//
// {
// 'id': 1343815269,
// 'clientOrderId': '',
// 'time': 1641051917.532965,
// 'side': 'sell',
// 'role': 2,
// 'amount': '9.986',
// 'price': '0.9995',
// 'deal': '9.981007',
// 'fee': '0.009981007',
// 'orderId': 58166729555,
// }
//
market = this.safeMarket (undefined, market);
const timestamp = this.safeTimestamp2 (trade, 'time', 'trade_timestamp');
const orderId = this.safeString2 (trade, 'dealOrderId', 'orderId');
const cost = this.safeString (trade, 'deal');
const price = this.safeString (trade, 'price');
const amount = this.safeString2 (trade, 'amount', 'quote_volume');
const id = this.safeString2 (trade, 'id', 'tradeID');
const side = this.safeString2 (trade, 'type', 'side');
const symbol = market['symbol'];
const role = this.safeInteger (trade, 'role');
let takerOrMaker = undefined;
if (role !== undefined) {
takerOrMaker = (role === 1) ? 'maker' : 'taker';
}
let fee = undefined;
const feeCost = this.safeString (trade, 'fee');
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': market['quote'],
};
}
return this.safeTrade ({
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'id': id,
'order': orderId,
'type': undefined,
'takerOrMaker': takerOrMaker,
'side': side,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
}, market);
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
/**
* @method
* @name whitebit#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @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|undefined} since timestamp in ms of the earliest candle to fetch
* @param {int|undefined} limit the maximum amount of candles to fetch
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {[[int]]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
'interval': this.timeframes[timeframe],
};
if (since !== undefined) {
const maxLimit = 1440;
if (limit === undefined) {
limit = maxLimit;
}
limit = Math.min (limit, maxLimit);
const start = parseInt (since / 1000);
const duration = this.parseTimeframe (timeframe);
const end = this.sum (start, duration * limit);
request['start'] = start;
request['end'] = end;
}
if (limit !== undefined) {
request['limit'] = limit; // max 1440
}
const response = await this.v1PublicGetKline (this.extend (request, params));
//
// {
// "success":true,
// "message":"",
// "result":[
// [1591488000,"0.025025","0.025025","0.025029","0.025023","6.181","0.154686629"],
// [1591488060,"0.025028","0.025033","0.025035","0.025026","8.067","0.201921167"],
// [1591488120,"0.025034","0.02505","0.02505","0.025034","20.089","0.503114696"],
// ]
// }
//
const result = this.safeValue (response, 'result', []);
return this.parseOHLCVs (result, market, timeframe, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// [
// 1591488000,
// "0.025025",
// "0.025025",
// "0.025029",
// "0.025023",
// "6.181",
// "0.154686629"
// ]
//
return [
this.safeTimestamp (ohlcv, 0), // timestamp
this.safeNumber (ohlcv, 1), // open
this.safeNumber (ohlcv, 3), // high
this.safeNumber (ohlcv, 4), // low
this.safeNumber (ohlcv, 2), // close
this.safeNumber (ohlcv, 5), // volume
];
}
async fetchStatus (params = {}) {
/**
* @method
* @name whitebit#fetchStatus
* @description the latest known information on the availability of the exchange API
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/en/latest/manual.html#exchange-status-structure}
*/
const response = await this.v4PublicGetPing (params);
//
// [
// "pong"
// ]
//
const status = this.safeString (response, 0);
return {
'status': (status === 'pong') ? 'ok' : status,
'updated': undefined,
'eta': undefined,
'url': undefined,
'info': response,
};
}
async fetchTime (params = {}) {
/**
* @method
* @name whitebit#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
const response = await this.v4PublicGetTime (params);
//
// {
// "time":1635467280514
// }
//
return this.safeInteger (response, 'time');
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
/**
* @method
* @name whitebit#createOrder
* @description create a trade order
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float|undefined} price the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
* @param {object} params extra parameters specific to the whitebit api endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/en/latest/manual.html#order-structure}
*/
await this.loadMarkets ();
const market