binance 3.0.0-beta.4 → 3.0.0-beta.6

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.
Files changed (62) hide show
  1. package/README.md +305 -75
  2. package/lib/coinm-client.d.ts +0 -12
  3. package/lib/coinm-client.js +1 -13
  4. package/lib/coinm-client.js.map +1 -1
  5. package/lib/main-client.d.ts +0 -31
  6. package/lib/main-client.js +1 -32
  7. package/lib/main-client.js.map +1 -1
  8. package/lib/types/portfolio-margin.d.ts +0 -9
  9. package/lib/types/shared.d.ts +1 -1
  10. package/lib/types/websockets/ws-api-requests.d.ts +87 -45
  11. package/lib/types/websockets/ws-api-responses.d.ts +43 -43
  12. package/lib/types/websockets/ws-api.d.ts +84 -84
  13. package/lib/types/websockets/ws-events-formatted.d.ts +2 -0
  14. package/lib/types/websockets/ws-events-raw.d.ts +2 -0
  15. package/lib/types/websockets/ws-general.d.ts +1 -1
  16. package/lib/usdm-client.d.ts +0 -8
  17. package/lib/usdm-client.js +1 -13
  18. package/lib/usdm-client.js.map +1 -1
  19. package/lib/util/BaseRestClient.js +19 -5
  20. package/lib/util/BaseRestClient.js.map +1 -1
  21. package/lib/util/BaseWSClient.d.ts +12 -1
  22. package/lib/util/BaseWSClient.js +45 -6
  23. package/lib/util/BaseWSClient.js.map +1 -1
  24. package/lib/util/beautifier-maps.d.ts +8 -0
  25. package/lib/util/beautifier-maps.js +8 -0
  26. package/lib/util/beautifier-maps.js.map +1 -1
  27. package/lib/util/beautifier.js +0 -1
  28. package/lib/util/beautifier.js.map +1 -1
  29. package/lib/util/browser-support.js +0 -41
  30. package/lib/util/browser-support.js.map +1 -1
  31. package/lib/util/node-support.js +7 -5
  32. package/lib/util/node-support.js.map +1 -1
  33. package/lib/util/requestUtils.d.ts +13 -1
  34. package/lib/util/requestUtils.js +24 -1
  35. package/lib/util/requestUtils.js.map +1 -1
  36. package/lib/util/typeGuards.d.ts +3 -0
  37. package/lib/util/typeGuards.js +3 -1
  38. package/lib/util/typeGuards.js.map +1 -1
  39. package/lib/util/webCryptoAPI.js +19 -45
  40. package/lib/util/webCryptoAPI.js.map +1 -1
  41. package/lib/util/websockets/WsStore.js +6 -1
  42. package/lib/util/websockets/WsStore.js.map +1 -1
  43. package/lib/util/websockets/enum.d.ts +11 -0
  44. package/lib/util/websockets/enum.js +24 -0
  45. package/lib/util/websockets/enum.js.map +1 -0
  46. package/lib/util/websockets/rest-client-cache.d.ts +1 -1
  47. package/lib/util/websockets/rest-client-cache.js +5 -5
  48. package/lib/util/websockets/rest-client-cache.js.map +1 -1
  49. package/lib/util/websockets/user-data-stream-manager.js +3 -4
  50. package/lib/util/websockets/user-data-stream-manager.js.map +1 -1
  51. package/lib/util/websockets/websocket-util.d.ts +11 -1
  52. package/lib/util/websockets/websocket-util.js +26 -11
  53. package/lib/util/websockets/websocket-util.js.map +1 -1
  54. package/lib/websocket-api-client.d.ts +139 -68
  55. package/lib/websocket-api-client.js +212 -117
  56. package/lib/websocket-api-client.js.map +1 -1
  57. package/lib/websocket-client-legacy.js +7 -8
  58. package/lib/websocket-client-legacy.js.map +1 -1
  59. package/lib/websocket-client.d.ts +21 -9
  60. package/lib/websocket-client.js +81 -96
  61. package/lib/websocket-client.js.map +1 -1
  62. package/package.json +2 -2
