ccxt
Version:
1,127 lines (1,124 loc) • 152 kB
JavaScript
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// EDIT THE CORRESPONDENT .ts FILE INSTEAD
// ---------------------------------------------------------------------------
import { ArgumentsRequired, ExchangeNotAvailable, InvalidOrder, InsufficientFunds, AccountSuspended, InvalidNonce, NotSupported, OrderNotFound, BadRequest, AuthenticationError, RateLimitExceeded, PermissionDenied } from './base/errors.js';
import { Precise } from './base/Precise.js';
import { TICK_SIZE } from './base/functions/number.js';
import kucoin from './abstract/kucoinfutures.js';
// ---------------------------------------------------------------------------
/**
* @class kucoinfutures
* @augments Exchange
*/
export default class kucoinfutures extends kucoin {
describe() {
return this.deepExtend(super.describe(), {
'id': 'kucoinfutures',
'name': 'KuCoin Futures',
'countries': ['SC'],
'rateLimit': 75,
'version': 'v1',
'certified': true,
'pro': true,
'comment': 'Platform 2.0',
'quoteJsonNumbers': false,
'has': {
'CORS': undefined,
'spot': false,
'margin': false,
'swap': true,
'future': true,
'option': false,
'addMargin': true,
'cancelAllOrders': true,
'cancelOrder': true,
'cancelOrders': true,
'closeAllPositions': false,
'closePosition': true,
'closePositions': false,
'createDepositAddress': true,
'createOrder': true,
'createOrders': true,
'createOrderWithTakeProfitAndStopLoss': true,
'createReduceOnlyOrder': true,
'createStopLimitOrder': true,
'createStopLossOrder': true,
'createStopMarketOrder': true,
'createStopOrder': true,
'createTakeProfitOrder': true,
'createTriggerOrder': true,
'fetchAccounts': true,
'fetchBalance': true,
'fetchBidsAsks': true,
'fetchBorrowRateHistories': false,
'fetchBorrowRateHistory': false,
'fetchClosedOrders': true,
'fetchCrossBorrowRate': false,
'fetchCrossBorrowRates': false,
'fetchCurrencies': false,
'fetchDepositAddress': true,
'fetchDepositAddresses': false,
'fetchDepositAddressesByNetwork': false,
'fetchDeposits': true,
'fetchDepositWithdrawFee': false,
'fetchDepositWithdrawFees': false,
'fetchFundingHistory': true,
'fetchFundingInterval': true,
'fetchFundingIntervals': false,
'fetchFundingRate': true,
'fetchFundingRateHistory': true,
'fetchIndexOHLCV': false,
'fetchIsolatedBorrowRate': false,
'fetchIsolatedBorrowRates': false,
'fetchL3OrderBook': true,
'fetchLedger': true,
'fetchLeverage': true,
'fetchLeverageTiers': false,
'fetchMarginAdjustmentHistory': false,
'fetchMarginMode': true,
'fetchMarketLeverageTiers': true,
'fetchMarkets': true,
'fetchMarkOHLCV': false,
'fetchMarkPrice': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchPosition': true,
'fetchPositionHistory': false,
'fetchPositionMode': false,
'fetchPositions': true,
'fetchPositionsHistory': true,
'fetchPremiumIndexOHLCV': false,
'fetchStatus': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': true,
'fetchTransactionFee': false,
'fetchWithdrawals': true,
'setLeverage': false,
'setMarginMode': true,
'transfer': true,
'withdraw': undefined,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/147508995-9e35030a-d046-43a1-a006-6fabd981b554.jpg',
'doc': [
'https://docs.kucoin.com/futures',
'https://docs.kucoin.com',
],
'www': 'https://futures.kucoin.com/',
'referral': 'https://futures.kucoin.com/?rcode=E5wkqe',
'api': {
'public': 'https://openapi-v2.kucoin.com',
'private': 'https://openapi-v2.kucoin.com',
'futuresPrivate': 'https://api-futures.kucoin.com',
'futuresPublic': 'https://api-futures.kucoin.com',
'webExchange': 'https://futures.kucoin.com/_api/web-front',
},
},
'requiredCredentials': {
'apiKey': true,
'secret': true,
'password': true,
},
'api': {
'futuresPublic': {
'get': {
'contracts/active': 1,
'contracts/{symbol}': 1,
'contracts/risk-limit/{symbol}': 1,
'ticker': 1,
'allTickers': 1,
'level2/snapshot': 1.33,
'level2/depth{limit}': 1,
'level2/message/query': 1,
'level3/message/query': 1,
'level3/snapshot': 1,
'trade/history': 1,
'interest/query': 1,
'index/query': 1,
'mark-price/{symbol}/current': 1,
'premium/query': 1,
'funding-rate/{symbol}/current': 1,
'timestamp': 1,
'status': 1,
'kline/query': 1,
},
'post': {
'bullet-public': 1,
},
},
'futuresPrivate': {
'get': {
'account-overview': 1.33,
'transaction-history': 4.44,
'deposit-address': 1,
'deposit-list': 1,
'withdrawals/quotas': 1,
'withdrawal-list': 1,
'transfer-list': 1,
'orders': 1.33,
'stopOrders': 1,
'recentDoneOrders': 1,
'orders/{orderId}': 1,
'orders/byClientOid': 1,
'fills': 4.44,
'recentFills': 4.44,
'openOrderStatistics': 1,
'position': 1,
'positions': 4.44,
'funding-history': 4.44,
'sub/api-key': 1,
'trade-statistics': 1,
'trade-fees': 1,
'history-positions': 1,
'getMaxOpenSize': 1,
'getCrossUserLeverage': 1,
'position/getMarginMode': 1,
},
'post': {
'withdrawals': 1,
'transfer-out': 1,
'transfer-in': 1,
'orders': 1.33,
'st-orders': 1.33,
'orders/test': 1.33,
'position/margin/auto-deposit-status': 1,
'position/margin/deposit-margin': 1,
'position/risk-limit-level/change': 1,
'bullet-private': 1,
'sub/api-key': 1,
'sub/api-key/update': 1,
'changeCrossUserLeverage': 1,
'position/changeMarginMode': 1,
},
'delete': {
'withdrawals/{withdrawalId}': 1,
'cancel/transfer-out': 1,
'orders/{orderId}': 1,
'orders': 4.44,
'stopOrders': 1,
'sub/api-key': 1,
'orders/client-order/{clientOid}': 1,
'orders/multi-cancel': 20,
},
},
'webExchange': {
'get': {
'contract/{symbol}/funding-rates': 1,
},
},
},
'precisionMode': TICK_SIZE,
'exceptions': {
'exact': {
'400': BadRequest,
'401': AuthenticationError,
'403': NotSupported,
'404': NotSupported,
'405': NotSupported,
'415': BadRequest,
'429': RateLimitExceeded,
'500': ExchangeNotAvailable,
'503': ExchangeNotAvailable,
'100001': InvalidOrder,
'100004': BadRequest,
'101030': PermissionDenied,
'200004': InsufficientFunds,
'230003': InsufficientFunds,
'260100': InsufficientFunds,
'300003': InsufficientFunds,
'300012': InvalidOrder,
'400001': AuthenticationError,
'400002': InvalidNonce,
'400003': AuthenticationError,
'400004': AuthenticationError,
'400005': AuthenticationError,
'400006': AuthenticationError,
'400007': AuthenticationError,
'404000': NotSupported,
'400100': BadRequest,
'411100': AccountSuspended,
'500000': ExchangeNotAvailable,
'300009': InvalidOrder, // {"msg":"No open positions to close.","code":"300009"}
},
'broad': {
'Position does not exist': OrderNotFound, // { "code":"200000", "msg":"Position does not exist" }
},
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber('0.0006'),
'maker': this.parseNumber('0.0002'),
'tiers': {
'taker': [
[this.parseNumber('0'), this.parseNumber('0.0006')],
[this.parseNumber('50'), this.parseNumber('0.0006')],
[this.parseNumber('200'), this.parseNumber('0.0006')],
[this.parseNumber('500'), this.parseNumber('0.0005')],
[this.parseNumber('1000'), this.parseNumber('0.0004')],
[this.parseNumber('2000'), this.parseNumber('0.0004')],
[this.parseNumber('4000'), this.parseNumber('0.00038')],
[this.parseNumber('8000'), this.parseNumber('0.00035')],
[this.parseNumber('15000'), this.parseNumber('0.00032')],
[this.parseNumber('25000'), this.parseNumber('0.0003')],
[this.parseNumber('40000'), this.parseNumber('0.0003')],
[this.parseNumber('60000'), this.parseNumber('0.0003')],
[this.parseNumber('80000'), this.parseNumber('0.0003')],
],
'maker': [
[this.parseNumber('0'), this.parseNumber('0.02')],
[this.parseNumber('50'), this.parseNumber('0.015')],
[this.parseNumber('200'), this.parseNumber('0.01')],
[this.parseNumber('500'), this.parseNumber('0.01')],
[this.parseNumber('1000'), this.parseNumber('0.01')],
[this.parseNumber('2000'), this.parseNumber('0')],
[this.parseNumber('4000'), this.parseNumber('0')],
[this.parseNumber('8000'), this.parseNumber('0')],
[this.parseNumber('15000'), this.parseNumber('-0.003')],
[this.parseNumber('25000'), this.parseNumber('-0.006')],
[this.parseNumber('40000'), this.parseNumber('-0.009')],
[this.parseNumber('60000'), this.parseNumber('-0.012')],
[this.parseNumber('80000'), this.parseNumber('-0.015')],
],
},
},
'funding': {
'tierBased': false,
'percentage': false,
'withdraw': {},
'deposit': {},
},
},
'commonCurrencies': {
'HOT': 'HOTNOW',
'EDGE': 'DADI',
'WAX': 'WAXP',
'TRY': 'Trias',
'VAI': 'VAIOT',
'XBT': 'BTC',
},
'timeframes': {
'1m': 1,
'3m': undefined,
'5m': 5,
'15m': 15,
'30m': 30,
'1h': 60,
'2h': 120,
'4h': 240,
'6h': undefined,
'8h': 480,
'12h': 720,
'1d': 1440,
'1w': 10080,
},
'options': {
'version': 'v1',
'symbolSeparator': '-',
'defaultType': 'swap',
'code': 'USDT',
'marginModes': {},
'marginTypes': {},
// endpoint versions
'versions': {
'futuresPrivate': {
'GET': {
'getMaxOpenSize': 'v2',
'getCrossUserLeverage': 'v2',
'position/getMarginMode': 'v2',
},
'POST': {
'transfer-out': 'v2',
'changeCrossUserLeverage': 'v2',
'position/changeMarginMode': 'v2',
},
},
'futuresPublic': {
'GET': {
'level3/snapshot': 'v2',
},
},
},
'networks': {
'OMNI': 'omni',
'ERC20': 'eth',
'TRC20': 'trx',
},
// 'code': 'BTC',
// 'fetchBalance': {
// 'code': 'BTC',
// },
},
'features': {
'spot': undefined,
'forDerivs': {
'sandbox': false,
'createOrder': {
'marginMode': true,
'triggerPrice': true,
'triggerPriceType': {
'last': true,
'mark': true,
'index': true,
},
'triggerDirection': true,
'stopLossPrice': true,
'takeProfitPrice': true,
'attachedStopLossTakeProfit': {
'triggerPriceType': undefined,
'price': true,
},
'timeInForce': {
'IOC': true,
'FOK': false,
'PO': true,
'GTD': false,
},
'hedged': false,
'trailing': false,
'leverage': true,
'marketBuyByCost': true,
'marketBuyRequiresPrice': false,
'selfTradePrevention': true,
'iceberg': true,
},
'createOrders': {
'max': 20,
},
'fetchMyTrades': {
'marginMode': true,
'limit': 1000,
'daysBack': undefined,
'untilDays': 7,
'symbolRequired': false,
},
'fetchOrder': {
'marginMode': false,
'trigger': false,
'trailing': false,
'symbolRequired': false,
},
'fetchOpenOrders': {
'marginMode': false,
'limit': 1000,
'trigger': true,
'trailing': false,
'symbolRequired': false,
},
'fetchOrders': undefined,
'fetchClosedOrders': {
'marginMode': false,
'limit': 1000,
'daysBack': undefined,
'daysBackCanceled': undefined,
'untilDays': undefined,
'trigger': true,
'trailing': false,
'symbolRequired': false,
},
'fetchOHLCV': {
'limit': 500,
},
},
'swap': {
'linear': {
'extends': 'forDerivs',
},
'inverse': {
'extends': 'forDerivs',
},
},
'future': {
'linear': {
'extends': 'forDerivs',
},
'inverse': {
'extends': 'forDerivs',
},
},
},
});
}
/**
* @method
* @name kucoinfutures#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-service-status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/#/?id=exchange-status-structure}
*/
async fetchStatus(params = {}) {
const response = await this.futuresPublicGetStatus(params);
//
// {
// "code":"200000",
// "data":{
// "status": "open", // open, close, cancelonly
// "msg": "upgrade match engine" // remark for operation when status not open
// }
// }
//
const data = this.safeValue(response, 'data', {});
const status = this.safeString(data, 'status');
return {
'status': (status === 'open') ? 'ok' : 'maintenance',
'updated': undefined,
'eta': undefined,
'url': undefined,
'info': response,
};
}
/**
* @method
* @name kucoinfutures#fetchMarkets
* @description retrieves data on all markets for kucoinfutures
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list
* @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.futuresPublicGetContractsActive(params);
//
// {
// "code": "200000",
// "data": {
// "symbol": "ETHUSDTM",
// "rootSymbol": "USDT",
// "type": "FFWCSX",
// "firstOpenDate": 1591086000000,
// "expireDate": null,
// "settleDate": null,
// "baseCurrency": "ETH",
// "quoteCurrency": "USDT",
// "settleCurrency": "USDT",
// "maxOrderQty": 1000000,
// "maxPrice": 1000000.0000000000,
// "lotSize": 1,
// "tickSize": 0.05,
// "indexPriceTickSize": 0.01,
// "multiplier": 0.01,
// "initialMargin": 0.01,
// "maintainMargin": 0.005,
// "maxRiskLimit": 1000000,
// "minRiskLimit": 1000000,
// "riskStep": 500000,
// "makerFeeRate": 0.00020,
// "takerFeeRate": 0.00060,
// "takerFixFee": 0.0000000000,
// "makerFixFee": 0.0000000000,
// "settlementFee": null,
// "isDeleverage": true,
// "isQuanto": true,
// "isInverse": false,
// "markMethod": "FairPrice",
// "fairMethod": "FundingRate",
// "fundingBaseSymbol": ".ETHINT8H",
// "fundingQuoteSymbol": ".USDTINT8H",
// "fundingRateSymbol": ".ETHUSDTMFPI8H",
// "indexSymbol": ".KETHUSDT",
// "settlementSymbol": "",
// "status": "Open",
// "fundingFeeRate": 0.000535,
// "predictedFundingFeeRate": 0.002197,
// "openInterest": "8724443",
// "turnoverOf24h": 341156641.03354263,
// "volumeOf24h": 74833.54000000,
// "markPrice": 4534.07,
// "indexPrice":4531.92,
// "lastTradePrice": 4545.4500000000,
// "nextFundingRateTime": 25481884,
// "maxLeverage": 100,
// "sourceExchanges": [ "huobi", "Okex", "Binance", "Kucoin", "Poloniex", "Hitbtc" ],
// "premiumsSymbol1M": ".ETHUSDTMPI",
// "premiumsSymbol8H": ".ETHUSDTMPI8H",
// "fundingBaseSymbol1M": ".ETHINT",
// "fundingQuoteSymbol1M": ".USDTINT",
// "lowPrice": 4456.90,
// "highPrice": 4674.25,
// "priceChgPct": 0.0046,
// "priceChg": 21.15
// }
// }
//
const result = [];
const data = this.safeValue(response, 'data', []);
for (let i = 0; i < data.length; i++) {
const market = data[i];
const id = this.safeString(market, 'symbol');
const expiry = this.safeInteger(market, 'expireDate');
const future = expiry ? true : false;
const swap = !future;
const baseId = this.safeString(market, 'baseCurrency');
const quoteId = this.safeString(market, 'quoteCurrency');
const settleId = this.safeString(market, 'settleCurrency');
const base = this.safeCurrencyCode(baseId);
const quote = this.safeCurrencyCode(quoteId);
const settle = this.safeCurrencyCode(settleId);
let symbol = base + '/' + quote + ':' + settle;
let type = 'swap';
if (future) {
symbol = symbol + '-' + this.yymmdd(expiry, '');
type = 'future';
}
const inverse = this.safeValue(market, 'isInverse');
const status = this.safeString(market, 'status');
const multiplier = this.safeString(market, 'multiplier');
const tickSize = this.safeNumber(market, 'tickSize');
const lotSize = this.safeNumber(market, 'lotSize');
let limitAmountMin = lotSize;
if (limitAmountMin === undefined) {
limitAmountMin = this.safeNumber(market, 'baseMinSize');
}
let limitAmountMax = this.safeNumber(market, 'maxOrderQty');
if (limitAmountMax === undefined) {
limitAmountMax = this.safeNumber(market, 'baseMaxSize');
}
let limitPriceMax = this.safeNumber(market, 'maxPrice');
if (limitPriceMax === undefined) {
const baseMinSizeString = this.safeString(market, 'baseMinSize');
const quoteMaxSizeString = this.safeString(market, 'quoteMaxSize');
limitPriceMax = this.parseNumber(Precise.stringDiv(quoteMaxSizeString, baseMinSizeString));
}
result.push({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': false,
'margin': false,
'swap': swap,
'future': future,
'option': false,
'active': (status === 'Open'),
'contract': true,
'linear': !inverse,
'inverse': inverse,
'taker': this.safeNumber(market, 'takerFeeRate'),
'maker': this.safeNumber(market, 'makerFeeRate'),
'contractSize': this.parseNumber(Precise.stringAbs(multiplier)),
'expiry': expiry,
'expiryDatetime': this.iso8601(expiry),
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': lotSize,
'price': tickSize,
},
'limits': {
'leverage': {
'min': this.parseNumber('1'),
'max': this.safeNumber(market, 'maxLeverage'),
},
'amount': {
'min': limitAmountMin,
'max': limitAmountMax,
},
'price': {
'min': tickSize,
'max': limitPriceMax,
},
'cost': {
'min': this.safeNumber(market, 'quoteMinSize'),
'max': this.safeNumber(market, 'quoteMaxSize'),
},
},
'created': this.safeInteger(market, 'firstOpenDate'),
'info': market,
});
}
return result;
}
/**
* @method
* @name kucoinfutures#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-server-time
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
async fetchTime(params = {}) {
const response = await this.futuresPublicGetTimestamp(params);
//
// {
// "code": "200000",
// "data": 1637385119302,
// }
//
return this.safeInteger(response, 'data');
}
/**
* @method
* @name kucoinfutures#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-klines
* @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
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @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();
let paginate = false;
[paginate, params] = this.handleOptionAndParams(params, 'fetchOHLCV', 'paginate');
if (paginate) {
return await this.fetchPaginatedCallDeterministic('fetchOHLCV', symbol, since, limit, timeframe, params, 200);
}
const market = this.market(symbol);
const marketId = market['id'];
const parsedTimeframe = this.safeInteger(this.timeframes, timeframe);
const request = {
'symbol': marketId,
};
if (parsedTimeframe !== undefined) {
request['granularity'] = parsedTimeframe;
}
else {
request['granularity'] = timeframe;
}
const duration = this.parseTimeframe(timeframe) * 1000;
let endAt = this.milliseconds();
if (since !== undefined) {
request['from'] = since;
if (limit === undefined) {
limit = this.safeInteger(this.options, 'fetchOHLCVLimit', 200);
}
endAt = this.sum(since, limit * duration);
}
else if (limit !== undefined) {
since = endAt - limit * duration;
request['from'] = since;
}
request['to'] = endAt;
const response = await this.futuresPublicGetKlineQuery(this.extend(request, params));
//
// {
// "code": "200000",
// "data": [
// [1636459200000, 4779.3, 4792.1, 4768.7, 4770.3, 78051],
// [1636460100000, 4770.25, 4778.55, 4757.55, 4777.25, 80164],
// [1636461000000, 4777.25, 4791.45, 4774.5, 4791.3, 51555]
// ]
// }
//
const data = this.safeList(response, 'data', []);
return this.parseOHLCVs(data, market, timeframe, since, limit);
}
parseOHLCV(ohlcv, market = undefined) {
//
// [
// "1545904980000", // Start time of the candle cycle
// "0.058", // opening price
// "0.049", // closing price
// "0.058", // highest price
// "0.049", // lowest price
// "0.018", // base volume
// "0.000945", // quote volume
// ]
//
return [
this.safeInteger(ohlcv, 0),
this.safeNumber(ohlcv, 1),
this.safeNumber(ohlcv, 2),
this.safeNumber(ohlcv, 3),
this.safeNumber(ohlcv, 4),
this.safeNumber(ohlcv, 5),
];
}
/**
* @method
* @name kucoinfutures#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-address
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/#/?id=address-structure}
*/
async fetchDepositAddress(code, params = {}) {
await this.loadMarkets();
const currency = this.currency(code);
const currencyId = currency['id'];
const request = {
'currency': currencyId, // Currency,including XBT,USDT
};
const response = await this.futuresPrivateGetDepositAddress(this.extend(request, params));
//
// {
// "code": "200000",
// "data": {
// "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",//Deposit address
// "memo": null//Address tag. If the returned value is null, it means that the requested token has no memo. If you are to transfer funds from another platform to KuCoin Futures and if the token to be //transferred has memo(tag), you need to fill in the memo to ensure the transferred funds will be sent //to the address you specified.
// }
// }
//
const data = this.safeValue(response, 'data', {});
const address = this.safeString(data, 'address');
if (currencyId !== 'NIM') {
// contains spaces
this.checkAddress(address);
}
return {
'info': response,
'currency': currencyId,
'network': this.safeString(data, 'chain'),
'address': address,
'tag': this.safeString(data, 'memo'),
};
}
/**
* @method
* @name kucoinfutures#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-part-order-book-level-2
* @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 level = this.safeNumber(params, 'level');
if (level !== 2 && level !== undefined) {
throw new BadRequest(this.id + ' fetchOrderBook() can only return level 2');
}
const market = this.market(symbol);
const request = {
'symbol': market['id'],
};
if (limit !== undefined) {
if ((limit === 20) || (limit === 100)) {
request['limit'] = limit;
}
else {
throw new BadRequest(this.id + ' fetchOrderBook() limit argument must be 20 or 100');
}
}
else {
request['limit'] = 20;
}
const response = await this.futuresPublicGetLevel2DepthLimit(this.extend(request, params));
//
// {
// "code": "200000",
// "data": {
// "symbol": "XBTUSDM", //Symbol
// "sequence": 100, //Ticker sequence number
// "asks": [
// ["5000.0", 1000], //Price, quantity
// ["6000.0", 1983] //Price, quantity
// ],
// "bids": [
// ["3200.0", 800], //Price, quantity
// ["3100.0", 100] //Price, quantity
// ],
// "ts": 1604643655040584408 // timestamp
// }
// }
//
const data = this.safeValue(response, 'data', {});
const timestamp = this.parseToInt(this.safeInteger(data, 'ts') / 1000000);
const orderbook = this.parseOrderBook(data, market['symbol'], timestamp, 'bids', 'asks', 0, 1);
orderbook['nonce'] = this.safeInteger(data, 'sequence');
return orderbook;
}
/**
* @method
* @name kucoinfutures#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-ticker
* @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 = {
'symbol': market['id'],
};
const response = await this.futuresPublicGetTicker(this.extend(request, params));
//
// {
// "code": "200000",
// "data": {
// "sequence": 1638444978558,
// "symbol": "ETHUSDTM",
// "side": "sell",
// "size": 4,
// "price": "4229.35",
// "bestBidSize": 2160,
// "bestBidPrice": "4229.0",
// "bestAskPrice": "4229.05",
// "tradeId": "61aaa8b777a0c43055fe4851",
// "ts": 1638574296209786785,
// "bestAskSize": 36,
// }
// }
//
return this.parseTicker(response['data'], market);
}
/**
* @method
* @name kucoinfutures#fetchMarkPrice
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-current-mark-price
* @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 fetchMarkPrice(symbol, params = {}) {
await this.loadMarkets();
const market = this.market(symbol);
const request = {
'symbol': market['id'],
};
const response = await this.futuresPublicGetMarkPriceSymbolCurrent(this.extend(request, params));
//
return this.parseTicker(response['data'], market);
}
/**
* @method
* @name kucoinfutures#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list
* @param {string[]} [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
* @param {string} [params.method] the method to use, futuresPublicGetAllTickers or futuresPublicGetContractsActive
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
async fetchTickers(symbols = undefined, params = {}) {
await this.loadMarkets();
symbols = this.marketSymbols(symbols);
let method = undefined;
[method, params] = this.handleOptionAndParams(params, 'fetchTickers', 'method', 'futuresPublicGetContractsActive');
let response = undefined;
if (method === 'futuresPublicGetAllTickers') {
response = await this.futuresPublicGetAllTickers(params);
}
else {
response = await this.futuresPublicGetContractsActive(params);
}
//
// {
// "code": "200000",
// "data": {
// "symbol": "ETHUSDTM",
// "rootSymbol": "USDT",
// "type": "FFWCSX",
// "firstOpenDate": 1591086000000,
// "expireDate": null,
// "settleDate": null,
// "baseCurrency": "ETH",
// "quoteCurrency": "USDT",
// "settleCurrency": "USDT",
// "maxOrderQty": 1000000,
// "maxPrice": 1000000.0000000000,
// "lotSize": 1,
// "tickSize": 0.05,
// "indexPriceTickSize": 0.01,
// "multiplier": 0.01,
// "initialMargin": 0.01,
// "maintainMargin": 0.005,
// "maxRiskLimit": 1000000,
// "minRiskLimit": 1000000,
// "riskStep": 500000,
// "makerFeeRate": 0.00020,
// "takerFeeRate": 0.00060,
// "takerFixFee": 0.0000000000,
// "makerFixFee": 0.0000000000,
// "settlementFee": null,
// "isDeleverage": true,
// "isQuanto": true,
// "isInverse": false,
// "markMethod": "FairPrice",
// "fairMethod": "FundingRate",
// "fundingBaseSymbol": ".ETHINT8H",
// "fundingQuoteSymbol": ".USDTINT8H",
// "fundingRateSymbol": ".ETHUSDTMFPI8H",
// "indexSymbol": ".KETHUSDT",
// "settlementSymbol": "",
// "status": "Open",
// "fundingFeeRate": 0.000535,
// "predictedFundingFeeRate": 0.002197,
// "openInterest": "8724443",
// "turnoverOf24h": 341156641.03354263,
// "volumeOf24h": 74833.54000000,
// "markPrice": 4534.07,
// "indexPrice":4531.92,
// "lastTradePrice": 4545.4500000000,
// "nextFundingRateTime": 25481884,
// "maxLeverage": 100,
// "sourceExchanges": [ "huobi", "Okex", "Binance", "Kucoin", "Poloniex", "Hitbtc" ],
// "premiumsSymbol1M": ".ETHUSDTMPI",
// "premiumsSymbol8H": ".ETHUSDTMPI8H",
// "fundingBaseSymbol1M": ".ETHINT",
// "fundingQuoteSymbol1M": ".USDTINT",
// "lowPrice": 4456.90,
// "highPrice": 4674.25,
// "priceChgPct": 0.0046,
// "priceChg": 21.15
// }
// }
//
const data = this.safeList(response, 'data');
const tickers = this.parseTickers(data, symbols);
return this.filterByArrayTickers(tickers, 'symbol', symbols);
}
parseTicker(ticker, market = undefined) {
//
// {
// "symbol": "LTCUSDTM",
// "granularity": 1000,
// "timePoint": 1727967339000,
// "value": 62.37, mark price
// "indexPrice": 62.37
// }
//
// {
// "code": "200000",
// "data": {
// "sequence": 1629930362547,
// "symbol": "ETHUSDTM",
// "side": "buy",
// "size": 130,
// "price": "4724.7",
// "bestBidSize": 5,
// "bestBidPrice": "4724.6",
// "bestAskPrice": "4724.65",
// "tradeId": "618d2a5a77a0c4431d2335f4",
// "ts": 1636641371963227600,
// "bestAskSize": 1789
// }
// }
//
// from fetchTickers
//
// {
// symbol: "XBTUSDTM",
// rootSymbol: "USDT",
// type: "FFWCSX",
// firstOpenDate: 1585555200000,
// expireDate: null,
// settleDate: null,
// baseCurrency: "XBT",
// quoteCurrency: "USDT",
// settleCurrency: "USDT",
// maxOrderQty: 1000000,
// maxPrice: 1000000,
// lotSize: 1,
// tickSize: 0.1,
// indexPriceTickSize: 0.01,
// multiplier: 0.001,
// initialMargin: 0.008,
// maintainMargin: 0.004,
// maxRiskLimit: 100000,
// minRiskLimit: 100000,
// riskStep: 50000,
// makerFeeRate: 0.0002,
// takerFeeRate: 0.0006,
// takerFixFee: 0,
// makerFixFee: 0,
// settlementFee: null,
// isDeleverage: true,
// isQuanto: true,
// isInverse: false,
// markMethod: "FairPrice",
// fairMethod: "FundingRate",
// fundingBaseSymbol: ".XBTINT8H",
// fundingQuoteSymbol: ".USDTINT8H",
// fundingRateSymbol: ".XBTUSDTMFPI8H",
// indexSymbol: ".KXBTUSDT",
// settlementSymbol: "",
// status: "Open",
// fundingFeeRate: 0.000297,
// predictedFundingFeeRate: 0.000327,
// fundingRateGranularity: 28800000,
// openInterest: "8033200",
// turnoverOf24h: 659795309.2524643,
// volumeOf24h: 9998.54,
// markPrice: 67193.51,
// indexPrice: 67184.81,
// lastTradePrice: 67191.8,
// nextFundingRateTime: 20022985,
// maxLeverage: 125,
// premiumsSymbol1M: ".XBTUSDTMPI",
// premiumsSymbol8H: ".XBTUSDTMPI8H",
// fundingBaseSymbol1M: ".XBTINT",
// fundingQuoteSymbol1M: ".USDTINT",
// lowPrice: 64041.6,
// highPrice: 67737.3,
// priceChgPct: 0.0447,
// priceChg: 2878.7
// }
//
const marketId = this.safeString(ticker, 'symbol');
market = this.safeMarket(marketId, market, '-');
const last = this.safeString2(ticker, 'price', 'lastTradePrice');
const timestamp = this.safeIntegerProduct(ticker, 'ts', 0.000001);
return this.safeTicker({
'symbol': market['symbol'],
'timestamp': timestamp,
'datetime': this.iso8601(timestamp),
'high': this.safeString(ticker, 'highPrice'),
'low': this.safeString(ticker, 'lowPrice'),
'bid': this.safeString(ticker, 'bestBidPrice'),
'bidVolume': this.safeString(ticker, 'bestBidSize'),
'ask': this.safeString(ticker, 'bestAskPrice'),
'askVolume': this.safeString(ticker, 'bestAskSize'),
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': this.safeString(ticker, 'priceChg'),
'percentage': this.safeString(ticker, 'priceChgPct'),
'average': undefined,
'baseVolume': this.safeString(ticker, 'volumeOf24h'),
'quoteVolume': this.safeString(ticker, 'turnoverOf24h'),
'markPrice': this.safeString2(ticker, 'markPrice', 'value'),
'indexPrice': this.safeString(ticker, 'indexPrice'),
'info': ticker,
}, market);
}
/**
* @method
* @name kucoinfutures#fetchBidsAsks
* @description fetches the bid and ask price and volume for multiple markets
* @param {string[]} [symbols] unified symbols of the markets to fetch the bids and asks for, all markets 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 fetchBidsAsks(symbols = undefined, params = {}) {
const request = {
'method': 'futuresPublicGetAllTickers',
};
return await this.fetchTickers(symbols, this.extend(request, params));
}
/**
* @method
* @name kucoinfutures#fetchFundingHistory
* @description fetch the history of funding payments paid and received on this account
* @see https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-funding-history
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch funding history for
* @param {int} [limit] the maximum number of funding history structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding history structure]{@link https://docs.ccxt.com/#/?id=funding-history-structure}
*/
async fetchFundingHistory(symbol = undefined, since = undefined, limit = undefined, params = {}) {