UNPKG

ccxt

Version:

A JavaScript / TypeScript / Python / C# / PHP cryptocurrency trading library with support for 100+ exchanges

1,096 lines (1,094 loc) • 111 kB
// ---------------------------------------------------------------------------- // 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 okxRest from '../okx.js'; import { ArgumentsRequired, BadRequest, ExchangeError, ChecksumError, AuthenticationError, InvalidNonce } from '../base/errors.js'; import { ArrayCache, ArrayCacheByTimestamp, ArrayCacheBySymbolById, ArrayCacheBySymbolBySide } from '../base/ws/Cache.js'; import { sha256 } from '../static_dependencies/noble-hashes/sha256.js'; // --------------------------------------------------------------------------- export default class okx extends okxRest { describe() { return this.deepExtend(super.describe(), { 'has': { 'ws': true, 'watchTicker': true, 'watchMarkPrice': true, 'watchMarkPrices': true, 'watchTickers': true, 'watchBidsAsks': true, 'watchOrderBook': true, 'watchTrades': true, 'watchTradesForSymbols': true, 'watchOrderBookForSymbols': true, 'watchBalance': true, 'watchLiquidations': 'emulated', 'watchLiquidationsForSymbols': true, 'watchMyLiquidations': 'emulated', 'watchMyLiquidationsForSymbols': true, 'watchOHLCV': true, 'watchOHLCVForSymbols': true, 'watchOrders': true, 'watchMyTrades': true, 'watchPositions': true, 'watchFundingRate': true, 'watchFundingRates': true, 'createOrderWs': true, 'editOrderWs': true, 'cancelOrderWs': true, 'cancelOrdersWs': true, 'cancelAllOrdersWs': true, }, 'urls': { 'api': { 'ws': 'wss://ws.okx.com:8443/ws/v5', }, 'test': { 'ws': 'wss://wspap.okx.com:8443/ws/v5', }, }, 'options': { 'watchOrderBook': { 'checksum': true, // // bbo-tbt // 1. Newly added channel that sends tick-by-tick Level 1 data // 2. All API users can subscribe // 3. Public depth channel, verification not required // // books-l2-tbt // 1. Only users who're VIP5 and above can subscribe // 2. Identity verification required before subscription // // books50-l2-tbt // 1. Only users who're VIP4 and above can subscribe // 2. Identity verification required before subscription // // books // 1. All API users can subscribe // 2. Public depth channel, verification not required // // books5 // 1. All API users can subscribe // 2. Public depth channel, verification not required // 3. Data feeds will be delivered every 100ms (vs. every 200ms now) // 'depth': 'books', }, 'watchBalance': 'spot', 'watchTicker': { 'channel': 'tickers', // tickers, sprd-tickers, index-tickers, block-tickers }, 'watchTickers': { 'channel': 'tickers', // tickers, sprd-tickers, index-tickers, block-tickers }, 'watchOrders': { 'type': 'ANY', // SPOT, MARGIN, SWAP, FUTURES, OPTION, ANY }, 'watchMyTrades': { 'type': 'ANY', // SPOT, MARGIN, SWAP, FUTURES, OPTION, ANY }, 'createOrderWs': { 'op': 'batch-orders', // order, batch-orders }, 'editOrderWs': { 'op': 'amend-order', // amend-order, batch-amend-orders }, 'ws': { // 'inflate': true, }, }, 'streaming': { // okex does not support built-in ws protocol-level ping-pong // instead it requires a custom text-based ping-pong 'ping': this.ping, 'keepAlive': 18000, }, }); } getUrl(channel, access = 'public') { // for context: https://www.okx.com/help-center/changes-to-v5-api-websocket-subscription-parameter-and-url const isSandbox = this.options['sandboxMode']; const sandboxSuffix = isSandbox ? '?brokerId=9999' : ''; const isBusiness = (access === 'business'); const isPublic = (access === 'public'); const url = this.urls['api']['ws']; if (isBusiness || (channel.indexOf('candle') > -1) || (channel === 'orders-algo')) { return url + '/business' + sandboxSuffix; } else if (isPublic) { return url + '/public' + sandboxSuffix; } return url + '/private' + sandboxSuffix; } async subscribeMultiple(access, channel, symbols = undefined, params = {}) { await this.loadMarkets(); if (symbols === undefined) { symbols = this.symbols; } symbols = this.marketSymbols(symbols); const url = this.getUrl(channel, access); const messageHashes = []; const args = []; for (let i = 0; i < symbols.length; i++) { const marketId = this.marketId(symbols[i]); const arg = { 'channel': channel, 'instId': marketId, }; args.push(this.extend(arg, params)); messageHashes.push(channel + '::' + symbols[i]); } const request = { 'op': 'subscribe', 'args': args, }; return await this.watchMultiple(url, messageHashes, request, messageHashes); } async subscribe(access, messageHash, channel, symbol, params = {}) { await this.loadMarkets(); const url = this.getUrl(channel, access); const firstArgument = { 'channel': channel, }; if (symbol !== undefined) { const market = this.market(symbol); messageHash += ':' + market['id']; firstArgument['instId'] = market['id']; } const request = { 'op': 'subscribe', 'args': [ this.deepExtend(firstArgument, params), ], }; return await this.watch(url, messageHash, request, messageHash); } /** * @method * @name okx#watchTrades * @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} [since] timestamp in ms of the earliest trade to fetch * @param {int} [limit] the maximum amount of trades to fetch * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades} */ async watchTrades(symbol, since = undefined, limit = undefined, params = {}) { return await this.watchTradesForSymbols([symbol], since, limit, params); } /** * @method * @name okx#watchTradesForSymbols * @description get the list of most recent trades for a particular symbol * @param {string} symbols * @param {int} [since] timestamp in ms of the earliest trade to fetch * @param {int} [limit] the maximum amount of trades to fetch * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades} */ async watchTradesForSymbols(symbols, since = undefined, limit = undefined, params = {}) { const symbolsLength = symbols.length; if (symbolsLength === 0) { throw new ArgumentsRequired(this.id + ' watchTradesForSymbols() requires a non-empty array of symbols'); } await this.loadMarkets(); symbols = this.marketSymbols(symbols); const channel = 'trades'; const topics = []; const messageHashes = []; for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; messageHashes.push(channel + ':' + symbol); const marketId = this.marketId(symbol); const topic = { 'channel': channel, 'instId': marketId, }; topics.push(topic); } const request = { 'op': 'subscribe', 'args': topics, }; const url = this.getUrl(channel, 'public'); const trades = await this.watchMultiple(url, messageHashes, request, messageHashes); if (this.newUpdates) { const first = this.safeValue(trades, 0); const tradeSymbol = this.safeString(first, 'symbol'); limit = trades.getLimit(tradeSymbol, limit); } return this.filterBySinceLimit(trades, since, limit, 'timestamp', true); } /** * @method * @name okx#unWatchTradesForSymbols * @description unWatches from the stream channel * @param {string[]} symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades} */ async unWatchTradesForSymbols(symbols, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols, undefined, false); const channel = 'trades'; const topics = []; const messageHashes = []; for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; messageHashes.push('unsubscribe:trades:' + symbol); const marketId = this.marketId(symbol); const topic = { 'channel': channel, 'instId': marketId, }; topics.push(topic); } const request = { 'op': 'unsubscribe', 'args': topics, }; const url = this.getUrl(channel, 'public'); return await this.watchMultiple(url, messageHashes, request, messageHashes); } /** * @method * @name okx#unWatchTrades * @description unWatches from the stream channel * @param {string} symbol unified symbol of the market to fetch trades for * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades} */ async unWatchTrades(symbol, params = {}) { return await this.unWatchTradesForSymbols([symbol], params); } handleTrades(client, message) { // // { // "arg": { channel: "trades", instId: "BTC-USDT" }, // "data": [ // { // "instId": "BTC-USDT", // "tradeId": "216970876", // "px": "31684.5", // "sz": "0.00001186", // "side": "buy", // "ts": "1626531038288" // } // ] // } // const arg = this.safeValue(message, 'arg', {}); const channel = this.safeString(arg, 'channel'); const marketId = this.safeString(arg, 'instId'); const symbol = this.safeSymbol(marketId); const data = this.safeValue(message, 'data', []); const tradesLimit = this.safeInteger(this.options, 'tradesLimit', 1000); for (let i = 0; i < data.length; i++) { const trade = this.parseTrade(data[i]); const messageHash = channel + ':' + symbol; let stored = this.safeValue(this.trades, symbol); if (stored === undefined) { stored = new ArrayCache(tradesLimit); this.trades[symbol] = stored; } stored.append(trade); client.resolve(stored, messageHash); } } /** * @method * @name okx#watchFundingRate * @description watch the current funding rate * @see https://www.okx.com/docs-v5/en/#public-data-websocket-funding-rate-channel * @param {string} symbol unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/#/?id=funding-rate-structure} */ async watchFundingRate(symbol, params = {}) { symbol = this.symbol(symbol); const fr = await this.watchFundingRates([symbol], params); return fr[symbol]; } /** * @method * @name coinbaseinternational#watchFundingRates * @description watch the funding rate for multiple markets * @see https://www.okx.com/docs-v5/en/#public-data-websocket-funding-rate-channel * @param {string[]} symbols list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a dictionary of [funding rates structures]{@link https://docs.ccxt.com/#/?id=funding-rates-structure}, indexe by market symbols */ async watchFundingRates(symbols, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols); const channel = 'funding-rate'; const topics = []; const messageHashes = []; for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; messageHashes.push(channel + ':' + symbol); const marketId = this.marketId(symbol); const topic = { 'channel': channel, 'instId': marketId, }; topics.push(topic); } const request = { 'op': 'subscribe', 'args': topics, }; const url = this.getUrl(channel, 'public'); const fundingRate = await this.watchMultiple(url, messageHashes, request, messageHashes); if (this.newUpdates) { const symbol = this.safeString(fundingRate, 'symbol'); const result = {}; result[symbol] = fundingRate; return result; } return this.filterByArray(this.fundingRates, 'symbol', symbols); } handleFundingRate(client, message) { // // "data":[ // { // "fundingRate":"0.0001875391284828", // "fundingTime":"1700726400000", // "instId":"BTC-USD-SWAP", // "instType":"SWAP", // "method": "next_period", // "maxFundingRate":"0.00375", // "minFundingRate":"-0.00375", // "nextFundingRate":"0.0002608059239328", // "nextFundingTime":"1700755200000", // "premium": "0.0001233824646391", // "settFundingRate":"0.0001699799259033", // "settState":"settled", // "ts":"1700724675402" // } // ] // const data = this.safeList(message, 'data', []); for (let i = 0; i < data.length; i++) { const rawfr = data[i]; const fundingRate = this.parseFundingRate(rawfr); const symbol = fundingRate['symbol']; this.fundingRates[symbol] = fundingRate; client.resolve(fundingRate, 'funding-rate' + ':' + fundingRate['symbol']); } } /** * @method * @name okx#watchTicker * @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel * @description watches 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 exchange API endpoint * @param {string} [params.channel] the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ async watchTicker(symbol, params = {}) { let channel = undefined; [channel, params] = this.handleOptionAndParams(params, 'watchTicker', 'channel', 'tickers'); params['channel'] = channel; const market = this.market(symbol); symbol = market['symbol']; const ticker = await this.watchTickers([symbol], params); return this.safeValue(ticker, symbol); } /** * @method * @name okx#unWatchTicker * @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel * @description unWatches 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 exchange API endpoint * @param {string} [params.channel] the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ async unWatchTicker(symbol, params = {}) { return await this.unWatchTickers([symbol], params); } /** * @method * @name okx#watchTickers * @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel * @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list * @param {string[]} [symbols] unified symbol of the market to fetch the ticker for * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.channel] the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ async watchTickers(symbols = undefined, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols, undefined, false); let channel = undefined; [channel, params] = this.handleOptionAndParams(params, 'watchTickers', 'channel', 'tickers'); const newTickers = await this.subscribeMultiple('public', channel, symbols, params); if (this.newUpdates) { return newTickers; } return this.filterByArray(this.tickers, 'symbol', symbols); } /** * @method * @name okx#watchMarkPrice * @see https://www.okx.com/docs-v5/en/#public-data-websocket-mark-price-channel * @description watches a 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 * @param {string} [params.channel] the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ async watchMarkPrice(symbol, params = {}) { let channel = undefined; [channel, params] = this.handleOptionAndParams(params, 'watchMarkPrice', 'channel', 'mark-price'); params['channel'] = channel; const market = this.market(symbol); symbol = market['symbol']; const ticker = await this.watchMarkPrices([symbol], params); return ticker[symbol]; } /** * @method * @name okx#watchMarkPrices * @see https://www.okx.com/docs-v5/en/#public-data-websocket-mark-price-channel * @description watches mark prices * @param {string[]} [symbols] unified symbol of the market to fetch the ticker for * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.channel] the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ async watchMarkPrices(symbols = undefined, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols, undefined, false); let channel = undefined; [channel, params] = this.handleOptionAndParams(params, 'watchMarkPrices', 'channel', 'mark-price'); const newTickers = await this.subscribeMultiple('public', channel, symbols, params); if (this.newUpdates) { return newTickers; } return this.filterByArray(this.tickers, 'symbol', symbols); } /** * @method * @name okx#unWatchTickers * @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel * @description unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list * @param {string[]} [symbols] unified symbol of the market to fetch the ticker for * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.channel] the channel to subscribe to, tickers by default. Can be tickers, sprd-tickers, index-tickers, block-tickers * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ async unWatchTickers(symbols = undefined, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols, undefined, false); let channel = undefined; [channel, params] = this.handleOptionAndParams(params, 'watchTickers', 'channel', 'tickers'); const topics = []; const messageHashes = []; for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; messageHashes.push('unsubscribe:ticker:' + symbol); const marketId = this.marketId(symbol); const topic = { 'channel': channel, 'instId': marketId, }; topics.push(topic); } const request = { 'op': 'unsubscribe', 'args': topics, }; const url = this.getUrl(channel, 'public'); return await this.watchMultiple(url, messageHashes, request, messageHashes); } handleTicker(client, message) { // // { // "arg": { channel: "tickers", instId: "BTC-USDT" }, // "data": [ // { // "instType": "SPOT", // "instId": "BTC-USDT", // "last": "31500.1", // "lastSz": "0.00001754", // "askPx": "31500.1", // "askSz": "0.00998144", // "bidPx": "31500", // "bidSz": "3.05652439", // "open24h": "31697", // "high24h": "32248", // "low24h": "31165.6", // "sodUtc0": "31385.5", // "sodUtc8": "32134.9", // "volCcy24h": "503403597.38138519", // "vol24h": "15937.10781721", // "ts": "1626526618762" // } // ] // } // this.handleBidAsk(client, message); const arg = this.safeValue(message, 'arg', {}); const marketId = this.safeString(arg, 'instId'); const market = this.safeMarket(marketId, undefined, '-'); const symbol = market['symbol']; const channel = this.safeString(arg, 'channel'); const data = this.safeValue(message, 'data', []); const newTickers = {}; for (let i = 0; i < data.length; i++) { const ticker = this.parseTicker(data[i]); this.tickers[symbol] = ticker; newTickers[symbol] = ticker; } const messageHash = channel + '::' + symbol; client.resolve(newTickers, messageHash); } /** * @method * @name okx#watchBidsAsks * @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel * @description watches best bid & ask for symbols * @param {string[]} symbols 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 watchBidsAsks(symbols = undefined, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols, undefined, false); let channel = undefined; [channel, params] = this.handleOptionAndParams(params, 'watchBidsAsks', 'channel', 'tickers'); const url = this.getUrl(channel, 'public'); const messageHashes = []; const args = []; for (let i = 0; i < symbols.length; i++) { const marketId = this.marketId(symbols[i]); const arg = { 'channel': channel, 'instId': marketId, }; args.push(this.extend(arg, params)); messageHashes.push('bidask::' + symbols[i]); } const request = { 'op': 'subscribe', 'args': args, }; const newTickers = await this.watchMultiple(url, messageHashes, request, messageHashes); if (this.newUpdates) { const tickers = {}; tickers[newTickers['symbol']] = newTickers; return tickers; } return this.filterByArray(this.bidsasks, 'symbol', symbols); } handleBidAsk(client, message) { // // { // "arg": { channel: "tickers", instId: "BTC-USDT" }, // "data": [ // { // "instType": "SPOT", // "instId": "BTC-USDT", // "last": "31500.1", // "lastSz": "0.00001754", // "askPx": "31500.1", // "askSz": "0.00998144", // "bidPx": "31500", // "bidSz": "3.05652439", // "open24h": "31697", // "high24h": "32248", // "low24h": "31165.6", // "sodUtc0": "31385.5", // "sodUtc8": "32134.9", // "volCcy24h": "503403597.38138519", // "vol24h": "15937.10781721", // "ts": "1626526618762" // } // ] // } // const data = this.safeList(message, 'data', []); const ticker = this.safeDict(data, 0, {}); const parsedTicker = this.parseWsBidAsk(ticker); const symbol = parsedTicker['symbol']; this.bidsasks[symbol] = parsedTicker; const messageHash = 'bidask::' + symbol; client.resolve(parsedTicker, messageHash); } parseWsBidAsk(ticker, market = undefined) { const marketId = this.safeString(ticker, 'instId'); market = this.safeMarket(marketId, market); const symbol = this.safeString(market, 'symbol'); const timestamp = this.safeInteger(ticker, 'ts'); return this.safeTicker({ 'symbol': symbol, 'timestamp': timestamp, 'datetime': this.iso8601(timestamp), 'ask': this.safeString(ticker, 'askPx'), 'askVolume': this.safeString(ticker, 'askSz'), 'bid': this.safeString(ticker, 'bidPx'), 'bidVolume': this.safeString(ticker, 'bidSz'), 'info': ticker, }, market); } /** * @method * @name okx#watchLiquidationsForSymbols * @description watch the public liquidations of a trading pair * @see https://www.okx.com/docs-v5/en/#public-data-websocket-liquidation-orders-channel * @param {string} symbols * @param {int} [since] the earliest time in ms to fetch liquidations for * @param {int} [limit] the maximum number of liquidation structures to retrieve * @param {object} [params] exchange specific parameters for the okx api endpoint * @returns {object} an array of [liquidation structures]{@link https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure} */ async watchLiquidationsForSymbols(symbols = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols, undefined, true, true); const messageHash = 'liquidations'; const messageHashes = []; if (symbols !== undefined) { for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; messageHashes.push(messageHash + '::' + symbol); } } else { messageHashes.push(messageHash); } const market = this.getMarketFromSymbols(symbols); let type = undefined; [type, params] = this.handleMarketTypeAndParams('watchliquidationsForSymbols', market, params); const channel = 'liquidation-orders'; if (type === 'spot') { type = 'SWAP'; } else if (type === 'future') { type = 'futures'; } const uppercaseType = type.toUpperCase(); const request = { 'op': 'subscribe', 'args': [ { 'channel': channel, 'instType': uppercaseType, }, ], }; const url = this.getUrl(channel, 'public'); const newLiquidations = await this.watchMultiple(url, messageHashes, request, messageHashes); if (this.newUpdates) { return newLiquidations; } return this.filterBySymbolsSinceLimit(this.liquidations, symbols, since, limit, true); } handleLiquidation(client, message) { // // { // "arg": { // "channel": "liquidation-orders", // "instType": "SWAP" // }, // "data": [ // { // "details": [ // { // "bkLoss": "0", // "bkPx": "0.007831", // "ccy": "", // "posSide": "short", // "side": "buy", // "sz": "13", // "ts": "1692266434010" // } // ], // "instFamily": "IOST-USDT", // "instId": "IOST-USDT-SWAP", // "instType": "SWAP", // "uly": "IOST-USDT" // } // ] // } // const rawLiquidations = this.safeList(message, 'data', []); for (let i = 0; i < rawLiquidations.length; i++) { const rawLiquidation = rawLiquidations[i]; const liquidation = this.parseWsLiquidation(rawLiquidation); const symbol = this.safeString(liquidation, 'symbol'); let liquidations = this.safeValue(this.liquidations, symbol); if (liquidations === undefined) { const limit = this.safeInteger(this.options, 'liquidationsLimit', 1000); liquidations = new ArrayCache(limit); } liquidations.append(liquidation); this.liquidations[symbol] = liquidations; client.resolve([liquidation], 'liquidations'); client.resolve([liquidation], 'liquidations::' + symbol); } } /** * @method * @name okx#watchMyLiquidationsForSymbols * @description watch the private liquidations of a trading pair * @see https://www.okx.com/docs-v5/en/#trading-account-websocket-balance-and-position-channel * @param {string[]} symbols * @param {int} [since] the earliest time in ms to fetch liquidations for * @param {int} [limit] the maximum number of liquidation structures to retrieve * @param {object} [params] exchange specific parameters for the okx api endpoint * @returns {object} an array of [liquidation structures]{@link https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure} */ async watchMyLiquidationsForSymbols(symbols = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets(); const isTrigger = this.safeValue2(params, 'stop', 'trigger', false); params = this.omit(params, ['stop', 'trigger']); await this.authenticate({ 'access': isTrigger ? 'business' : 'private' }); symbols = this.marketSymbols(symbols, undefined, true, true); const messageHash = 'myLiquidations'; const messageHashes = []; if (symbols !== undefined) { for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; messageHashes.push(messageHash + '::' + symbol); } } else { messageHashes.push(messageHash); } const channel = 'balance_and_position'; const request = { 'op': 'subscribe', 'args': [ { 'channel': channel, }, ], }; const url = this.getUrl(channel, 'private'); const newLiquidations = await this.watchMultiple(url, messageHashes, this.deepExtend(request, params), messageHashes); if (this.newUpdates) { return newLiquidations; } return this.filterBySymbolsSinceLimit(this.liquidations, symbols, since, limit, true); } handleMyLiquidation(client, message) { // // { // "arg": { // "channel": "balance_and_position", // "uid": "77982378738415879" // }, // "data": [{ // "pTime": "1597026383085", // "eventType": "snapshot", // "balData": [{ // "ccy": "BTC", // "cashBal": "1", // "uTime": "1597026383085" // }], // "posData": [{ // "posId": "1111111111", // "tradeId": "2", // "instId": "BTC-USD-191018", // "instType": "FUTURES", // "mgnMode": "cross", // "posSide": "long", // "pos": "10", // "ccy": "BTC", // "posCcy": "", // "avgPx": "3320", // "uTIme": "1597026383085" // }], // "trades": [{ // "instId": "BTC-USD-191018", // "tradeId": "2", // }] // }] // } // const rawLiquidations = this.safeList(message, 'data', []); for (let i = 0; i < rawLiquidations.length; i++) { const rawLiquidation = rawLiquidations[i]; const eventType = this.safeString(rawLiquidation, 'eventType'); if (eventType !== 'liquidation') { return; } const liquidation = this.parseWsMyLiquidation(rawLiquidation); const symbol = this.safeString(liquidation, 'symbol'); let liquidations = this.safeValue(this.liquidations, symbol); if (liquidations === undefined) { const limit = this.safeInteger(this.options, 'myLiquidationsLimit', 1000); liquidations = new ArrayCache(limit); } liquidations.append(liquidation); this.liquidations[symbol] = liquidations; client.resolve([liquidation], 'myLiquidations'); client.resolve([liquidation], 'myLiquidations::' + symbol); } } parseWsMyLiquidation(liquidation, market = undefined) { // // { // "pTime": "1597026383085", // "eventType": "snapshot", // "balData": [{ // "ccy": "BTC", // "cashBal": "1", // "uTime": "1597026383085" // }], // "posData": [{ // "posId": "1111111111", // "tradeId": "2", // "instId": "BTC-USD-191018", // "instType": "FUTURES", // "mgnMode": "cross", // "posSide": "long", // "pos": "10", // "ccy": "BTC", // "posCcy": "", // "avgPx": "3320", // "uTIme": "1597026383085" // }], // "trades": [{ // "instId": "BTC-USD-191018", // "tradeId": "2", // }] // } // const posData = this.safeList(liquidation, 'posData', []); const firstPosData = this.safeDict(posData, 0, {}); const marketId = this.safeString(firstPosData, 'instId'); market = this.safeMarket(marketId, market); const timestamp = this.safeInteger(firstPosData, 'uTIme'); return this.safeLiquidation({ 'info': liquidation, 'symbol': this.safeSymbol(marketId, market), 'contracts': this.safeNumber(firstPosData, 'pos'), 'contractSize': this.safeNumber(market, 'contractSize'), 'price': this.safeNumber(liquidation, 'avgPx'), 'baseValue': undefined, 'quoteValue': undefined, 'timestamp': timestamp, 'datetime': this.iso8601(timestamp), }); } parseWsLiquidation(liquidation, market = undefined) { // // public liquidation // { // "details": [ // { // "bkLoss": "0", // "bkPx": "0.007831", // "ccy": "", // "posSide": "short", // "side": "buy", // "sz": "13", // "ts": "1692266434010" // } // ], // "instFamily": "IOST-USDT", // "instId": "IOST-USDT-SWAP", // "instType": "SWAP", // "uly": "IOST-USDT" // } // const details = this.safeList(liquidation, 'details', []); const liquidationDetails = this.safeDict(details, 0, {}); const marketId = this.safeString(liquidation, 'instId'); market = this.safeMarket(marketId, market); const timestamp = this.safeInteger(liquidationDetails, 'ts'); return this.safeLiquidation({ 'info': liquidation, 'symbol': this.safeSymbol(marketId, market), 'contracts': this.safeNumber(liquidationDetails, 'sz'), 'contractSize': this.safeNumber(market, 'contractSize'), 'price': this.safeNumber(liquidationDetails, 'bkPx'), 'baseValue': undefined, 'quoteValue': undefined, 'timestamp': timestamp, 'datetime': this.iso8601(timestamp), }); } /** * @method * @name okx#watchOHLCV * @description watches 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} [since] timestamp in ms of the earliest candle to fetch * @param {int} [limit] the maximum amount of candles to fetch * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume */ async watchOHLCV(symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) { await this.loadMarkets(); symbol = this.symbol(symbol); const interval = this.safeString(this.timeframes, timeframe, timeframe); const name = 'candle' + interval; const ohlcv = await this.subscribe('public', name, name, symbol, params); if (this.newUpdates) { limit = ohlcv.getLimit(symbol, limit); } return this.filterBySinceLimit(ohlcv, since, limit, 0, true); } /** * @method * @name okx#unWatchOHLCV * @description watches 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 {object} [params] extra parameters specific to the exchange API endpoint * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume */ async unWatchOHLCV(symbol, timeframe = '1m', params = {}) { await this.loadMarkets(); return await this.unWatchOHLCVForSymbols([[symbol, timeframe]], params); } /** * @method * @name okx#watchOHLCVForSymbols * @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market * @param {string[][]} symbolsAndTimeframes array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']] * @param {int} [since] timestamp in ms of the earliest candle to fetch * @param {int} [limit] the maximum amount of candles to fetch * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume */ async watchOHLCVForSymbols(symbolsAndTimeframes, since = undefined, limit = undefined, params = {}) { const symbolsLength = symbolsAndTimeframes.length; if (symbolsLength === 0 || !Array.isArray(symbolsAndTimeframes[0])) { throw new ArgumentsRequired(this.id + " watchOHLCVForSymbols() requires a an array of symbols and timeframes, like [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]"); } await this.loadMarkets(); const topics = []; const messageHashes = []; for (let i = 0; i < symbolsAndTimeframes.length; i++) { const symbolAndTimeframe = symbolsAndTimeframes[i]; const sym = symbolAndTimeframe[0]; const tf = symbolAndTimeframe[1]; const marketId = this.marketId(sym); const interval = this.safeString(this.timeframes, tf, tf); const channel = 'candle' + interval; const topic = { 'channel': channel, 'instId': marketId, }; topics.push(topic); messageHashes.push('multi:' + channel + ':' + sym); } const request = { 'op': 'subscribe', 'args': topics, }; const url = this.getUrl('candle', 'public'); const [symbol, timeframe, candles] = await this.watchMultiple(url, messageHashes, request, messageHashes); if (this.newUpdates) { limit = candles.getLimit(symbol, limit); } const filtered = this.filterBySinceLimit(candles, since, limit, 0, true); return this.createOHLCVObject(symbol, timeframe, filtered); } /** * @method * @name okx#unWatchOHLCVForSymbols * @description unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market * @param {string[][]} symbolsAndTimeframes array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']] * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume */ async unWatchOHLCVForSymbols(symbolsAndTimeframes, params = {}) { const symbolsLength = symbolsAndTimeframes.length; if (symbolsLength === 0 || !Array.isArray(symbolsAndTimeframes[0])) { throw new ArgumentsRequired(this.id + " watchOHLCVForSymbols() requires a an array of symbols and timeframes, like [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]"); } await this.loadMarkets(); const topics = []; const messageHashes = []; for (let i = 0; i < symbolsAndTimeframes.length; i++) { const symbolAndTimeframe = symbolsAndTimeframes[i]; const sym = symbolAndTimeframe[0]; const tf = symbolAndTimeframe[1]; const marketId = this.marketId(sym); const interval = this.safeString(this.timeframes, tf, tf); const channel = 'candle' + interval; const topic = { 'channel': channel, 'instId': marketId, }; topics.push(topic); messageHashes.push('unsubscribe:multi:' + channel + ':' + sym); } const request = { 'op': 'unsubscribe', 'args': topics, }; const url = this.getUrl('candle', 'public'); return await this.watchMultiple(url, messageHashes, request, messageHashes); } handleOHLCV(client, message) { // // { // "arg": { channel: "candle1m", instId: "BTC-USDT" }, // "data": [ // [ // "1626690720000", // "31334", // "31334", // "31334", // "31334", // "0.0077", // "241.2718" // ] // ] // } // const arg = this.safeValue(message, 'arg', {}); const channel = this.safeString(arg, 'channel'); const data = this.safeValue(message, 'data', []); const marketId = this.safeString(arg, 'instId'); const market = this.safeMarket(marketId); const symbol = market['symbol']; const interval = channel.replace('candle', ''); // use a reverse lookup in a static map instead const timeframe = this.findTimeframe(interval); for (let i = 0; i < data.length; i++) { const parsed = this.parseOHLCV(data[i], market); this.ohlcvs[symbol] = this.safeValue(this.ohlcvs, symbol, {}); let stored = this.safeValue(this.ohlcvs[symbol], timeframe); if (stored === undefined) { const limit = this.safeInteger(this.options, 'OHLCVLimit', 1000); stored = new ArrayCacheByTimestamp(limit); this.ohlcvs[symbol][timeframe] = stored; } stored.append(parsed); const messageHash = channel + ':' + market['id']; client.resolve(stored, messageHash); // for multiOHLCV we need special object, as opposed to other "multi" // methods, because OHLCV response item does not contain symbol // or timeframe, thus otherwise it would be unrecognizable const messageHashForMulti = 'multi:' + channel + ':' + symbol; client.resolve([symbol, timeframe, stored], messageHashForMulti); } } /** * @method * @name okx#watchOrderBook * @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-order-book-channel * @description watches 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} [limit] the maximum amount of order book entries to return * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.depth] okx order book depth, can be books, books5, books-l2-tbt, books50-l2-tbt, bbo-tbt * @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure} indexed by market symbols */ async watchOrderBook(symbol, limit = undefined, params = {}) { // // bbo-tbt // 1. Newly added channel that sends tick-by-tick Level 1 data // 2.