@@ -35,65 +35,25 @@ function getFuturesMarketWsKey(market) {
35
35
  * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly:
36
36
  * https://github.com/tiagosiebler/binance/blob/wsapi/examples/ws-api-promises.ts#L52-L61
37
37
  */
38
- class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
38
+ class WebsocketAPIClient {
39
39
  constructor(options, logger) {
40
- super(options, logger);
41
40
  /**
42
41
  * Minimal state store around automating sticky "userDataStream.subscribe" sessions
43
42
  */
44
43
  this.subscribedUserDataStreamState = {};
45
- this.wsAPIClientOptions = Object.assign({ onReconnectResubscribeUserDataStream: false, resubscribeUserDataStreamDelaySeconds: 2 }, this.options);
46
- this.on('reconnected', ({ wsKey }) => {
47
- var _a;
48
- // Delay existing timer, if exists
49
- if (this.wsAPIClientOptions.onReconnectResubscribeUserDataStream &&
50
- (0, typeGuards_1.isWSAPIWsKey)(wsKey) &&
51
- this.subscribedUserDataStreamState[wsKey]) {
52
- if ((_a = this.subscribedUserDataStreamState[wsKey]) === null || _a === void 0 ? void 0 : _a.respawnTimeout) {
53
- clearTimeout(this.subscribedUserDataStreamState[wsKey].respawnTimeout);
54
- delete this.subscribedUserDataStreamState[wsKey].respawnTimeout;
55
- this.logger.error('tryResubscribeUserDataStream(): Respawn timer already active while trying to queue respawn...delaying existing timer further...', Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), { wsKey }));
56
- }
57
- this.logger.error('tryResubscribeUserDataStream(): queued resubscribe for wsKey user data stream', Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), { wsKey }));
58
- // Queue resubscribe workflow
59
- this.subscribedUserDataStreamState[wsKey].respawnTimeout = setTimeout(() => {
60
- this.tryResubscribeUserDataStream(wsKey);
61
- }, 1000 * this.wsAPIClientOptions.resubscribeUserDataStreamDelaySeconds);
62
- return;
63
- }
44
+ this.wsClient = new websocket_client_1.WebsocketClient(options, logger);
45
+ this.options = Object.assign({ resubscribeUserDataStreamAfterReconnect: true, resubscribeUserDataStreamDelaySeconds: 2, attachEventListeners: true }, options);
46
+ this.logger = this.wsClient.logger;
47
+ this.setupDefaultEventListeners();
48
+ this.wsClient.on('reconnected', ({ wsKey }) => {
49
+ this.handleWSReconnectedEvent({ wsKey });
64
50
  });
65
51
  }
66
- tryResubscribeUserDataStream(wsKey) {
67
- return __awaiter(this, void 0, void 0, function* () {
68
- var _a;
69
- const subscribeState = this.getSubscribedUserDataStreamState(wsKey);
70
- const respawnDelayInSeconds = this.wsAPIClientOptions.resubscribeUserDataStreamDelaySeconds;
71
- this.logger.error('tryResubscribeUserDataStream(): resubscribing to user data stream....', Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), { wsKey }));
72
- try {
73
- if ((_a = this.subscribedUserDataStreamState[wsKey]) === null || _a === void 0 ? void 0 : _a.respawnTimeout) {
74
- clearTimeout(this.subscribedUserDataStreamState[wsKey].respawnTimeout);
75
- delete this.subscribedUserDataStreamState[wsKey].respawnTimeout;
76
- }
77
- subscribeState.subscribeAttempt++;
78
- yield this.requestSubscribeUserDataStream(wsKey);
79
- this.subscribedUserDataStreamState[wsKey] = Object.assign(Object.assign({}, subscribeState), { subscribedAt: new Date(), subscribeAttempt: 0 });
80
- this.logger.info('tryResubscribeUserDataStream()->ok', Object.assign(Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), subscribeState), { wsKey }));
81
- }
82
- catch (e) {
83
- this.logger.error('tryResubscribeUserDataStream() exception - retry after timeout', Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), { wsKey, exception: e, subscribeState }));
84
- subscribeState.respawnTimeout = setTimeout(() => {
85
- this.tryResubscribeUserDataStream(wsKey);
86
- }, 1000 * respawnDelayInSeconds);
87
- this.subscribedUserDataStreamState[wsKey] = Object.assign({}, subscribeState);
88
- }
89
- });
52
+ getWSClient() {
53
+ return this.wsClient;
90
54
  }
