@nevuamarkets/poly-websockets 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  A TypeScript library for real-time Polymarket WebSocket price alerts with automatic connection management and intelligent reconnection handling.
4
4
 
5
+ Powering [Nevua Markets](https://nevua.markets)
6
+
5
7
  ## Installation
6
8
 
7
9
  ```bash
@@ -10,11 +12,11 @@ npm install poly-websockets
10
12
 
11
13
  ## Features
12
14
 
13
- - 🔄 **Automatic Connection Management**: Handles WebSocket connections, reconnections, and cleanup for grouped subscriptions
14
- - 📊 **Real-time Price Updates**: Get live price data, order book updates, and trade events from Polymarket
15
- - 🎯 **Smart Price Logic**: Implements Polymarket's price calculation logic (midpoint vs last trade price based on spread)
15
+ - 🔄 **Automatic Connection Management**: Handles WebSocket connections, reconnections, and cleanup for grouped assetId (i.e. clobTokenId) subscriptions
16
+ - 📊 **Real-time Market Updates**: Get `book` , `price_change`, `tick_size_change` and `last_trade_price` real-time market events from Polymarket WSS
17
+ - 🎯 **Derived Future Price Event**: Implements Polymarket's [price calculation logic](https://docs.polymarket.com/polymarket-learn/trading/how-are-prices-calculated#future-price) (midpoint vs last trade price based on spread)
16
18
  - 🚦 **Rate Limiting**: Built-in rate limiting to respect Polymarket API limits
17
- - 🔗 **Group Management**: Efficiently manages multiple asset subscriptions across connection groups
19
+ - 🔗 **Group Management**: Efficiently manages multiple asset subscriptions across connection groups **without losing events** when subscribing / unsubscribing assets.
18
20
  - 💪 **TypeScript Support**: Full TypeScript definitions for all events and handlers
19
21
 
20
22
  ## Quick Start
@@ -64,14 +66,7 @@ new WSSubscriptionManager(handlers: WebSocketHandlers, options?: SubscriptionMan
64
66
  - `options` - Optional configuration object:
65
67
  - `maxMarketsPerWS?: number` - Maximum assets per WebSocket connection (default: 100)
66
68
  - `reconnectAndCleanupIntervalMs?: number` - Interval for reconnection attempts (default: 10s)
67
- - `burstLimiter?: Bottleneck` - Custom rate limiter instance
68
-
69
- **Connection Management:**
70
- The WSSubscriptionManager automatically:
71
- - Groups asset subscriptions into efficient WebSocket connections
72
- - Handles reconnections when connections drop
73
- - Manages connection lifecycle and cleanup
74
- - Balances load across multiple WebSocket groups
69
+ - `burstLimiter?: Bottleneck` - Custom rate limiter instance. If none is provided, one will be created and used internally in the component.
75
70
 
76
71
  #### Methods
77
72
 
@@ -84,7 +79,7 @@ Adds new asset subscriptions. The manager will:
84
79
 
85
80
  ##### `removeSubscriptions(assetIds: string[]): Promise<void>`
86
81
 
87
- Removes asset subscriptions. Connections are kept alive to avoid missing events, and unused groups are cleaned up during the next reconnection cycle.
82
+ Removes asset subscriptions. **Connections are kept alive to avoid missing events**, and unused groups are cleaned up during the next reconnection cycle.
88
83
 
89
84
  ##### `clearState(): Promise<void>`
90
85
 
@@ -105,7 +100,7 @@ interface WebSocketHandlers {
105
100
  onPriceChange?: (events: PriceChangeEvent[]) => Promise<void>;
106
101
  onTickSizeChange?: (events: TickSizeChangeEvent[]) => Promise<void>;
107
102
 
108
- // Aggregated price update event (recommended for most use cases)
103
+ // Derived polymarket price update event
109
104
  onPolymarketPriceUpdate?: (events: PolymarketPriceUpdateEvent[]) => Promise<void>;
110
105
 
111
106
  // Connection lifecycle events
@@ -117,24 +112,22 @@ interface WebSocketHandlers {
117
112
 
118
113
  #### Key Event Types
119
114
 
120
- **PolymarketPriceUpdateEvent** (Recommended)
121
- - Aggregated price update following Polymarket's display logic
122
- - Uses midpoint when spread < $0.10, otherwise uses last trade price
123
- - Includes full order book context
124
-
125
115
  **BookEvent**
126
- - Complete order book snapshots with bids and asks
127
- - Triggered on significant order book changes
116
+ - See // https://docs.polymarket.com/developers/CLOB/websocket/market-channel#book-message
128
117
 
129
118
  **PriceChangeEvent**
130
- - Individual price level changes in the order book
131
- - More granular than book events
119
+ - See https://docs.polymarket.com/developers/CLOB/websocket/market-channel#price-change-message
120
+
121
+ **onTickSizeChange**
122
+ - See https://docs.polymarket.com/developers/CLOB/websocket/market-channel#tick-size-change-message
132
123
 
133
124
  **LastTradePriceEvent**
134
- - Real-time trade executions
135
- - Includes trade side, size, and price
125
+ - Currently undocumented, but is emitted when a trade occurs
136
126
 
137
- ## Advanced Usage
127
+ **PolymarketPriceUpdateEvent**
128
+ - Derived price update following Polymarket's display logic
129
+ - Uses midpoint when spread <= $0.10, otherwise uses last trade price
130
+ - Includes full order book context
138
131
 
139
132
  ### Custom Rate Limiting
140
133
 
@@ -142,10 +135,10 @@ interface WebSocketHandlers {
142
135
  import Bottleneck from 'bottleneck';
143
136
 
144
137
  const customLimiter = new Bottleneck({
145
- reservoir: 3,
146
- reservoirRefreshAmount: 3,
138
+ reservoir: 10,
139
+ reservoirRefreshAmount: 10,
147
140
  reservoirRefreshInterval: 1000,
148
- maxConcurrent: 3
141
+ maxConcurrent: 10
149
142
  });
150
143
 
151
144
  const manager = new WSSubscriptionManager(handlers, {
@@ -153,55 +146,6 @@ const manager = new WSSubscriptionManager(handlers, {
153
146
  });
154
147
  ```
155
148
 
156
- ### Connection Group Configuration
157
-
158
- ```typescript
159
- const manager = new WSSubscriptionManager(handlers, {
160
- maxMarketsPerWS: 50, // Smaller groups for more granular control
161
- reconnectAndCleanupIntervalMs: 5000 // More frequent reconnection checks
162
- });
163
- ```
164
-
165
- ### Handling All Event Types
166
-
167
- ```typescript
168
- const comprehensiveHandlers: WebSocketHandlers = {
169
- onPolymarketPriceUpdate: async (events) => {
170
- // Primary price updates for UI display
171
- events.forEach(event => {
172
- updatePriceDisplay(event.asset_id, event.price);
173
- });
174
- },
175
-
176
- onBook: async (events) => {
177
- // Order book depth for trading interfaces
178
- events.forEach(event => {
179
- updateOrderBook(event.asset_id, event.bids, event.asks);
180
- });
181
- },
182
-
183
- onLastTradePrice: async (events) => {
184
- // Real-time trade feed
185
- events.forEach(event => {
186
- logTrade(event.asset_id, event.price, event.size, event.side);
187
- });
188
- },
189
-
190
- onWSOpen: async (groupId, assetIds) => {
191
- console.log(`Connected group ${groupId} with ${assetIds.length} assets`);
192
- },
193
-
194
- onWSClose: async (groupId, code, reason) => {
195
- console.log(`Disconnected group ${groupId}: ${reason} (${code})`);
196
- },
197
-
198
- onError: async (error) => {
199
- console.error('WebSocket error:', error);
200
- // Implement your error handling/alerting logic
201
- }
202
- };
203
- ```
204
-
205
149
  ## Examples
206
150
 
207
151
  Check the [examples](./examples) folder for complete working examples including:
@@ -211,10 +155,8 @@ Check the [examples](./examples) folder for complete working examples including:
211
155
 
212
156
  ## Error Handling
213
157
 
214
- The library includes comprehensive error handling:
158
+ The library includes error handling:
215
159
  - Automatic reconnection on connection drops
216
- - Rate limiting to prevent API blocking
217
- - Graceful handling of malformed messages
218
160
  - User-defined error callbacks for custom handling
219
161
 
220
162
  ## Rate Limits
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nevuamarkets/poly-websockets",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Plug-and-play Polymarket WebSocket price alerts",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -10,7 +10,7 @@
10
10
  ],
