import { CircularBuffer, getJSON, wait } from '../handy.ts' import type { MexcDepthSnapshotMessage } from '../mappers/mexc.ts' import { Filter } from '../types.ts' import { RealTimeFeedBase } from './realtimefeed.ts' import { decodeMexcProtobufMessage } from './mexcprotobuf.ts' export class MexcRealTimeFeed extends RealTimeFeedBase { private static readonly depthChannel = 'spot@public.aggre.depth.v3.api.pb@10ms' private static readonly depthSnapshotChannel = 'spot@public.aggre.depth.snapshot.v3.api.pb@10ms' private static readonly jsonObjectStart = '{'.charCodeAt(0) private readonly pendingDepthSnapshotSymbols = new Set() private readonly bufferedDepthUpdates = new Map>() protected readonly wssURL = 'wss://wbs-api.mexc.com/ws' protected readonly httpURL: string = 'https://api.mexc.com' private readonly channels = new Set([ 'spot@public.aggre.deals.v3.api.pb@10ms', MexcRealTimeFeed.depthChannel, MexcRealTimeFeed.depthSnapshotChannel, 'spot@public.aggre.bookTicker.v3.api.pb@10ms' ]) protected override mapToSubscribeMessages(filters: Filter[]): any[] { const filtersWithSymbols = filters.map>>((filter) => { if (!this.channels.has(filter.channel)) { throw new Error(`MexcRealTimeFeed unsupported channel ${filter.channel}`) } if (!filter.symbols || filter.symbols.length === 0) { throw new Error('MexcRealTimeFeed requires explicitly specified symbols when subscribing to live feed') } return filter as Required> }) const depthSnapshotFilters = filtersWithSymbols.filter((filter) => filter.channel === MexcRealTimeFeed.depthSnapshotChannel) this.validateDepthSnapshotFilters(filtersWithSymbols, depthSnapshotFilters) this.resetDepthSnapshotTracking(depthSnapshotFilters) return [ { method: 'SUBSCRIPTION', params: filtersWithSymbols.flatMap((filter) => filter.channel === MexcRealTimeFeed.depthSnapshotChannel ? [] : filter.symbols.map((symbol) => `${filter.channel}@${symbol.toUpperCase()}`) ) } ] } protected override parseMessage(message: Buffer): any { const buffer = Buffer.isBuffer(message) ? message : Buffer.from(message) if (buffer.length > 0 && buffer[0] === MexcRealTimeFeed.jsonObjectStart) { return JSON.parse(buffer.toString()) } return decodeMexcProtobufMessage(buffer) } protected override messageIsError(message: any): boolean { return message.code !== undefined && message.code !== 0 } protected override messageIsHeartbeat(message: any) { return message.msg === 'PONG' } protected override onMessage(message: any) { if ( message.channel?.startsWith(MexcRealTimeFeed.depthChannel) !== true || message.symbol === undefined || this.pendingDepthSnapshotSymbols.has(message.symbol) === false ) { return } const firstVersion = Number(message.publicAggreDepths?.fromVersion) const lastVersion = Number(message.publicAggreDepths?.toVersion) if (Number.isFinite(firstVersion) === false || Number.isFinite(lastVersion) === false) { return } const bufferedUpdates = this.bufferedDepthUpdates.get(message.symbol) ?? new CircularBuffer(2000) bufferedUpdates.append({ firstVersion, lastVersion }) this.bufferedDepthUpdates.set(message.symbol, bufferedUpdates) } protected override async provideManualSnapshots(filters: Filter[], shouldCancel: () => boolean) { const depthFilter = filters.find((filter) => filter.channel === MexcRealTimeFeed.depthSnapshotChannel) if (depthFilter === undefined) { return } this.debug('requesting manual snapshots for: %s', depthFilter.symbols!) for (const symbol of depthFilter.symbols!) { await this.provideManualSnapshot(symbol.toUpperCase(), shouldCancel) } this.debug('requested manual snapshots successfully for: %s ', depthFilter.symbols!) } protected sendCustomPing = () => { this.send({ method: 'PING' }) } private resetDepthSnapshotTracking(filters: Required>[]) { this.pendingDepthSnapshotSymbols.clear() this.bufferedDepthUpdates.clear() for (const filter of filters) { for (const symbol of filter.symbols) { const upperCaseSymbol = symbol.toUpperCase() this.pendingDepthSnapshotSymbols.add(upperCaseSymbol) this.bufferedDepthUpdates.set(upperCaseSymbol, new CircularBuffer(2000)) } } } private validateDepthSnapshotFilters(filters: Required>[], depthSnapshotFilters: Required>[]) { if (depthSnapshotFilters.length === 0) { return } const depthSymbols = new Set( filters .filter((filter) => filter.channel === MexcRealTimeFeed.depthChannel) .flatMap((filter) => filter.symbols.map((symbol) => symbol.toUpperCase())) ) for (const filter of depthSnapshotFilters) { for (const symbol of filter.symbols) { if (depthSymbols.has(symbol.toUpperCase()) === false) { throw new Error( `MexcRealTimeFeed requires ${MexcRealTimeFeed.depthChannel} for every ${MexcRealTimeFeed.depthSnapshotChannel} symbol` ) } } } } private async provideManualSnapshot(symbol: string, shouldCancel: () => boolean) { const maxSnapshotRounds = 4 const maxSnapshotAttemptsPerRound = 3 for (let round = 0; round < maxSnapshotRounds; round++) { for (let attempt = 1; attempt <= maxSnapshotAttemptsPerRound; attempt++) { if (shouldCancel()) { return } const { data } = await getJSON(`${this.httpURL}/api/v3/depth?symbol=${symbol}&limit=5000`) if (this.snapshotResponseIsValid(data) === false) { if (attempt < maxSnapshotAttemptsPerRound) { await wait(attempt * 1000) } continue } const hasOverlap = await this.waitForSnapshotOverlap(symbol, data.lastUpdateId) if (shouldCancel()) { return } if (hasOverlap === false) { this.trimBufferedUpdates(symbol) if (attempt < maxSnapshotAttemptsPerRound) { await wait(attempt * 1000) } continue } if (hasOverlap === true || attempt === maxSnapshotAttemptsPerRound) { this.manualSnapshotsBuffer.push(this.createManualSnapshot(symbol, data)) this.pendingDepthSnapshotSymbols.delete(symbol) this.bufferedDepthUpdates.delete(symbol) return } } } throw new Error(`MexcRealTimeFeed could not align depth snapshot for ${symbol}`) } private async waitForSnapshotOverlap(symbol: string, lastUpdateId: number) { let hasOverlap = this.validateSnapshotOverlap(symbol, lastUpdateId) for (let attempt = 0; attempt < 60; attempt++) { if (hasOverlap !== undefined) { return hasOverlap } await wait(100) hasOverlap = this.validateSnapshotOverlap(symbol, lastUpdateId) } return hasOverlap } private validateSnapshotOverlap(symbol: string, lastUpdateId: number) { const bufferedUpdates = this.bufferedDepthUpdates.get(symbol) for (const update of bufferedUpdates?.items() ?? []) { if (update.lastVersion <= lastUpdateId) { continue } return update.firstVersion <= lastUpdateId + 1 && update.lastVersion >= lastUpdateId + 1 } return undefined } private trimBufferedUpdates(symbol: string) { const bufferedUpdates = this.bufferedDepthUpdates.get(symbol) if (bufferedUpdates === undefined || bufferedUpdates.count <= 100) { return } const trimmed = new CircularBuffer(2000) for (const update of [...bufferedUpdates.items()].slice(-100)) { trimmed.append(update) } this.bufferedDepthUpdates.set(symbol, trimmed) } private snapshotResponseIsValid(data: MexcDepthSnapshotResponse) { return Number.isFinite(data.lastUpdateId) && Array.isArray(data.asks) && Array.isArray(data.bids) } private createManualSnapshot(symbol: string, data: MexcDepthSnapshotResponse): MexcDepthSnapshotMessage { return { channel: `${MexcRealTimeFeed.depthSnapshotChannel}@${symbol}`, symbol, generated: true, publicAggreDepthsSnapshot: { lastUpdateId: data.lastUpdateId, asks: data.asks, bids: data.bids, timestamp: data.timestamp } } } } type MexcDepthSnapshotResponse = { lastUpdateId: number bids: [string, string][] asks: [string, string][] timestamp: number } type MexcDepthUpdateData = { firstVersion: number lastVersion: number }