91
- getSubscribedUserDataStreamState(wsKey) {
92
- const subscribedState = this.subscribedUserDataStreamState[wsKey] || {
93
- subscribedAt: new Date(),
94
- subscribeAttempt: 0,
95
- };
96
- return subscribedState;
55
+ setTimeOffsetMs(newOffset) {
56
+ return this.getWSClient().setTimeOffsetMs(newOffset);
97
57
  }
98
58
  /*
99
59
  *
@@ -104,22 +64,22 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
104
64
  * Test connectivity to the WebSocket API
105
65
  */
106
66
  testSpotConnectivity(wsKey) {
107
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ping');
67
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ping');
108
68
  }
109
69
  /**
110
70
  * Test connectivity to the WebSocket API and get the current server time
111
71
  */
112
72
  getSpotServerTime(wsKey) {
113
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'time');
73
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'time');
114
74
  }
115
75
  /**
116
76
  * Query current exchange trading rules, rate limits, and symbol information
117
77
  */
118
78
  getSpotExchangeInfo(params, wsKey) {
119
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'exchangeInfo', params);
79
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'exchangeInfo', params);
120
80
  }
121
81
  getSpotSessionStatus(wsKey) {
122
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'session.status');
82
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'session.status');
123
83
  }
124
84
  /*
125
85
  *
@@ -131,82 +91,82 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
131
91
  * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams
132
92
  */
133
93
  getSpotOrderBook(params, wsKey) {
134
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'depth', params);
94
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'depth', params);
135
95
  }
136
96
  /**
137
97
  * Get recent trades
138
98
  * Note: If you need access to real-time trading activity, consider using WebSocket Streams
139
99
  */
140
100
  getSpotRecentTrades(params, wsKey) {
141
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'trades.recent', params);
101
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'trades.recent', params);
142
102
  }
143
103
  /**
144
104
  * Get historical trades
145
105
  * Note: If fromId is not specified, the most recent trades are returned
146
106
  */
147
107
  getSpotHistoricalTrades(params, wsKey) {
148
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'trades.historical', params);
108
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'trades.historical', params);
149
109
  }
150
110
  /**
151
111
  * Get aggregate trades
152
112
  * Note: An aggregate trade represents one or more individual trades that fill at the same time
153
113
  */
154
114
  getSpotAggregateTrades(params, wsKey) {
155
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'trades.aggregate', params);
115
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'trades.aggregate', params);
156
116
  }
157
117
  /**
158
118
  * Get klines (candlestick bars)
159
119
  * Note: If you need access to real-time kline updates, consider using WebSocket Streams
160
120
  */
161
121
  getSpotKlines(params, wsKey) {
162
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'klines', params);
122
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'klines', params);
163
123
  }
164
124
  /**
165
125
  * Get klines (candlestick bars) optimized for presentation
166
126
  * Note: This request is similar to klines, having the same parameters and response
167
127
  */
168
128
  getSpotUIKlines(params, wsKey) {
169
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'uiKlines', params);
129
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'uiKlines', params);
170
130
  }
171
131
  /**
172
132
  * Get current average price for a symbol
173
133
  */
174
134
  getSpotAveragePrice(params, wsKey) {
175
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'avgPrice', params);
135
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'avgPrice', params);
176
136
  }
177
137
  /**
178
138
  * Get 24-hour rolling window price change statistics
179
139
  * Note: If you need to continuously monitor trading statistics, consider using WebSocket Streams
180
140
  */
181
141
  getSpot24hrTicker(params, wsKey) {
182
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker.24hr', params);
142
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker.24hr', params);
183
143
  }
184
144
  /**
185
145
  * Get price change statistics for a trading day
186
146
  */
187
147
  getSpotTradingDayTicker(params, wsKey) {
188
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker.tradingDay', params);
148
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker.tradingDay', params);
189
149
  }
190
150
  /**
191
151
  * Get rolling window price change statistics with a custom window
192
152
  * Note: Window size precision is limited to 1 minute
193
153
  */
194
154
  getSpotTicker(params, wsKey) {
195
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker', params);
155
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker', params);
196
156
  }
197
157
  /**
198
158
  * Get the latest market price for a symbol
199
159
  * Note: If you need access to real-time price updates, consider using WebSocket Streams
200
160
  */
201
161
  getSpotSymbolPriceTicker(params, wsKey) {
202
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker.price', params);
162
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker.price', params);
203
163
  }
204
164
  /**
205
165
  * Get the current best price and quantity on the order book
206
166
  * Note: If you need access to real-time order book ticker updates, consider using WebSocket Streams
207
167
  */
