UNPKG

ccxt

Version:

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

1,110 lines (1,108 loc) • 96.1 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 bitgetRest from '../bitget.js'; import { AuthenticationError, BadRequest, ArgumentsRequired, ChecksumError, ExchangeError, RateLimitExceeded, UnsubscribeError } from '../base/errors.js'; import { Precise } from '../base/Precise.js'; import { ArrayCache, ArrayCacheBySymbolById, ArrayCacheBySymbolBySide, ArrayCacheByTimestamp } from '../base/ws/Cache.js'; import { sha256 } from '../static_dependencies/noble-hashes/sha256.js'; // --------------------------------------------------------------------------- /** * @class bitget * @augments Exchange * @description watching delivery future markets is not yet implemented (perpertual future & swap is implemented) */ export default class bitget extends bitgetRest { describe() { return this.deepExtend(super.describe(), { 'has': { 'ws': true, 'createOrderWs': false, 'editOrderWs': false, 'fetchOpenOrdersWs': false, 'fetchOrderWs': false, 'cancelOrderWs': false, 'cancelOrdersWs': false, 'cancelAllOrdersWs': false, 'watchBalance': true, 'watchMyTrades': true, 'watchOHLCV': true, 'watchOHLCVForSymbols': false, 'watchOrderBook': true, 'watchOrderBookForSymbols': true, 'watchOrders': true, 'watchTicker': true, 'watchTickers': true, 'watchBidsAsks': true, 'watchTrades': true, 'watchTradesForSymbols': true, 'watchPositions': true, }, 'urls': { 'api': { 'ws': { 'public': 'wss://ws.bitget.com/v2/ws/public', 'private': 'wss://ws.bitget.com/v2/ws/private', }, 'demo': { 'public': 'wss://wspap.bitget.com/v2/ws/public', 'private': 'wss://wspap.bitget.com/v2/ws/private', }, }, }, 'options': { 'tradesLimit': 1000, 'OHLCVLimit': 1000, // WS timeframes differ from REST timeframes 'timeframes': { '1m': '1m', '5m': '5m', '15m': '15m', '30m': '30m', '1h': '1H', '4h': '4H', '6h': '6H', '12h': '12H', '1d': '1D', '1w': '1W', }, 'watchOrderBook': { 'checksum': true, }, 'watchTrades': { 'ignoreDuplicates': true, }, }, 'streaming': { 'ping': this.ping, }, 'exceptions': { 'ws': { 'exact': { '30001': BadRequest, '30002': AuthenticationError, '30003': BadRequest, '30004': AuthenticationError, '30005': AuthenticationError, '30006': RateLimitExceeded, '30007': RateLimitExceeded, '30011': AuthenticationError, '30012': AuthenticationError, '30013': AuthenticationError, '30014': BadRequest, '30015': AuthenticationError, '30016': BadRequest, // { event: 'error', code: 30016, msg: 'Param error' } }, 'broad': {}, }, }, }); } getInstType(market, params = {}) { let instType = undefined; if (market === undefined) { [instType, params] = this.handleProductTypeAndParams(undefined, params); } else if ((market['swap']) || (market['future'])) { [instType, params] = this.handleProductTypeAndParams(market, params); } else { instType = 'SPOT'; } let instypeAux = undefined; [instypeAux, params] = this.handleOptionAndParams(params, 'getInstType', 'instType', instType); instType = instypeAux; return [instType, params]; } /** * @method * @name bitget#watchTicker * @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market * @see https://www.bitget.com/api-doc/spot/websocket/public/Tickers-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/Tickers-Channel * @param {string} symbol unified symbol of the market to watch 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 watchTicker(symbol, params = {}) { await this.loadMarkets(); const market = this.market(symbol); symbol = market['symbol']; const messageHash = 'ticker:' + symbol; let instType = undefined; [instType, params] = this.getInstType(market, params); const args = { 'instType': instType, 'channel': 'ticker', 'instId': market['id'], }; return await this.watchPublic(messageHash, args, params); } /** * @method * @name bitget#unWatchTicker * @description unsubscribe from the ticker channel * @see https://www.bitget.com/api-doc/spot/websocket/public/Tickers-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/Tickers-Channel * @param {string} symbol unified symbol of the market to unwatch the ticker for * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {any} status of the unwatch request */ async unWatchTicker(symbol, params = {}) { await this.loadMarkets(); return await this.unWatchChannel(symbol, 'ticker', 'ticker', params); } /** * @method * @name bitget#watchTickers * @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list * @see https://www.bitget.com/api-doc/spot/websocket/public/Tickers-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/Tickers-Channel * @param {string[]} symbols unified symbol of the market to watch the tickers 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 watchTickers(symbols = undefined, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols, undefined, false); const market = this.market(symbols[0]); let instType = undefined; [instType, params] = this.getInstType(market, params); const topics = []; const messageHashes = []; for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; const marketInner = this.market(symbol); const args = { 'instType': instType, 'channel': 'ticker', 'instId': marketInner['id'], }; topics.push(args); messageHashes.push('ticker:' + symbol); } const tickers = await this.watchPublicMultiple(messageHashes, topics, params); if (this.newUpdates) { const result = {}; result[tickers['symbol']] = tickers; return result; } return this.filterByArray(this.tickers, 'symbol', symbols); } handleTicker(client, message) { // // { // "action": "snapshot", // "arg": { // "instType": "SPOT", // "channel": "ticker", // "instId": "BTCUSDT" // }, // "data": [ // { // "instId": "BTCUSDT", // "lastPr": "43528.19", // "open24h": "42267.78", // "high24h": "44490.00", // "low24h": "41401.53", // "change24h": "0.03879", // "bidPr": "43528", // "askPr": "43528.01", // "bidSz": "0.0334", // "askSz": "0.1917", // "baseVolume": "15002.4216", // "quoteVolume": "648006446.7164", // "openUtc": "44071.18", // "changeUtc24h": "-0.01232", // "ts": "1701842994338" // } // ], // "ts": 1701842994341 // } // this.handleBidAsk(client, message); const ticker = this.parseWsTicker(message); const symbol = ticker['symbol']; this.tickers[symbol] = ticker; const messageHash = 'ticker:' + symbol; client.resolve(ticker, messageHash); } parseWsTicker(message, market = undefined) { // // spot // // { // "action": "snapshot", // "arg": { // "instType": "SPOT", // "channel": "ticker", // "instId": "BTCUSDT" // }, // "data": [ // { // "instId": "BTCUSDT", // "lastPr": "43528.19", // "open24h": "42267.78", // "high24h": "44490.00", // "low24h": "41401.53", // "change24h": "0.03879", // "bidPr": "43528", // "askPr": "43528.01", // "bidSz": "0.0334", // "askSz": "0.1917", // "baseVolume": "15002.4216", // "quoteVolume": "648006446.7164", // "openUtc": "44071.18", // "changeUtc24h": "-0.01232", // "ts": "1701842994338" // } // ], // "ts": 1701842994341 // } // // contract // // { // "action": "snapshot", // "arg": { // "instType": "USDT-FUTURES", // "channel": "ticker", // "instId": "BTCUSDT" // }, // "data": [ // { // "instId": "BTCUSDT", // "lastPr": "43480.4", // "bidPr": "43476.3", // "askPr": "43476.8", // "bidSz": "0.1", // "askSz": "3.055", // "open24h": "42252.3", // "high24h": "44518.2", // "low24h": "41387.0", // "change24h": "0.03875", // "fundingRate": "0.000096", // "nextFundingTime": "1701849600000", // "markPrice": "43476.4", // "indexPrice": "43478.4", // "holdingAmount": "50670.787", // "baseVolume": "120187.104", // "quoteVolume": "5167385048.693", // "openUtc": "44071.4", // "symbolType": "1", // "symbol": "BTCUSDT", // "deliveryPrice": "0", // "ts": "1701843962811" // } // ], // "ts": 1701843962812 // } // const arg = this.safeValue(message, 'arg', {}); const data = this.safeValue(message, 'data', []); const ticker = this.safeValue(data, 0, {}); const timestamp = this.safeInteger(ticker, 'ts'); const instType = this.safeString(arg, 'instType'); const marketType = (instType === 'SPOT') ? 'spot' : 'contract'; const marketId = this.safeString(ticker, 'instId'); market = this.safeMarket(marketId, market, undefined, marketType); const close = this.safeString(ticker, 'lastPr'); const changeDecimal = this.safeString(ticker, 'change24h'); const change = Precise.stringMul(changeDecimal, '100'); return this.safeTicker({ 'symbol': market['symbol'], 'timestamp': timestamp, 'datetime': this.iso8601(timestamp), 'high': this.safeString(ticker, 'high24h'), 'low': this.safeString(ticker, 'low24h'), 'bid': this.safeString(ticker, 'bidPr'), 'bidVolume': this.safeString(ticker, 'bidSz'), 'ask': this.safeString(ticker, 'askPr'), 'askVolume': this.safeString(ticker, 'askSz'), 'vwap': undefined, 'open': this.safeString(ticker, 'open24h'), 'close': close, 'last': close, 'previousClose': undefined, 'change': undefined, 'percentage': change, 'average': undefined, 'baseVolume': this.safeString(ticker, 'baseVolume'), 'quoteVolume': this.safeString(ticker, 'quoteVolume'), 'info': ticker, }, market); } /** * @method * @name bitget#watchBidsAsks * @see https://www.bitget.com/api-doc/spot/websocket/public/Tickers-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/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); const market = this.market(symbols[0]); let instType = undefined; [instType, params] = this.getInstType(market, params); const topics = []; const messageHashes = []; for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; const marketInner = this.market(symbol); const args = { 'instType': instType, 'channel': 'ticker', 'instId': marketInner['id'], }; topics.push(args); messageHashes.push('bidask:' + symbol); } const tickers = await this.watchPublicMultiple(messageHashes, topics, params); if (this.newUpdates) { const result = {}; result[tickers['symbol']] = tickers; return result; } return this.filterByArray(this.bidsasks, 'symbol', symbols); } handleBidAsk(client, message) { const ticker = this.parseWsBidAsk(message); const symbol = ticker['symbol']; this.bidsasks[symbol] = ticker; const messageHash = 'bidask:' + symbol; client.resolve(ticker, messageHash); } parseWsBidAsk(message, market = undefined) { const arg = this.safeValue(message, 'arg', {}); const data = this.safeValue(message, 'data', []); const ticker = this.safeValue(data, 0, {}); const timestamp = this.safeInteger(ticker, 'ts'); const instType = this.safeString(arg, 'instType'); const marketType = (instType === 'SPOT') ? 'spot' : 'contract'; const marketId = this.safeString(ticker, 'instId'); market = this.safeMarket(marketId, market, undefined, marketType); return this.safeTicker({ 'symbol': market['symbol'], 'timestamp': timestamp, 'datetime': this.iso8601(timestamp), 'ask': this.safeString(ticker, 'askPr'), 'askVolume': this.safeString(ticker, 'askSz'), 'bid': this.safeString(ticker, 'bidPr'), 'bidVolume': this.safeString(ticker, 'bidSz'), 'info': ticker, }, market); } /** * @method * @name bitget#watchOHLCV * @description watches historical candlestick data containing the open, high, low, close price, and the volume of a market * @see https://www.bitget.com/api-doc/spot/websocket/public/Candlesticks-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/Candlesticks-Channel * @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(); const market = this.market(symbol); symbol = market['symbol']; const timeframes = this.safeValue(this.options, 'timeframes'); const interval = this.safeString(timeframes, timeframe); const messageHash = 'candles:' + timeframe + ':' + symbol; let instType = undefined; [instType, params] = this.getInstType(market, params); const args = { 'instType': instType, 'channel': 'candle' + interval, 'instId': market['id'], }; const ohlcv = await this.watchPublic(messageHash, args, params); if (this.newUpdates) { limit = ohlcv.getLimit(symbol, limit); } return this.filterBySinceLimit(ohlcv, since, limit, 0, true); } /** * @method * @name bitget#unWatchOHLCV * @description unsubscribe from the ohlcv channel * @see https://www.bitget.com/api-doc/spot/websocket/public/Candlesticks-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/Candlesticks-Channel * @param {string} symbol unified symbol of the market to unwatch the ohlcv for * @param {string} [timeframe] the period for the ratio, default is 1 minute * @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 unWatchOHLCV(symbol, timeframe = '1m', params = {}) { await this.loadMarkets(); const timeframes = this.safeDict(this.options, 'timeframes'); const interval = this.safeString(timeframes, timeframe); const channel = 'candle' + interval; return await this.unWatchChannel(symbol, channel, 'candles:' + timeframe, params); } handleOHLCV(client, message) { // // { // "action": "snapshot", // "arg": { // "instType": "SPOT", // "channel": "candle1m", // "instId": "BTCUSDT" // }, // "data": [ // [ // "1701871620000", // "44080.23", // "44080.23", // "44028.5", // "44028.51", // "9.9287", // "437404.105512", // "437404.105512" // ], // [ // "1701871680000", // "44028.51", // "44108.11", // "44028.5", // "44108.11", // "17.139", // "755436.870643", // "755436.870643" // ], // ], // "ts": 1701901610417 // } // const arg = this.safeValue(message, 'arg', {}); const instType = this.safeString(arg, 'instType'); const marketType = (instType === 'SPOT') ? 'spot' : 'contract'; const marketId = this.safeString(arg, 'instId'); const market = this.safeMarket(marketId, undefined, undefined, marketType); const symbol = market['symbol']; this.ohlcvs[symbol] = this.safeValue(this.ohlcvs, symbol, {}); const channel = this.safeString(arg, 'channel'); const interval = channel.replace('candle', ''); const timeframes = this.safeValue(this.options, 'timeframes'); const timeframe = this.findTimeframe(interval, timeframes); 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; } const data = this.safeValue(message, 'data', []); for (let i = 0; i < data.length; i++) { const parsed = this.parseWsOHLCV(data[i], market); stored.append(parsed); } const messageHash = 'candles:' + timeframe + ':' + symbol; client.resolve(stored, messageHash); } parseWsOHLCV(ohlcv, market = undefined) { // // [ // "1701871620000", // timestamp // "44080.23", // open // "44080.23", // high // "44028.5", // low // "44028.51", // close // "9.9287", // base volume // "437404.105512", // quote volume // "437404.105512" // USDT volume // ] // const volumeIndex = (market['inverse']) ? 6 : 5; return [ this.safeInteger(ohlcv, 0), this.safeNumber(ohlcv, 1), this.safeNumber(ohlcv, 2), this.safeNumber(ohlcv, 3), this.safeNumber(ohlcv, 4), this.safeNumber(ohlcv, volumeIndex), ]; } /** * @method * @name bitget#watchOrderBook * @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data * @see https://www.bitget.com/api-doc/spot/websocket/public/Depth-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/Order-Book-Channel * @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 watchOrderBook(symbol, limit = undefined, params = {}) { return await this.watchOrderBookForSymbols([symbol], limit, params); } /** * @method * @name bitget#unWatchOrderBook * @description unsubscribe from the orderbook channel * @see https://www.bitget.com/api-doc/spot/websocket/public/Depth-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/Order-Book-Channel * @param {string} symbol unified symbol of the market to fetch the order book for * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.limit] orderbook limit, default is undefined * @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure} indexed by market symbols */ async unWatchOrderBook(symbol, params = {}) { await this.loadMarkets(); let channel = 'books'; const limit = this.safeInteger(params, 'limit'); if ((limit === 1) || (limit === 5) || (limit === 15)) { params = this.omit(params, 'limit'); channel += limit.toString(); } return await this.unWatchChannel(symbol, channel, 'orderbook', params); } async unWatchChannel(symbol, channel, messageHashTopic, params = {}) { await this.loadMarkets(); const market = this.market(symbol); const messageHash = 'unsubscribe:' + messageHashTopic + ':' + market['symbol']; let instType = undefined; [instType, params] = this.getInstType(market, params); const args = { 'instType': instType, 'channel': channel, 'instId': market['id'], }; return await this.unWatchPublic(messageHash, args, params); } /** * @method * @name bitget#watchOrderBookForSymbols * @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data * @see https://www.bitget.com/api-doc/spot/websocket/public/Depth-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/Order-Book-Channel * @param {string[]} symbols unified array of symbols * @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 watchOrderBookForSymbols(symbols, limit = undefined, params = {}) { await this.loadMarkets(); symbols = this.marketSymbols(symbols); let channel = 'books'; let incrementalFeed = true; if ((limit === 1) || (limit === 5) || (limit === 15)) { channel += limit.toString(); incrementalFeed = false; } const topics = []; const messageHashes = []; for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; const market = this.market(symbol); let instType = undefined; [instType, params] = this.getInstType(market, params); const args = { 'instType': instType, 'channel': channel, 'instId': market['id'], }; topics.push(args); messageHashes.push('orderbook:' + symbol); } const orderbook = await this.watchPublicMultiple(messageHashes, topics, params); if (incrementalFeed) { return orderbook.limit(); } else { return orderbook; } } handleOrderBook(client, message) { // // { // "action":"snapshot", // "arg":{ // "instType":"SPOT", // "channel":"books5", // "instId":"BTCUSDT" // }, // "data":[ // { // "asks":[ // ["21041.11","0.0445"], // ["21041.16","0.0411"], // ["21041.21","0.0421"], // ["21041.26","0.0811"], // ["21041.65","1.9465"] // ], // "bids":[ // ["21040.76","0.0417"], // ["21040.71","0.0434"], // ["21040.66","0.1141"], // ["21040.61","0.3004"], // ["21040.60","1.3357"] // ], // "checksum": -1367582038, // "ts":"1656413855484" // } // ] // } // const arg = this.safeValue(message, 'arg'); const channel = this.safeString(arg, 'channel'); const instType = this.safeString(arg, 'instType'); const marketType = (instType === 'SPOT') ? 'spot' : 'contract'; const marketId = this.safeString(arg, 'instId'); const market = this.safeMarket(marketId, undefined, undefined, marketType); const symbol = market['symbol']; const messageHash = 'orderbook:' + symbol; const data = this.safeValue(message, 'data'); const rawOrderBook = this.safeValue(data, 0); const timestamp = this.safeInteger(rawOrderBook, 'ts'); const incrementalBook = channel === 'books'; if (incrementalBook) { // storedOrderBook = this.safeValue (this.orderbooks, symbol); if (!(symbol in this.orderbooks)) { // const ob = this.orderBook ({}); const ob = this.countedOrderBook({}); ob['symbol'] = symbol; this.orderbooks[symbol] = ob; } const storedOrderBook = this.orderbooks[symbol]; const asks = this.safeValue(rawOrderBook, 'asks', []); const bids = this.safeValue(rawOrderBook, 'bids', []); this.handleDeltas(storedOrderBook['asks'], asks); this.handleDeltas(storedOrderBook['bids'], bids); storedOrderBook['timestamp'] = timestamp; storedOrderBook['datetime'] = this.iso8601(timestamp); const checksum = this.handleOption('watchOrderBook', 'checksum', true); const isSnapshot = this.safeString(message, 'action') === 'snapshot'; // snapshot does not have a checksum if (!isSnapshot && checksum) { const storedAsks = storedOrderBook['asks']; const storedBids = storedOrderBook['bids']; const asksLength = storedAsks.length; const bidsLength = storedBids.length; const payloadArray = []; for (let i = 0; i < 25; i++) { if (i < bidsLength) { payloadArray.push(storedBids[i][2][0]); payloadArray.push(storedBids[i][2][1]); } if (i < asksLength) { payloadArray.push(storedAsks[i][2][0]); payloadArray.push(storedAsks[i][2][1]); } } const payload = payloadArray.join(':'); const calculatedChecksum = this.crc32(payload, true); const responseChecksum = this.safeInteger(rawOrderBook, 'checksum'); if (calculatedChecksum !== responseChecksum) { // if (messageHash in client.subscriptions) { // // delete client.subscriptions[messageHash]; // // delete this.orderbooks[symbol]; // } this.spawn(this.handleCheckSumError, client, symbol, messageHash); return; } } } else { const orderbook = this.orderBook({}); const parsedOrderbook = this.parseOrderBook(rawOrderBook, symbol, timestamp); orderbook.reset(parsedOrderbook); this.orderbooks[symbol] = orderbook; } client.resolve(this.orderbooks[symbol], messageHash); } async handleCheckSumError(client, symbol, messageHash) { await this.unWatchOrderBook(symbol); const error = new ChecksumError(this.id + ' ' + this.orderbookChecksumMessage(symbol)); client.reject(error, messageHash); } handleDelta(bookside, delta) { const bidAsk = this.parseBidAsk(delta, 0, 1); // we store the string representations in the orderbook for checksum calculation // this simplifies the code for generating checksums as we do not need to do any complex number transformations bidAsk.push(delta); bookside.storeArray(bidAsk); } handleDeltas(bookside, deltas) { for (let i = 0; i < deltas.length; i++) { this.handleDelta(bookside, deltas[i]); } } /** * @method * @name bitget#watchTrades * @description get the list of most recent trades for a particular symbol * @see https://www.bitget.com/api-doc/spot/websocket/public/Trades-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/New-Trades-Channel * @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 bitget#watchTradesForSymbols * @description get the list of most recent trades for a particular symbol * @see https://www.bitget.com/api-doc/spot/websocket/public/Trades-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/New-Trades-Channel * @param {string[]} symbols 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 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 topics = []; const messageHashes = []; for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; const market = this.market(symbol); let instType = undefined; [instType, params] = this.getInstType(market, params); const args = { 'instType': instType, 'channel': 'trade', 'instId': market['id'], }; topics.push(args); messageHashes.push('trade:' + symbol); } const trades = await this.watchPublicMultiple(messageHashes, topics, params); if (this.newUpdates) { const first = this.safeValue(trades, 0); const tradeSymbol = this.safeString(first, 'symbol'); limit = trades.getLimit(tradeSymbol, limit); } const result = this.filterBySinceLimit(trades, since, limit, 'timestamp', true); if (this.handleOption('watchTrades', 'ignoreDuplicates', true)) { let filtered = this.removeRepeatedTradesFromArray(result); filtered = this.sortBy(filtered, 'timestamp'); return filtered; } return result; } /** * @method * @name bitget#unWatchTrades * @description unsubscribe from the trades channel * @see https://www.bitget.com/api-doc/spot/websocket/public/Trades-Channel * @see https://www.bitget.com/api-doc/contract/websocket/public/New-Trades-Channel * @param {string} symbol unified symbol of the market to unwatch the trades for * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {any} status of the unwatch request */ async unWatchTrades(symbol, params = {}) { await this.loadMarkets(); return await this.unWatchChannel(symbol, 'trade', 'trade', params); } handleTrades(client, message) { // // { // "action": "snapshot", // "arg": { "instType": "SPOT", "channel": "trade", "instId": "BTCUSDT" }, // "data": [ // { // "ts": "1701910980366", // "price": "43854.01", // "size": "0.0535", // "side": "buy", // "tradeId": "1116461060594286593" // }, // ], // "ts": 1701910980730 // } // const arg = this.safeValue(message, 'arg', {}); const instType = this.safeString(arg, 'instType'); const marketType = (instType === 'SPOT') ? 'spot' : 'contract'; const marketId = this.safeString(arg, 'instId'); const market = this.safeMarket(marketId, undefined, undefined, marketType); const symbol = market['symbol']; let stored = this.safeValue(this.trades, symbol); if (stored === undefined) { const limit = this.safeInteger(this.options, 'tradesLimit', 1000); stored = new ArrayCache(limit); this.trades[symbol] = stored; } const data = this.safeList(message, 'data', []); const length = data.length; // fix chronological order by reversing for (let i = 0; i < length; i++) { const index = length - i - 1; const rawTrade = data[index]; const parsed = this.parseWsTrade(rawTrade, market); stored.append(parsed); } const messageHash = 'trade:' + symbol; client.resolve(stored, messageHash); } parseWsTrade(trade, market = undefined) { // // { // "ts": "1701910980366", // "price": "43854.01", // "size": "0.0535", // "side": "buy", // "tradeId": "1116461060594286593" // } // swap private // // { // "orderId": "1169142761031114781", // "tradeId": "1169142761312637004", // "symbol": "LTCUSDT", // "orderType": "market", // "side": "buy", // "price": "80.87", // "baseVolume": "0.1", // "quoteVolume": "8.087", // "profit": "0", // "tradeSide": "open", // "posMode": "hedge_mode", // "tradeScope": "taker", // "feeDetail": [ // { // "feeCoin": "USDT", // "deduction": "no", // "totalDeductionFee": "0", // "totalFee": "-0.0048522" // } // ], // "cTime": "1714471276596", // "uTime": "1714471276596" // } // spot private // { // "orderId": "1169142457356959747", // "tradeId": "1169142457636958209", // "symbol": "LTCUSDT", // "orderType": "market", // "side": "buy", // "priceAvg": "81.069", // "size": "0.074", // "amount": "5.999106", // "tradeScope": "taker", // "feeDetail": [ // { // "feeCoin": "LTC", // "deduction": "no", // "totalDeductionFee": "0", // "totalFee": "0.000074" // } // ], // "cTime": "1714471204194", // "uTime": "1714471204194" // } // const instId = this.safeString2(trade, 'symbol', 'instId'); const posMode = this.safeString(trade, 'posMode'); const defaultType = (posMode !== undefined) ? 'contract' : 'spot'; if (market === undefined) { market = this.safeMarket(instId, undefined, undefined, defaultType); } const timestamp = this.safeIntegerN(trade, ['uTime', 'cTime', 'ts']); const feeDetail = this.safeList(trade, 'feeDetail', []); const first = this.safeDict(feeDetail, 0); let fee = undefined; if (first !== undefined) { const feeCurrencyId = this.safeString(first, 'feeCoin'); const feeCurrencyCode = this.safeCurrencyCode(feeCurrencyId); fee = { 'cost': Precise.stringAbs(this.safeString(first, 'totalFee')), 'currency': feeCurrencyCode, }; } return this.safeTrade({ 'info': trade, 'id': this.safeString(trade, 'tradeId'), 'order': this.safeString(trade, 'orderId'), 'timestamp': timestamp, 'datetime': this.iso8601(timestamp), 'symbol': market['symbol'], 'type': this.safeString(trade, 'orderType'), 'side': this.safeString(trade, 'side'), 'takerOrMaker': this.safeString(trade, 'tradeScope'), 'price': this.safeString2(trade, 'priceAvg', 'price'), 'amount': this.safeString2(trade, 'size', 'baseVolume'), 'cost': this.safeString2(trade, 'amount', 'quoteVolume'), 'fee': fee, }, market); } /** * @method * @name bitget#watchPositions * @description watch all open positions * @see https://www.bitget.com/api-doc/contract/websocket/private/Positions-Channel * @param {string[]|undefined} symbols list of unified market symbols * @param {int} [since] the earliest time in ms to fetch positions for * @param {int} [limit] the maximum number of positions to retrieve * @param {object} params extra parameters specific to the exchange API endpoint * @param {string} [params.instType] one of 'USDT-FUTURES', 'USDC-FUTURES', 'COIN-FUTURES', 'SUSDT-FUTURES', 'SUSDC-FUTURES' or 'SCOIN-FUTURES', default is 'USDT-FUTURES' * @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/en/latest/manual.html#position-structure} */ async watchPositions(symbols = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets(); let market = undefined; let messageHash = ''; const subscriptionHash = 'positions'; let instType = 'USDT-FUTURES'; symbols = this.marketSymbols(symbols); if (!this.isEmpty(symbols)) { market = this.getMarketFromSymbols(symbols); [instType, params] = this.getInstType(market, params); } messageHash = instType + ':positions' + messageHash; const args = { 'instType': instType, 'channel': 'positions', 'instId': 'default', }; const newPositions = await this.watchPrivate(messageHash, subscriptionHash, args, params); if (this.newUpdates) { return newPositions; } return this.filterBySymbolsSinceLimit(newPositions, symbols, since, limit, true); } handlePositions(client, message) { // // { // "action": "snapshot", // "arg": { // "instType": "USDT-FUTURES", // "channel": "positions", // "instId": "default" // }, // "data": [ // { // "posId": "926036334386778112", // "instId": "BTCUSDT", // "marginCoin": "USDT", // "marginSize": "2.19245", // "marginMode": "crossed", // "holdSide": "long", // "posMode": "hedge_mode", // "total": "0.001", // "available": "0.001", // "frozen": "0", // "openPriceAvg": "43849", // "leverage": 20, // "achievedProfits": "0", // "unrealizedPL": "-0.0032", // "unrealizedPLR": "-0.00145955438", // "liquidationPrice": "17629.684814834", // "keepMarginRate": "0.004", // "marginRate": "0.007634649185", // "cTime": "1652331666985", // "uTime": "1701913016923", // "autoMargin": "off" // }, // ... // ] // "ts": 1701913043767 // } // const arg = this.safeValue(message, 'arg', {}); const instType = this.safeString(arg, 'instType', ''); if (this.positions === undefined) { this.positions = {}; } const action = this.safeString(message, 'action'); if (!(instType in this.positions) || (action === 'snapshot')) { this.positions[instType] = new ArrayCacheBySymbolBySide(); } const cache = this.positions[instType]; const rawPositions = this.safeValue(message, 'data', []); const newPositions = []; for (let i = 0; i < rawPositions.length; i++) { const rawPosition = rawPositions[i]; const marketId = this.safeString(rawPosition, 'instId'); const market = this.safeMarket(marketId, undefined, undefined, 'contract'); const position = this.parseWsPosition(rawPosition, market); newPositions.push(position); cache.append(position); } const messageHashes = this.findMessageHashes(client, instType + ':positions::'); for (let i = 0; i < messageHashes.length; i++) { const messageHash = messageHashes[i]; const parts = messageHash.split('::'); const symbolsString = parts[1]; const symbols = symbolsString.split(','); const positions = this.filterByArray(newPositions, 'symbol', symbols, false); if (!this.isEmpty(positions)) { client.resolve(positions, messageHash); } } client.resolve(newPositions, instType + ':positions'); } parseWsPosition(position, market = undefined) { // // { // "posId": "926036334386778112", // "instId": "BTCUSDT", // "marginCoin": "USDT", // "marginSize": "2.19245", // "marginMode": "crossed", // "holdSide": "long", // "posMode": "hedge_mode", // "total": "0.001", // "available": "0.001", // "frozen": "0", // "openPriceAvg": "43849", // "leverage": 20, // "achievedProfits": "0", // "unrealizedPL": "-0.0032", // "unrealizedPLR": "-0.00145955438", // "liquidationPrice": "17629.684814834", // "keepMarginRate": "0.004", // "marginRate": "0.007634649185", // "cTime": "1652331666985", // "uTime": "1701913016923", // "autoMargin": "off" // } // const marketId = this.safeString(position, 'instId'); const marginModeId = this.safeString(position, 'marginMode'); const marginMode = this.getSupportedMapping(marginModeId, { 'crossed': 'cross', 'isolated': 'isolated', }); const hedgedId = this.safeString(position, 'posMode'); const hedged = (hedgedId === 'hedge_mode') ? true : false; const timestamp = this.safeInteger2(position, 'uTime', 'cTime'); const percentageDecimal = this.safeString(position, 'unrealizedPLR'); const percentage = Precise.stringMul(percentageDecimal, '100'); let contractSize = undefined; if (market !== undefined) { contractSize = market['contractSize']; } return this.safePosition({ 'info': position, 'id': this.safeString(position, 'posId'), 'symbol': this.safeSymbol(marketId, market, undefined, 'contract'), 'notional': undefined, 'marginMode': marginMode, 'liquidationPrice': this.safeNumber(position, 'liquidationPrice'), 'entryPrice': this.safeNumber(position, 'openPriceAvg'), 'unrealizedPnl': this.safeNumber(position, 'unrealizedPL'), 'percentage': this.parseNumber(percentage), 'contracts': this.safeNumber(position, 'total'), 'contractSize': contractSize, 'markPrice':