import { debug } from '../debug.ts' import { CircularBuffer, upperCaseSymbols } from '../handy.ts' import { BookChange, DerivativeTicker, Trade } from '../types.ts' import { Mapper, PendingTickerInfoHelper } from './mapper.ts' import { exchangeMappers, isRealTime } from './registry.ts' export const mexcFuturesMappers = exchangeMappers({ 'mexc-futures': { trades: () => new MexcFuturesTradesMapper(), bookChanges: (localTimestamp) => new MexcFuturesBookChangeMapper({ ignoreBookSnapshotOverlapError: isRealTime(localTimestamp) === false }), derivativeTickers: () => new MexcFuturesDerivativeTickerMapper() } }) export class MexcFuturesTradesMapper implements Mapper<'mexc-futures', Trade> { canHandle(message: MexcFuturesDealMessage) { return message.channel === 'push.deal' } getFilters(symbols: string[] = []) { return [{ channel: 'push.deal', symbols: upperCaseSymbols(symbols) } as const] } *map(message: MexcFuturesDealMessage, localTimestamp: Date): IterableIterator { for (const trade of message.data) { yield { type: 'trade', symbol: message.symbol, exchange: 'mexc-futures', id: trade.i, price: trade.p, amount: trade.v, side: trade.T === MexcFuturesTradeSide.Buy ? 'buy' : 'sell', timestamp: new Date(trade.t), localTimestamp } } } } export class MexcFuturesBookChangeMapper implements Mapper<'mexc-futures', BookChange> { private readonly symbolDepthInfo: Record = {} private readonly ignoreBookSnapshotOverlapError: boolean constructor({ ignoreBookSnapshotOverlapError }: { ignoreBookSnapshotOverlapError: boolean }) { this.ignoreBookSnapshotOverlapError = ignoreBookSnapshotOverlapError } canHandle(message: MexcFuturesDepthMessage) { return message.channel === 'push.depth' || message.channel === 'push.depth.snapshot' } getFilters(symbols: string[] = []) { const normalizedSymbols = upperCaseSymbols(symbols) return [ { channel: 'push.depth', symbols: normalizedSymbols } as const, { channel: 'push.depth.snapshot', symbols: normalizedSymbols } as const ] } *map(message: MexcFuturesDepthMessage, localTimestamp: Date): IterableIterator { const depthInfo = this.getSymbolDepthInfo(message.symbol) if (message.generated === true) { if (depthInfo.snapshotEmitted) { return } for (const update of depthInfo.updates.items()) { const updateFirstVersion = this.getFirstVersion(update.data) const updateLastVersion = this.getLastVersion(update.data) if (message.data.version >= updateLastVersion) { continue } if (!depthInfo.isContinuityValidated) { if (updateFirstVersion > message.data.version + 1 || updateLastVersion < message.data.version + 1) { const errorMessage = `MEXC futures depth snapshot has no overlap with first update, update ${JSON.stringify(update)}, currentBookVersion: ${message.data.version}` if (this.ignoreBookSnapshotOverlapError) { depthInfo.isContinuityValidated = true debug(errorMessage) } else { throw new Error(errorMessage) } } else { depthInfo.isContinuityValidated = true } } for (const bid of update.data.bids) { this.applyLevel(message.data.bids, bid) } for (const ask of update.data.asks) { this.applyLevel(message.data.asks, ask) } message.data.version = updateLastVersion } depthInfo.updates.clear() depthInfo.currentBookVersion = message.data.version depthInfo.snapshotEmitted = true yield { type: 'book_change', symbol: message.symbol, exchange: 'mexc-futures', isSnapshot: true, bids: message.data.bids.map(this.mapBookLevel), asks: message.data.asks.map(this.mapBookLevel), timestamp: new Date(message.data.timestamp), localTimestamp } return } if (!depthInfo.snapshotEmitted) { depthInfo.updates.append(message) return } const firstVersion = this.getFirstVersion(message.data) const lastVersion = this.getLastVersion(message.data) if (lastVersion <= depthInfo.currentBookVersion!) { return } if (!depthInfo.isContinuityValidated) { if (firstVersion > depthInfo.currentBookVersion! + 1 || lastVersion < depthInfo.currentBookVersion! + 1) { const errorMessage = `MEXC futures depth snapshot has no overlap with first update, update ${JSON.stringify(message)}, currentBookVersion: ${depthInfo.currentBookVersion}` if (this.ignoreBookSnapshotOverlapError) { depthInfo.isContinuityValidated = true debug(errorMessage) } else { throw new Error(errorMessage) } } else { depthInfo.isContinuityValidated = true } } depthInfo.currentBookVersion = lastVersion yield { type: 'book_change', symbol: message.symbol, exchange: 'mexc-futures', isSnapshot: false, bids: message.data.bids.map(this.mapBookLevel), asks: message.data.asks.map(this.mapBookLevel), timestamp: new Date(message.ts), localTimestamp } } private getFirstVersion(data: MexcFuturesDepthUpdateData) { return data.begin !== undefined && data.begin !== null && data.begin !== 0 ? data.begin : data.version } private getLastVersion(data: MexcFuturesDepthUpdateData) { return data.end !== undefined && data.end !== null && data.end !== 0 ? data.end : data.version } private applyLevel(bookSide: MexcFuturesDepthLevel[], levelUpdate: MexcFuturesDepthLevel) { const existingIndex = bookSide.findIndex((level) => level[0] === levelUpdate[0]) if (levelUpdate[1] === 0) { if (existingIndex !== -1) { bookSide.splice(existingIndex, 1) } return } if (existingIndex === -1) { bookSide.push(levelUpdate) } else { bookSide[existingIndex] = levelUpdate } } private mapBookLevel(level: MexcFuturesDepthLevel) { return { price: level[0], amount: level[1] } } private getSymbolDepthInfo(symbol: string) { if (this.symbolDepthInfo[symbol] === undefined) { this.symbolDepthInfo[symbol] = { updates: new CircularBuffer(2000) } } return this.symbolDepthInfo[symbol] } } export class MexcFuturesDerivativeTickerMapper implements Mapper<'mexc-futures', DerivativeTicker> { private readonly pendingTickerInfoHelper = new PendingTickerInfoHelper() canHandle(message: MexcFuturesTickerMessage | MexcFuturesFundingRateMessage) { return message.channel === 'push.ticker' || message.channel === 'push.funding.rate' } getFilters(symbols: string[] = []) { const normalizedSymbols = upperCaseSymbols(symbols) return [ { channel: 'push.ticker', symbols: normalizedSymbols } as const, { channel: 'push.funding.rate', symbols: normalizedSymbols } as const ] } *map(message: MexcFuturesTickerMessage | MexcFuturesFundingRateMessage, localTimestamp: Date): IterableIterator { // Unopened markets send zero activity without mark or index prices. if ( message.channel === 'push.ticker' && message.data.lastPrice === 0 && message.data.holdVol === 0 && message.data.fairPrice === undefined && message.data.indexPrice === undefined ) { return } const pendingTickerInfo = this.pendingTickerInfoHelper.getPendingTickerInfo(message.symbol, 'mexc-futures') if (message.channel === 'push.funding.rate') { pendingTickerInfo.updateFundingRate(message.data.rate) pendingTickerInfo.updateFundingTimestamp( message.data.nextSettleTime !== undefined ? new Date(message.data.nextSettleTime) : undefined ) return } pendingTickerInfo.updateLastPrice(message.data.lastPrice) pendingTickerInfo.updateOpenInterest(message.data.holdVol) pendingTickerInfo.updateIndexPrice(message.data.indexPrice) pendingTickerInfo.updateMarkPrice(message.data.fairPrice) pendingTickerInfo.updateTimestamp(new Date(message.data.timestamp)) if (pendingTickerInfo.hasChanged()) { yield pendingTickerInfo.getSnapshot(localTimestamp) } } } const MEXC_FUTURES_MAPPED_PUSH_CHANNELS = [ 'push.deal', 'push.depth', 'push.depth.snapshot', 'push.ticker', 'push.index.price', 'push.fair.price', 'push.funding.rate' ] as const type MexcFuturesMappedPushChannel = (typeof MEXC_FUTURES_MAPPED_PUSH_CHANNELS)[number] type MexcFuturesMessage = { channel: TChannel symbol: string ts: number data: TData } type MexcFuturesDealMessage = MexcFuturesMessage< 'push.deal', { p: number v: number T: MexcFuturesTradeSide O: MexcFuturesOpenCloseFlag M: MexcFuturesSelfTrade t: number i: string cts?: string }[] > enum MexcFuturesTradeSide { Buy = 1, Sell = 2 } enum MexcFuturesOpenCloseFlag { NewPosition = 1, ReducePosition = 2, Unchanged = 3 } enum MexcFuturesSelfTrade { Yes = 1, No = 2 } type MexcFuturesDepthInfo = { isContinuityValidated?: boolean currentBookVersion?: number snapshotEmitted?: boolean updates: CircularBuffer } type MexcFuturesDepthMessage = MexcFuturesDepthSnapshotMessage | MexcFuturesDepthUpdateMessage export type MexcFuturesDepthSnapshotMessage = { channel: 'push.depth.snapshot' symbol: string generated: true data: MexcFuturesDepthSnapshotData } export type MexcFuturesDepthSnapshotData = { asks: MexcFuturesDepthLevel[] bids: MexcFuturesDepthLevel[] cts?: number | null timestamp: number version: number } type MexcFuturesDepthUpdateMessage = MexcFuturesMessage<'push.depth', MexcFuturesDepthUpdateData> & { generated?: undefined } export type MexcFuturesDepthUpdateData = { asks: MexcFuturesDepthLevel[] bids: MexcFuturesDepthLevel[] begin?: number | null cts?: number end?: number | null version: number } export type MexcFuturesDepthLevel = [price: number, quantity: number, ordersCount: number] type MexcFuturesTickerMessage = MexcFuturesMessage< 'push.ticker', { ask1: number bid1: number contractId?: number fairPrice?: number fundingRate: number high24Price: number indexPrice?: number lastPrice: number lower24Price: number maxBidPrice: number minAskPrice: number riseFallRate: number riseFallValue: number symbol: string timestamp: number holdVol: number volume24: number amount24?: number riseFallRates?: number[] riseFallRatesOfTimezone?: number[] zone?: string } > type MexcFuturesIndexPriceMessage = MexcFuturesMessage<'push.index.price', MexcFuturesPriceData> type MexcFuturesFairPriceMessage = MexcFuturesMessage<'push.fair.price', MexcFuturesPriceData> type MexcFuturesPriceData = { price: number symbol: string } type MexcFuturesFundingRateMessage = MexcFuturesMessage<'push.funding.rate', { rate: number; symbol: string; nextSettleTime?: number }>