208
168
  getSpotSymbolOrderBookTicker(params, wsKey) {
209
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker.book', params);
169
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'ticker.book', params);
210
170
  }
211
171
  /*
212
172
  *
@@ -217,112 +177,112 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
217
177
  * Submit a spot order
218
178
  */
219
179
  submitNewSpotOrder(params, wsKey) {
220
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.place', params);
180
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.place', params);
221
181
  }
222
182
  /**
223
183
  * Test order placement
224
184
  * Note: Validates new order parameters and verifies your signature but does not send the order into the matching engine
225
185
  */
226
186
  testSpotOrder(params, wsKey) {
227
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.test', params);
187
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.test', params);
228
188
  }
229
189
  /**
230
190
  * Check execution status of an order
231
191
  * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used
232
192
  */
233
193
  getSpotOrderStatus(params, wsKey) {
234
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.status', params);
194
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.status', params);
235
195
  }
236
196
  /**
237
197
  * Cancel an active order
238
198
  * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used
239
199
  */
240
200
  cancelSpotOrder(params, wsKey) {
241
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.cancel', params);
201
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.cancel', params);
242
202
  }
243
203
  /**
244
204
  * Cancel an existing order and immediately place a new order
245
205
  * Note: If both cancelOrderId and cancelOrigClientOrderId parameters are specified, only cancelOrderId is used
246
206
  */
247
207
  cancelReplaceSpotOrder(params, wsKey) {
248
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.cancelReplace', params);
208
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'order.cancelReplace', params);
249
209
  }
250
210
  /**
251
211
  * Query execution status of all open orders
252
212
  * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams
253
213
  */
254
214
  getSpotOpenOrders(params, wsKey) {
255
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'openOrders.status', params);
215
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'openOrders.status', params);
256
216
  }
257
217
  /**
258
218
  * Cancel all open orders on a symbol
259
219
  * Note: This includes orders that are part of an order list
260
220
  */
261
221
  cancelAllSpotOpenOrders(params, wsKey) {
262
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'openOrders.cancelAll', params);
222
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'openOrders.cancelAll', params);
263
223
  }
264
224
  /**
265
225
  * Place a new order list
266
226
  * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead
267
227
  */
268
228
  placeSpotOrderList(params, wsKey) {
269
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.place', params);
229
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.place', params);
270
230
  }
271
231
  /**
272
232
  * Place a new OCO (One-Cancels-the-Other) order list
273
233
  * Note: Activation of one order immediately cancels the other
274
234
  */
275
235
  placeSpotOCOOrderList(params, wsKey) {
276
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.place.oco', params);
236
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.place.oco', params);
277
237
  }
278
238
  /**
279
239
  * Place a new OTO (One-Triggers-the-Other) order list
280
240
  * Note: The pending order is placed only when the working order is fully filled
281
241
  */
282
242
  placeSpotOTOOrderList(params, wsKey) {
283
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.place.oto', params);
243
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.place.oto', params);
284
244
  }
285
245
  /**
286
246
  * Place a new OTOCO (One-Triggers-One-Cancels-the-Other) order list
287
247
  * Note: The pending orders are placed only when the working order is fully filled
288
248
  */
289
249
  placeSpotOTOCOOrderList(params, wsKey) {
290
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.place.otoco', params);
250
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.place.otoco', params);
291
251
  }
292
252
  /**
293
253
  * Check execution status of an order list
294
254
  * Note: If both origClientOrderId and orderListId parameters are specified, only origClientOrderId is used
295
255
  */
296
256
  getSpotOrderListStatus(params, wsKey) {
297
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.status', params);
257
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.status', params);
298
258
  }
299
259
  /**
300
260
  * Cancel an active order list
301
261
  * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used
302
262
  */
303
263
  cancelSpotOrderList(params, wsKey) {
304
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.cancel', params);
264
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'orderList.cancel', params);
305
265
  }
306
266
  /**
307
267
  * Query execution status of all open order lists
308
268
  * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams
309
269
  */
310
270
  getSpotOpenOrderLists(params, wsKey) {
311
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'openOrderLists.status', params);
271
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'openOrderLists.status', params);
312
272
  }
313
273
  /**
314
274
  * Place a new order using Smart Order Routing (SOR)
315
275
  * Note: Only supports LIMIT and MARKET orders. quoteOrderQty is not supported
316
276
  */
