@tentou-tech/poly-websockets
v1.0.1
Published
Plug-and-play Polymarket WebSocket price alerts
Readme
Poly-WebSockets
A TypeScript library for real-time Polymarket market data over WebSocket with automatic reconnections and easy subscription management.
Powering Nevua Markets
Installation
npm install @tentou-tech/poly-websocketsFeatures
- 📊 Real-time Market Updates: Get
book,price_change,tick_size_change,last_trade_price,best_bid_ask,new_marketandmarket_resolvedevents from Polymarket WebSocket - 🎯 Derived Price Event: Implements Polymarket's price calculation logic (midpoint vs last trade price based on spread)
- 🔗 Dynamic Subscriptions: Subscribe and unsubscribe to assets without reconnecting
- 🔄 Automatic Reconnection: Handles connection drops with automatic reconnection
- 💪 TypeScript Support: Full TypeScript definitions for all events and handlers
- 🔒 Independent Instances: Each manager instance is fully isolated with its own WebSocket connection
Quick Start
import { WSSubscriptionManager } from '@nevuamarkets/poly-websockets';
const manager = new WSSubscriptionManager({
onBook: async (events) => {
console.log('Book events:', events);
},
onPriceChange: async (events) => {
console.log('Price change events:', events);
},
onPolymarketPriceUpdate: async (events) => {
// Derived price following Polymarket's display logic
console.log('Price updates:', events);
},
onError: async (error) => {
console.error('Error:', error.message);
}
});
// Subscribe to assets
await manager.addSubscriptions(['asset-id-1', 'asset-id-2']);
// Get monitored assets
console.log('Monitored:', manager.getAssetIds());
// Remove subscriptions
await manager.removeSubscriptions(['asset-id-1']);
// Clear all subscriptions and close connection
await manager.clearState();Market-Level Events
To receive new_market and market_resolved events, enable custom features:
import { WSSubscriptionManager, NewMarketEvent, MarketResolvedEvent } from '@nevuamarkets/poly-websockets';
const manager = new WSSubscriptionManager({
onNewMarket: async (events: NewMarketEvent[]) => {
for (const event of events) {
console.log('New market created:', event.question);
console.log('Market ID:', event.id);
console.log('Asset IDs:', event.assets_ids);
}
},
onMarketResolved: async (events: MarketResolvedEvent[]) => {
for (const event of events) {
console.log('Market resolved:', event.question);
console.log('Winning outcome:', event.winning_outcome);
}
},
onBestBidAsk: async (events) => {
for (const event of events) {
console.log(`Best bid: ${event.best_bid}, Best ask: ${event.best_ask}`);
}
}
}, {
enableCustomFeatures: true // Required for new_market and market_resolved
});
// Market-level events work even without asset subscriptions
await manager.addSubscriptions([]);Note: Market-level events (new_market, market_resolved) are broadcast to all handlers regardless of asset subscriptions. Asset-level events (book, price_change, best_bid_ask, etc.) are only received for subscribed assets.
API Reference
WSSubscriptionManager
Constructor
new WSSubscriptionManager(handlers: WebSocketHandlers, options?: SubscriptionManagerOptions)Parameters:
handlers- Event handlers for WebSocket eventsoptions- Optional configuration:reconnectAndCleanupIntervalMs?: number- Reconnection check interval (default: 5000ms)pendingFlushIntervalMs?: number- How often to flush pending subscriptions (default: 100ms)enableCustomFeatures?: boolean- Enable custom features likenew_marketandmarket_resolvedevents (default: false)
Methods
| Method | Description |
|--------|-------------|
| addSubscriptions(assetIds: string[]) | Add assets to monitor |
| removeSubscriptions(assetIds: string[]) | Stop monitoring assets |
| getAssetIds(): string[] | Get all monitored asset IDs (subscribed + pending) |
| getStatistics() | Get connection and subscription statistics |
| clearState() | Clear all subscriptions and close connection |
Statistics Object
manager.getStatistics() // Returns:
{
openWebSockets: number; // 1 if connected, 0 otherwise
assetIds: number; // Total monitored assets
pendingSubscribeCount: number; // Assets waiting to be subscribed
pendingUnsubscribeCount: number; // Assets waiting to be unsubscribed
}WebSocketHandlers
interface WebSocketHandlers {
// Polymarket WebSocket events (asset-level)
onBook?: (events: BookEvent[]) => Promise<void>;
onLastTradePrice?: (events: LastTradePriceEvent[]) => Promise<void>;
onPriceChange?: (events: PriceChangeEvent[]) => Promise<void>;
onTickSizeChange?: (events: TickSizeChangeEvent[]) => Promise<void>;
onBestBidAsk?: (events: BestBidAskEvent[]) => Promise<void>;
// Polymarket WebSocket events (market-level, requires enableCustomFeatures: true)
onNewMarket?: (events: NewMarketEvent[]) => Promise<void>;
onMarketResolved?: (events: MarketResolvedEvent[]) => Promise<void>;
// Derived price update (implements Polymarket's display logic)
onPolymarketPriceUpdate?: (events: PolymarketPriceUpdateEvent[]) => Promise<void>;
// Connection events
onWSOpen?: (managerId: string, pendingAssetIds: string[]) => Promise<void>;
onWSClose?: (managerId: string, code: number, reason: string) => Promise<void>;
onError?: (error: Error) => Promise<void>;
}Event Types
Asset-Level Events
These events are filtered by subscribed asset IDs:
| Event | Description |
|-------|-------------|
| BookEvent | Full order book snapshot (docs) |
| PriceChangeEvent | Order book price level changes (docs) |
| TickSizeChangeEvent | Tick size changes (docs) |
| LastTradePriceEvent | Trade executions |
| BestBidAskEvent | Best bid/ask price updates (docs) |
Market-Level Events
These events are broadcast to all handlers (not filtered by subscriptions). Requires enableCustomFeatures: true:
| Event | Description |
|-------|-------------|
| NewMarketEvent | New market creation (docs) |
| MarketResolvedEvent | Market resolution (docs) |
Derived Events
| Event | Description |
|-------|-------------|
| PolymarketPriceUpdateEvent | Derived price using Polymarket's display logic |
Multiple Independent Connections
Each WSSubscriptionManager instance maintains its own WebSocket connection:
// Two separate connections for different asset groups
const manager1 = new WSSubscriptionManager(handlers1);
const manager2 = new WSSubscriptionManager(handlers2);
await manager1.addSubscriptions(['asset-1', 'asset-2']);
await manager2.addSubscriptions(['asset-3', 'asset-4']);Examples
See the examples folder for complete working examples.
Testing
npm testLicense
AGPL-3.0
Disclaimer
This software is provided "as is", without warranty of any kind. The author(s) are not responsible for any financial losses, trading decisions, bugs, or system failures. Use at your own risk.