11
11
  "scripts": {
12
12
  "build": "tsc",
13
- "prepare": "npm run build",
13
+ "prepare": "npm run build && npm run test",
14
14
  "test": "vitest run"
15
15
  },
16
16
  "repository": {
@@ -19,10 +19,14 @@
19
19
  },
20
20
  "keywords": [
21
21
  "polymarket",
22
+ "polymarket-api",
22
23
  "websocket",
23
24
  "price",
24
25
  "market",
25
- "alerts"
26
+ "alerts",
27
+ "real-time",
28
+ "trading",
29
+ "prediction-markets"
26
30
  ],
27
31
  "author": "Konstantinos Lekkas",
28
32
  "license": "AGPL-3.0",
@@ -221,7 +221,7 @@ export type WebSocketHandlers = {
221
221
  and denotes the probability of an event happening. Read more about it here:
222
222
  https://docs.polymarket.com/polymarket-learn/trading/how-are-prices-calculated#future-price
223
223
 
224
- This is an aggregate event that is not emmited by the Polymarket WebSocket directly.
224
+ This is a derived event that is not emmited by the Polymarket WebSocket directly.
225
225
  */
226
226
  onPolymarketPriceUpdate?: (events: PolymarketPriceUpdateEvent[]) => Promise<void>;
227
227