317
277
  placeSpotSOROrder(params, wsKey) {
318
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'sor.order.place', params);
278
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'sor.order.place', params);
319
279
  }
320
280
  /**
321
281
  * Test new order creation and signature/recvWindow using Smart Order Routing (SOR)
322
282
  * Note: Creates and validates a new order but does not send it into the matching engine
323
283
  */
324
284
  testSpotSOROrder(params, wsKey) {
325
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'sor.order.test', params);
285
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'sor.order.test', params);
326
286
  }
327
287
  /*
328
288
  *
@@ -334,56 +294,56 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
334
294
  * Note: Weight: 20
335
295
  */
336
296
  getSpotAccountStatus(params, wsKey) {
337
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'account.status', params);
297
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'account.status', params);
338
298
  }
339
299
  /**
340
300
  * Query your current unfilled order count for all intervals
341
301
  * Note: Weight: 40
342
302
  */
343
303
  getSpotOrderRateLimits(params, wsKey) {
344
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'account.rateLimits.orders', params);
304
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'account.rateLimits.orders', params);
345
305
  }
346
306
  /**
347
307
  * Query information about all your orders – active, canceled, filled – filtered by time range
348
308
  * Note: Weight: 20
349
309
  */
350
310
  getSpotAllOrders(params, wsKey) {
351
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'allOrders', params);
311
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'allOrders', params);
352
312
  }
353
313
  /**
354
314
  * Query information about all your order lists, filtered by time range
355
315
  * Note: Weight: 20
356
316
  */
357
317
  getSpotAllOrderLists(params, wsKey) {
358
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'allOrderLists', params);
318
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'allOrderLists', params);
359
319
  }
360
320
  /**
361
321
  * Query information about all your trades, filtered by time range
362
322
  * Note: Weight: 20
363
323
  */
364
324
  getSpotMyTrades(params, wsKey) {
365
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'myTrades', params);
325
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'myTrades', params);
366
326
  }
367
327
  /**
368
328
  * Displays the list of orders that were expired due to STP
369
329
  * Note: Weight varies based on query type (2-20)
370
330
  */
371
331
  getSpotPreventedMatches(params, wsKey) {
372
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'myPreventedMatches', params);
332
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'myPreventedMatches', params);
373
333
  }
374
334
  /**
375
335
  * Retrieves allocations resulting from SOR order placement
376
336
  * Note: Weight: 20
377
337
  */
378
338
  getSpotAllocations(params, wsKey) {
379
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'myAllocations', params);
339
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'myAllocations', params);
380
340
  }
381
341
  /**
382
342
  * Get current account commission rates
383
343
  * Note: Weight: 20
384
344
  */
385
345
  getSpotAccountCommission(params, wsKey) {
386
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'account.commission', params);
346
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'account.commission', params);
387
347
  }
388
348
  /*
389
349
  *
@@ -395,21 +355,21 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
395
355
  * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams
396
356
  */
397
357
  getFuturesOrderBook(params) {
398
- return this.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'depth', params);
358
+ return this.wsClient.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'depth', params);
399
359
  }
400
360
  /**
401
361
  * Get latest price for a futures symbol or symbols
402
362
  * Note: If symbol is not provided, prices for all symbols will be returned
403
363
  */
404
364
  getFuturesSymbolPriceTicker(params) {
405
- return this.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'ticker.price', params);
365
+ return this.wsClient.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'ticker.price', params);
406
366
  }
407
367
  /**
408
368
  * Get best price/qty on the order book for a futures symbol or symbols
409
369
  * Note: If symbol is not provided, bookTickers for all symbols will be returned
410
370
  */
411
371
  getFuturesSymbolOrderBookTicker(params) {
412
- return this.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'ticker.book', params);
372
+ return this.wsClient.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'ticker.book', params);
413
373
  }
414
374
  /*
415
375
  *
@@ -422,7 +382,7 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
422
382
  * This endpoint is used for both USDM and COINM futures.
423
383
  */
424
384
  submitNewFuturesOrder(market, params) {
425
- return this.sendWSAPIRequest(getFuturesMarketWsKey(market), 'order.place', params);
385
+ return this.wsClient.sendWSAPIRequest(getFuturesMarketWsKey(market), 'order.place', params);
426
386
  }
427
387
  /**
428
388
  * Modify an existing futures order
@@ -430,7 +390,7 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
430
390
  * This endpoint is used for both USDM and COINM futures.
431
391
  */
