UNPKG

@nevuamarkets/poly-websockets

Version:

Plug-and-play Polymarket WebSocket price alerts

146 lines (145 loc) 5.18 kB
import { WebSocketHandlers } from './types/PolymarketWebSocket'; import { SubscriptionManagerOptions } from './types/WebSocketSubscriptions'; /** * WebSocket Subscription Manager for Polymarket CLOB WebSocket. * * Each instance manages a single WebSocket connection and tracks: * - Subscribed assets: Successfully subscribed to the WebSocket * - Pending assets: Waiting to be subscribed (batched and flushed periodically) * * Instances are fully independent - no shared state between managers. */ declare class WSSubscriptionManager { private readonly managerId; private handlers; private bookCache; private wsClient; private status; private connecting; private subscribedAssetIds; private pendingSubscribeAssetIds; private pendingUnsubscribeAssetIds; private reconnectIntervalMs; private pendingFlushIntervalMs; private reconnectInterval?; private pendingFlushInterval?; private pingInterval?; private connectionTimeout?; constructor(userHandlers: WebSocketHandlers, options?: SubscriptionManagerOptions); /** * Clears all WebSocket subscriptions and state. * * This will: * 1. Stop all timers * 2. Close the WebSocket connection * 3. Clear all asset tracking * 4. Clear the order book cache */ clearState(): Promise<void>; /** * Filters events to only include those for subscribed assets. * Wraps user handler calls in try-catch to prevent user errors from breaking internal logic. * Does not call the handler if all events are filtered out. */ private actOnSubscribedEvents; /** * Adds new subscriptions. * * Assets are added to a pending queue and will be subscribed when: * - The WebSocket connects (initial subscription) * - The pending flush timer fires (for new assets on an existing connection) * * @param assetIdsToAdd - The asset IDs to add subscriptions for. */ addSubscriptions(assetIdsToAdd: string[]): Promise<void>; /** * Ensures the periodic intervals are running. * Called after clearState() when new subscriptions are added. */ private ensureIntervalsRunning; /** * Schedules the next reconnection check. * Uses a fixed interval (default 5 seconds) between checks. */ private scheduleReconnectionCheck; /** * Safely calls the error handler, catching any exceptions thrown by it. * Prevents user handler exceptions from breaking internal logic. */ private safeCallErrorHandler; /** * Removes subscriptions. * * @param assetIdsToRemove - The asset IDs to remove subscriptions for. */ removeSubscriptions(assetIdsToRemove: string[]): Promise<void>; /** * Get all currently monitored asset IDs. * This includes both successfully subscribed assets and pending subscriptions. * * @returns Array of asset IDs being monitored. */ getAssetIds(): string[]; /** * Returns statistics about the current state of the subscription manager. */ getStatistics(): { openWebSockets: number; assetIds: number; pendingSubscribeCount: number; pendingUnsubscribeCount: number; /** @deprecated Use pendingSubscribeCount + pendingUnsubscribeCount instead */ pendingAssetIds: number; }; /** * Flush pending subscriptions and unsubscriptions to the WebSocket. * * SUBSCRIPTION PROTOCOL NOTE: * The Polymarket WebSocket protocol does NOT send any confirmation or acknowledgment * messages for subscribe/unsubscribe operations. The server silently processes these * requests. We optimistically assume success after sending. If the server rejects * a request (e.g., invalid asset ID), events for those assets simply won't arrive - * there is no error response to handle. * * This means: * - We cannot definitively know if a subscription succeeded * - We cannot definitively know if an unsubscription succeeded * - The only indication of failure is the absence of expected events */ private flushPendingSubscriptions; /** * Closes the WebSocket connection and cleans up related resources. */ private closeWebSocket; /** * Check if we need to reconnect. * Note: Assets are moved to pending in handleClose/handleError handlers, * so this method only needs to check if reconnection is needed. */ private checkReconnection; /** * Establish the WebSocket connection. */ private connect; /** * Sets up event handlers for the WebSocket connection. */ private setupEventHandlers; /** * Handles book events by updating the cache and notifying listeners. */ private handleBookEvents; /** * Handles tick size change events by notifying listeners. */ private handleTickEvents; /** * Handles price change events. */ private handlePriceChangeEvents; /** * Handles last trade price events. */ private handleLastTradeEvents; } export { WSSubscriptionManager, WebSocketHandlers };