432
392
  modifyFuturesOrder(market, params) {
433
- return this.sendWSAPIRequest(getFuturesMarketWsKey(market), 'order.modify', params);
393
+ return this.wsClient.sendWSAPIRequest(getFuturesMarketWsKey(market), 'order.modify', params);
434
394
  }
435
395
  /**
436
396
  * Cancel a futures order
@@ -438,7 +398,7 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
438
398
  * This endpoint is used for both USDM and COINM futures.
439
399
  */
440
400
  cancelFuturesOrder(market, params) {
441
- return this.sendWSAPIRequest(getFuturesMarketWsKey(market), 'order.cancel', params);
401
+ return this.wsClient.sendWSAPIRequest(getFuturesMarketWsKey(market), 'order.cancel', params);
442
402
  }
443
403
  /**
444
404
  * Query futures order status
@@ -446,14 +406,14 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
446
406
  * This endpoint is used for both USDM and COINM futures.
447
407
  */
448
408
  getFuturesOrderStatus(market, params) {
449
- return this.sendWSAPIRequest(getFuturesMarketWsKey(market), 'order.status', params);
409
+ return this.wsClient.sendWSAPIRequest(getFuturesMarketWsKey(market), 'order.status', params);
450
410
  }
451
411
  /**
452
412
  * Get current position information (V2)
453
413
  * Note: Only symbols that have positions or open orders will be returned
454
414
  */
455
415
  getFuturesPositionV2(params) {
456
- return this.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'v2/account.position', params);
416
+ return this.wsClient.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'v2/account.position', params);
457
417
  }
458
418
  /**
459
419
  * Get current position information
@@ -462,7 +422,7 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
462
422
  * This endpoint is used for both USDM and COINM futures.
463
423
  */
464
424
  getFuturesPosition(market, params) {
465
- return this.sendWSAPIRequest(getFuturesMarketWsKey(market), 'account.position', params);
425
+ return this.wsClient.sendWSAPIRequest(getFuturesMarketWsKey(market), 'account.position', params);
466
426
  }
467
427
  /*
468
428
  *
@@ -474,7 +434,7 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
474
434
  * Note: Returns balance information for all assets
475
435
  */
476
436
  getFuturesAccountBalanceV2(params) {
477
- return this.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'v2/account.balance', params);
437
+ return this.wsClient.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'v2/account.balance', params);
478
438
  }
479
439
  /**
480
440
  * Get account balance information
@@ -483,14 +443,14 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
483
443
  * This endpoint is used for both USDM and COINM futures.
484
444
  */
485
445
  getFuturesAccountBalance(market, params) {
486
- return this.sendWSAPIRequest(getFuturesMarketWsKey(market), 'account.balance', params);
446
+ return this.wsClient.sendWSAPIRequest(getFuturesMarketWsKey(market), 'account.balance', params);
487
447
  }
488
448
  /**
489
449
  * Get account information (V2)
490
450
  * Note: Returns detailed account information including positions and assets
491
451
  */
492
452
  getFuturesAccountStatusV2(params) {
493
- return this.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'v2/account.status', params);
453
+ return this.wsClient.sendWSAPIRequest(websocket_util_1.WS_KEY_MAP.usdmWSAPI, 'v2/account.status', params);
494
454
  }
495
455
  /**
496
456
  * Get account information
@@ -499,38 +459,173 @@ class WebsocketAPIClient extends websocket_client_1.WebsocketClient {
499
459
  * This endpoint is used for both USDM and COINM futures.
500
460
  */
501
461
  getFuturesAccountStatus(market, params) {
502
- return this.sendWSAPIRequest(getFuturesMarketWsKey(market), 'account.status', params);
462
+ return this.wsClient.sendWSAPIRequest(getFuturesMarketWsKey(market), 'account.status', params);
503
463
  }
504
464
  /*
505
465
  *
506
466
  * User data stream requests
507
467
  *
508
468
  */
509
- startSpotUserDataStream(params, wsKey) {
510
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'userDataStream.start', params);
469
+ /**
470
+ * Start the user data stream for an apiKey (passed as param).
471
+ *
472
+ * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead.
473
+ *
474
+ * @param params
475
+ * @param wsKey
476
+ * @returns listenKey
477
+ */
478
+ startUserDataStreamForKey(params, wsKey = websocket_util_1.WS_KEY_MAP.mainWSAPI) {
479
+ return this.wsClient.sendWSAPIRequest(wsKey, 'userDataStream.start', params);
511
480
  }
512
- pingSpotUserDataStream(params, wsKey) {
513
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'userDataStream.ping', params);
481
+ /**
482
+ * Attempt to "ping" a listen key.
483
+ *
484
+ * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead.
485
+ *
486
+ * @param params
487
+ * @param wsKey
488
+ * @returns
489
+ */
490
+ pingUserDataStreamForKey(params, wsKey = websocket_util_1.WS_KEY_MAP.mainWSAPI) {
491
+ return this.wsClient.sendWSAPIRequest(wsKey, 'userDataStream.ping', params);
514
492
  }
515
- stopSpotUserDataStream(params, wsKey) {
516
- return this.sendWSAPIRequest(wsKey || websocket_util_1.WS_KEY_MAP.mainWSAPI, 'userDataStream.stop', params);
493
+ /**
494
+ * Stop the user data stream listen key.
495
+ *
496
+ * @param params
497
+ * @param wsKey
498
+ * @returns
499
+ */
500
+ stopUserDataStreamForKey(params, wsKey = websocket_util_1.WS_KEY_MAP.mainWSAPI) {
501
+ return this.wsClient.sendWSAPIRequest(wsKey, 'userDataStream.stop', params);
517
502
  }
518
503
  /**
519
- * Request user data stream subscription on the currently authenticated connection
504
+ * Request user data stream subscription on the currently authenticated connection.
505
+ *
506
+ * If reconnected, this will automatically resubscribe unless you unsubscribe manually.
520
507
  */
521
- requestSubscribeUserDataStream(wsKey) {
508
+ subscribeUserDataStream(wsKey) {
522
509
  return __awaiter(this, void 0, void 0, function* () {
523
- const res = yield this.sendWSAPIRequest(wsKey, 'userDataStream.subscribe');
524
- this.subscribedUserDataStreamState[wsKey] = {
510
+ const resolvedWsKey = this.options.testnet ? (0, websocket_util_1.getTestnetWsKey)(wsKey) : wsKey;
511
+ const res = yield this.wsClient.sendWSAPIRequest(resolvedWsKey, 'userDataStream.subscribe');
512
+ // Used to track whether this connection had the general "userDataStream.subscribe" called.
513
+ // Used as part of `resubscribeUserDataStreamAfterReconnect` to know which connections to resub.
514
+ this.subscribedUserDataStreamState[resolvedWsKey] = {
525
515
  subscribedAt: new Date(),
526
516
  subscribeAttempt: 0,
527
517
  };
528
518
  return res;
529
519
  });
530
520
  }
531
- requestUnsubscribeUserDataStream(wsKey) {
532
- delete this.subscribedUserDataStreamState[wsKey];
533
- return this.sendWSAPIRequest(wsKey, 'userDataStream.unsubscribe');
521
+ /**
522
+ * Unsubscribe from the user data stream subscription on the currently authenticated connection.
523
+ *
524
+ * If reconnected, this will also stop it from automatically resubscribing after reconnect.
525
+ */
526
+ unsubscribeUserDataStream(wsKey) {
527
+ const resolvedWsKey = this.options.testnet ? (0, websocket_util_1.getTestnetWsKey)(wsKey) : wsKey;
528
+ delete this.subscribedUserDataStreamState[resolvedWsKey];
529
+ return this.wsClient.sendWSAPIRequest(resolvedWsKey, 'userDataStream.unsubscribe');
530
+ }
531
+ /**
532
+ *
533
+ *
534
+ *
535
+ *
536
+ *
537
+ *
538
+ *
539
+ * Private methods for handling some of the convenience/automation provided by the WS API Client
540
+ *
541
+ *
542
+ *
543
+ *
544
+ *
545
+ *
546
+ *
547
+ */
548
+ setupDefaultEventListeners() {
549
+ if (this.options.attachEventListeners) {
550
+ /**
551
+ * General event handlers for monitoring the WebsocketClient
552
+ */
553
+ this.wsClient
554
+ .on('open', (data) => {
555
+ console.log(new Date(), 'ws connected', data.wsKey);
556
+ })
557
+ .on('reconnecting', ({ wsKey }) => {
558
+ console.log(new Date(), 'ws automatically reconnecting.... ', wsKey);
559
+ })
560
+ .on('reconnected', (data) => {
561
+ console.log(new Date(), 'ws has reconnected ', data === null || data === void 0 ? void 0 : data.wsKey);
562
+ })
563
+ .on('authenticated', (data) => {
564
+ console.info(new Date(), 'ws has authenticated ', data === null || data === void 0 ? void 0 : data.wsKey);
565
+ })
566
+ .on('exception', (data) => {
567
+ console.error(new Date(), 'ws exception: ', JSON.stringify(data));
568
+ });
569
+ }
570
+ }
571
+ tryResubscribeUserDataStream(wsKey) {
572
+ return __awaiter(this, void 0, void 0, function* () {
573
+ var _a;
574
+ const subscribeState = this.getSubscribedUserDataStreamState(wsKey);
575
+ const respawnDelayInSeconds = this.options.resubscribeUserDataStreamDelaySeconds;
576
+ this.logger.error('tryResubscribeUserDataStream(): resubscribing to user data stream....', Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), { wsKey }));
577
+ try {
578
+ if ((_a = this.subscribedUserDataStreamState[wsKey]) === null || _a === void 0 ? void 0 : _a.respawnTimeout) {
579
+ clearTimeout(this.subscribedUserDataStreamState[wsKey].respawnTimeout);
580
+ delete this.subscribedUserDataStreamState[wsKey].respawnTimeout;
581
+ }
582
+ subscribeState.subscribeAttempt++;
583
+ yield this.subscribeUserDataStream(wsKey);
584
+ this.subscribedUserDataStreamState[wsKey] = Object.assign(Object.assign({}, subscribeState), { subscribedAt: new Date(), subscribeAttempt: 0 });
585
+ this.logger.info('tryResubscribeUserDataStream()->ok', Object.assign(Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), subscribeState), { wsKey }));
586
+ }
587
+ catch (e) {
588
+ this.logger.error('tryResubscribeUserDataStream() exception - retry after timeout', Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), { wsKey, exception: e, subscribeState }));
589
+ subscribeState.respawnTimeout = setTimeout(() => {
590
+ this.tryResubscribeUserDataStream(wsKey);
591
+ }, 1000 * respawnDelayInSeconds);
592
+ this.subscribedUserDataStreamState[wsKey] = Object.assign({}, subscribeState);
593
+ }
594
+ });
595
+ }
596
+ getSubscribedUserDataStreamState(wsKey) {
597
+ const subscribedState = this.subscribedUserDataStreamState[wsKey] || {
598
+ subscribedAt: new Date(),
599
+ subscribeAttempt: 0,
600
+ };
601
+ return subscribedState;
602
+ }
603
+ handleWSReconnectedEvent(params) {
604
+ var _a;
605
+ const wsKey = params.wsKey;
606
+ // Not a WS API connection
607
+ if (!(0, typeGuards_1.isWSAPIWsKey)(wsKey)) {
608
+ return;
609
+ }
610
+ const fnName = 'handleWSReconnectedEvent()';
611
+ // For the workflow without the listen key
612
+ if (
613
+ // Feature enabled
614
+ this.options.resubscribeUserDataStreamAfterReconnect &&
615
+ // Was subscribed to user data stream (without listen key)
616
+ this.subscribedUserDataStreamState[wsKey]) {
617
+ // Delay existing timer, if exists
618
+ if ((_a = this.subscribedUserDataStreamState[wsKey]) === null || _a === void 0 ? void 0 : _a.respawnTimeout) {
619
+ clearTimeout(this.subscribedUserDataStreamState[wsKey].respawnTimeout);
620
+ delete this.subscribedUserDataStreamState[wsKey].respawnTimeout;
621
+ this.logger.error(`${fnName} -> resubUserData(): Respawn timer already active while trying to queue respawn...delaying existing timer further...`, Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), { wsKey }));
622
+ }
623
+ this.logger.trace(`${fnName} -> resubUserData():: queued resubscribe for wsKey user data stream`, Object.assign(Object.assign({}, websocket_util_1.WS_LOGGER_CATEGORY), { wsKey }));
624
+ // Queue resubscribe workflow
625
+ this.subscribedUserDataStreamState[wsKey].respawnTimeout = setTimeout(() => {
626
+ this.tryResubscribeUserDataStream(wsKey);
627
+ }, 1000 * this.options.resubscribeUserDataStreamDelaySeconds);
628
+ }
534
629
  }
535
630
  }
536
631
  exports.WebsocketAPIClient = WebsocketAPIClient;