kucoin-api 2.1.23 → 2.2.0

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 (98) hide show
  1. package/README.md +111 -14
  2. package/dist/cjs/WebsocketAPIClient.d.ts +123 -0
  3. package/dist/cjs/WebsocketAPIClient.js +147 -0
  4. package/dist/cjs/WebsocketAPIClient.js.map +1 -0
  5. package/dist/cjs/WebsocketClient.d.ts +14 -9
  6. package/dist/cjs/WebsocketClient.js +277 -37
  7. package/dist/cjs/WebsocketClient.js.map +1 -1
  8. package/dist/cjs/index.d.ts +4 -3
  9. package/dist/cjs/index.js +4 -3
  10. package/dist/cjs/index.js.map +1 -1
  11. package/dist/cjs/lib/BaseRestClient.d.ts +16 -0
  12. package/dist/cjs/lib/BaseRestClient.js +46 -12
  13. package/dist/cjs/lib/BaseRestClient.js.map +1 -1
  14. package/dist/cjs/lib/BaseWSClient.d.ts +30 -17
  15. package/dist/cjs/lib/BaseWSClient.js +248 -55
  16. package/dist/cjs/lib/BaseWSClient.js.map +1 -1
  17. package/dist/cjs/lib/requestUtils.d.ts +11 -0
  18. package/dist/cjs/lib/requestUtils.js.map +1 -1
  19. package/dist/cjs/lib/websocket/WsStore.d.ts +15 -3
  20. package/dist/cjs/lib/websocket/WsStore.js +61 -12
  21. package/dist/cjs/lib/websocket/WsStore.js.map +1 -1
  22. package/dist/cjs/lib/websocket/WsStore.types.d.ts +6 -4
  23. package/dist/cjs/lib/websocket/WsStore.types.js +2 -2
  24. package/dist/cjs/lib/websocket/WsStore.types.js.map +1 -1
  25. package/dist/cjs/lib/websocket/logger.d.ts +1 -0
  26. package/dist/cjs/lib/websocket/websocket-util.d.ts +12 -6
  27. package/dist/cjs/lib/websocket/websocket-util.js +17 -8
  28. package/dist/cjs/lib/websocket/websocket-util.js.map +1 -1
  29. package/dist/cjs/types/request/futures.types.d.ts +1 -0
  30. package/dist/cjs/types/websockets/ws-api.d.ts +123 -0
  31. package/dist/cjs/types/websockets/ws-api.js +22 -0
  32. package/dist/cjs/types/websockets/ws-api.js.map +1 -0
  33. package/dist/cjs/types/websockets/ws-events.d.ts +11 -0
  34. package/dist/cjs/types/websockets/ws-events.js +11 -0
  35. package/dist/cjs/types/websockets/ws-events.js.map +1 -0
  36. package/dist/cjs/types/websockets/{client.d.ts → ws-general.d.ts} +5 -0
  37. package/dist/cjs/types/websockets/{events.js → ws-general.js} +1 -1
  38. package/dist/cjs/types/websockets/ws-general.js.map +1 -0
  39. package/dist/mjs/WebsocketAPIClient.d.ts +123 -0
  40. package/dist/mjs/WebsocketAPIClient.js +143 -0
  41. package/dist/mjs/WebsocketAPIClient.js.map +1 -0
  42. package/dist/mjs/WebsocketClient.d.ts +14 -9
  43. package/dist/mjs/WebsocketClient.js +278 -38
  44. package/dist/mjs/WebsocketClient.js.map +1 -1
  45. package/dist/mjs/index.d.ts +4 -3
  46. package/dist/mjs/index.js +4 -3
  47. package/dist/mjs/index.js.map +1 -1
  48. package/dist/mjs/lib/BaseRestClient.d.ts +16 -0
  49. package/dist/mjs/lib/BaseRestClient.js +47 -13
  50. package/dist/mjs/lib/BaseRestClient.js.map +1 -1
  51. package/dist/mjs/lib/BaseWSClient.d.ts +30 -17
  52. package/dist/mjs/lib/BaseWSClient.js +248 -55
  53. package/dist/mjs/lib/BaseWSClient.js.map +1 -1
  54. package/dist/mjs/lib/requestUtils.d.ts +11 -0
  55. package/dist/mjs/lib/requestUtils.js.map +1 -1
  56. package/dist/mjs/lib/websocket/WsStore.d.ts +15 -3
  57. package/dist/mjs/lib/websocket/WsStore.js +61 -12
  58. package/dist/mjs/lib/websocket/WsStore.js.map +1 -1
  59. package/dist/mjs/lib/websocket/WsStore.types.d.ts +6 -4
  60. package/dist/mjs/lib/websocket/WsStore.types.js +2 -2
  61. package/dist/mjs/lib/websocket/WsStore.types.js.map +1 -1
  62. package/dist/mjs/lib/websocket/logger.d.ts +1 -0
  63. package/dist/mjs/lib/websocket/websocket-util.d.ts +12 -6
  64. package/dist/mjs/lib/websocket/websocket-util.js +15 -7
  65. package/dist/mjs/lib/websocket/websocket-util.js.map +1 -1
  66. package/dist/mjs/types/request/futures.types.d.ts +1 -0
  67. package/dist/mjs/types/websockets/ws-api.d.ts +123 -0
  68. package/dist/mjs/types/websockets/ws-api.js +19 -0
  69. package/dist/mjs/types/websockets/ws-api.js.map +1 -0
  70. package/dist/mjs/types/websockets/ws-events.d.ts +11 -0
  71. package/dist/mjs/types/websockets/ws-events.js +8 -0
  72. package/dist/mjs/types/websockets/ws-events.js.map +1 -0
  73. package/dist/mjs/types/websockets/{client.d.ts → ws-general.d.ts} +5 -0
  74. package/dist/mjs/types/websockets/ws-general.js +2 -0
  75. package/dist/mjs/types/websockets/ws-general.js.map +1 -0
  76. package/llms.txt +5985 -4979
  77. package/package.json +6 -4
  78. package/dist/cjs/types/websockets/client.js +0 -3
  79. package/dist/cjs/types/websockets/client.js.map +0 -1
  80. package/dist/cjs/types/websockets/events.d.ts +0 -5
  81. package/dist/cjs/types/websockets/events.js.map +0 -1
  82. package/dist/cjs/types/websockets/requests.d.ts +0 -8
  83. package/dist/cjs/types/websockets/requests.js +0 -3
  84. package/dist/cjs/types/websockets/requests.js.map +0 -1
  85. package/dist/cjs/types/websockets/wsAPI.d.ts +0 -9
  86. package/dist/cjs/types/websockets/wsAPI.js +0 -3
  87. package/dist/cjs/types/websockets/wsAPI.js.map +0 -1
  88. package/dist/mjs/types/websockets/client.js +0 -2
  89. package/dist/mjs/types/websockets/client.js.map +0 -1
  90. package/dist/mjs/types/websockets/events.d.ts +0 -5
  91. package/dist/mjs/types/websockets/events.js +0 -2
  92. package/dist/mjs/types/websockets/events.js.map +0 -1
  93. package/dist/mjs/types/websockets/requests.d.ts +0 -8
  94. package/dist/mjs/types/websockets/requests.js +0 -2
  95. package/dist/mjs/types/websockets/requests.js.map +0 -1
  96. package/dist/mjs/types/websockets/wsAPI.d.ts +0 -9
  97. package/dist/mjs/types/websockets/wsAPI.js +0 -2
  98. package/dist/mjs/types/websockets/wsAPI.js.map +0 -1
package/README.md CHANGED
@@ -1,4 +1,11 @@
1
- # Node.js & JavaScript SDK for Kucoin REST APIs & Websockets
1
+ # Node.js & JavaScript SDK for Kucoin REST APIs, Websockets & WebSocket API
2
+
3
+ [![Build & Test](https://github.com/tiagosiebler/kucoin-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/kucoin-api/actions/workflows/e2etest.yml)
4
+ [![npm version](https://img.shields.io/npm/v/kucoin-api)][1]
5
+ [![npm size](https://img.shields.io/bundlephobia/min/kucoin-api/latest)][1]
6
+ [![npm downloads](https://img.shields.io/npm/dt/kucoin-api)][1]
7
+ [![last commit](https://img.shields.io/github/last-commit/tiagosiebler/kucoin-api)][1]
8
+ [![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders)
2
9
 
3
10
  <p align="center">
4
11
  <a href="https://www.npmjs.com/package/kucoin-api">
@@ -9,13 +16,6 @@
9
16
  </a>
10
17
  </p>
11
18
 
12
- [![npm version](https://img.shields.io/npm/v/kucoin-api)][1]
13
- [![npm size](https://img.shields.io/bundlephobia/min/kucoin-api/latest)][1]
14
- [![npm downloads](https://img.shields.io/npm/dt/kucoin-api)][1]
15
- [![Build & Test](https://github.com/tiagosiebler/kucoin-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/kucoin-api/actions/workflows/e2etest.yml)
16
- [![last commit](https://img.shields.io/github/last-commit/tiagosiebler/kucoin-api)][1]
17
- [![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders)
18
-
19
19
  [1]: https://www.npmjs.com/package/kucoin-api
20
20
 
21
21
  Updated & performant JavaScript & Node.js SDK for the Kucoin REST APIs and WebSockets:
@@ -24,6 +24,7 @@ Updated & performant JavaScript & Node.js SDK for the Kucoin REST APIs and WebSo
24
24
  - Complete integration with all Kucoin REST APIs and WebSockets.
25
25
  - Dedicated REST clients for Spot, Futures, and Broker operations
26
26
  - Unified WebSocket client for all markets
27
+ - Dedicated WebSocket API client, to trade on the WebSocket API without the complexity of WebSockets.
27
28
  - Complete TypeScript support (with type declarations for most API requests & responses).
28
29
  - Strongly typed requests and responses.
29
30
  - Automated end-to-end tests ensuring reliability.
@@ -33,6 +34,9 @@ Updated & performant JavaScript & Node.js SDK for the Kucoin REST APIs and WebSo
33
34
  - Smart WebSocket persistence with automatic reconnection handling.
34
35
  - Emit `reconnected` event when dropped connection is restored.
35
36
  - Support for both public and private WebSocket streams.
37
+ - Supports WebSocket API on all available product groups, including Spot & Futures:
38
+ - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or;
39
+ - Use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/WebSockets/ws-api-client.ts](./examples/WebSockets/ws-api-client.ts) for a demonstration.
36
40
  - Browser-friendly HMAC signature mechanism.
37
41
  - Automatically supports both ESM and CJS projects.
38
42
  - Heavy automated end-to-end testing with real API calls.
@@ -52,9 +56,13 @@ Updated & performant JavaScript & Node.js SDK for the Kucoin REST APIs and WebSo
52
56
  - [Spot & Margin Trading](#spot--margin-trading)
53
57
  - [Futures Trading](#futures-trading)
54
58
  - [Broker Operations](#broker-operations)
55
- - [WebSocket Client](#websockets)
56
- - [Public WebSocket Streams](#public-websocket-streams)
57
- - [Private WebSocket Streams](#private-websocket-streams)
59
+ - [WebSockets](#websockets)
60
+ - [WebSocket Consumers](#websocket-consumers)
61
+ - [Public WebSocket Streams](#public-websocket-streams)
62
+ - [Private WebSocket Streams](#private-websocket-streams)
63
+ - [WebSocket API](#websocket-api)
64
+ - [Event Driven API](#event-driven-api)
65
+ - [Promise Driven API](#async-await-api)
58
66
  - [Customise Logging](#customise-logging)
59
67
  - [LLMs & AI](#use-with-llms--ai)
60
68
  - [Used By](#used-by)
@@ -194,7 +202,11 @@ Key WebSocket features:
194
202
  - Support for both public and private WebSocket streams
195
203
  - Unified client for spot and futures markets
196
204
 
197
- ### Public WebSocket Streams
205
+ ### WebSocket Consumers
206
+
207
+ All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required.
208
+
209
+ #### Public WebSocket Streams
198
210
 
199
211
  For public market data, API credentials are not required:
200
212
 
@@ -278,12 +290,97 @@ try {
278
290
  }
279
291
  ```
280
292
 
281
- ### Private WebSocket Streams
293
+ #### Private WebSocket Streams
282
294
 
283
295
  For private account data streams, API credentials are required. The WebsocketClient will automatically handle authentication when you provide API credentials.
284
296
 
285
297
  See [WebsocketClient](./src/WebsocketClient.ts) for further information and make sure to check the [examples](./examples/) folder for much more detail, especially [ws-spot-public.ts](./examples/ws-spot-public.ts), which explains a lot of detail.
286
298
 
299
+ ### WebSocket API
300
+
301
+ Kucoin also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. There are two key ways of interacting with the WebSocket API. The existing WebsocketClient allows raw event routing via the awaitable sendWSAPIRequest() method, or for a much simpler & convenient interface, use the promise-driven API. The surface feels like a REST API, but routing is automatically routed via a dedicated WebSocket connection.
302
+
303
+ #### Event Driven API
304
+
305
+ The WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method.
306
+
307
+ Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design.
308
+
309
+ #### Promise Driven API
310
+
311
+ The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient).
312
+
313
+ It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection.
314
+
315
+ Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. For more detailed demonstration, take a look at the [examples/WebSockets/ws-api-client.ts](./examples/WebSockets//ws-api-client.ts) example:
316
+
317
+ ```typescript
318
+ import { DefaultLogger, WebsocketAPIClient } from 'kucoin-api';
319
+
320
+ // or, if you prefer `require()`:
321
+ // const { DefaultLogger, WebsocketAPIClient } = require('kucoin-api');
322
+
323
+ const customLogger = {
324
+ ...DefaultLogger,
325
+ // For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line:
326
+ // trace: (...params) => console.log(new Date(), 'trace', ...params),
327
+ };
328
+
329
+ const account = {
330
+ key: process.env.API_KEY || 'keyHere',
331
+ secret: process.env.API_SECRET || 'secretHere',
332
+ passphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere', // This is NOT your account password
333
+ };
334
+
335
+ const wsClient = new WebsocketAPIClient(
336
+ {
337
+ apiKey: account.key,
338
+ apiSecret: account.secret,
339
+ apiPassphrase: account.passphrase,
340
+
341
+ // If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below:
342
+ // attachEventListeners: false
343
+ },
344
+ // customLogger, // optional: uncomment this to inject a custom logger
345
+ );
346
+
347
+ // Make WebSocket API calls, very similar to a REST API:
348
+
349
+ wsClient
350
+ .submitNewSpotOrder({
351
+ side: 'buy',
352
+ symbol: 'BTC-USDT',
353
+ type: 'limit',
354
+ price: '150000',
355
+ size: '0.0001',
356
+ })
357
+ .then((syncSpotOrderResponse) => {
358
+ console.log('Sync spot order response:', syncSpotOrderResponse);
359
+ })
360
+ .catch((e) => {
361
+ console.log('Sync spot order error:', e);
362
+ });
363
+
364
+ wsClient
365
+ .submitFuturesOrder({
366
+ clientOid: 'futures-test-' + Date.now(),
367
+ side: 'buy',
368
+ symbol: 'XBTUSDTM',
369
+ marginMode: 'CROSS',
370
+ type: 'limit',
371
+ price: '1000',
372
+ qty: '0.01',
373
+ leverage: 10,
374
+ positionSide: 'LONG', // needed if trading two-way (hedge) position mode
375
+ })
376
+ .then((futuresOrderResponse) => {
377
+ console.log('Futures order response:', futuresOrderResponse);
378
+ })
379
+ .catch((e) => {
380
+ console.log('Futures order error:', e);
381
+ });
382
+ ```
383
+
287
384
  ---
288
385
 
289
386
  ## Customise Logging
@@ -301,8 +398,8 @@ const logger = {
301
398
  trace: (...params) => {
302
399
  if (
303
400
  [
401
+ // Selectively prevent some traces from logging
304
402
  'Sending ping',
305
- // 'Sending upstream ws message: ',
306
403
  'Received pong',
307
404
  ].includes(params[0])
308
405
  ) {
@@ -0,0 +1,123 @@
1
+ import { DefaultLogger } from './lib/websocket/logger.js';
2
+ import { WSAPIWsKey } from './lib/websocket/websocket-util.js';
3
+ import { BatchCancelOrdersRequest, Order } from './types/request/futures.types.js';
4
+ import { SubmitHFMarginOrderRequest } from './types/request/spot-margin-trading.js';
5
+ import { ModifyHFOrderRequest, SubmitHFOrderRequest } from './types/request/spot-trading.js';
6
+ import { BatchCancelOrderResult, SubmitMultipleOrdersFuturesResponse } from './types/response/futures.types.js';
7
+ import { MarginSubmitOrderV3Response } from './types/response/spot-margin-trading.js';
8
+ import { SubmitHFOrderSyncResponse, SyncCancelHFOrderResponse } from './types/response/spot-trading.js';
9
+ import { WSAPICancelOrderRequest, WSAPIOrderResponse, WSAPIResponse } from './types/websockets/ws-api.js';
10
+ import { WSClientConfigurableOptions } from './types/websockets/ws-general.js';
11
+ import { WebsocketClient } from './WebsocketClient.js';
12
+ /**
13
+ * Configurable options specific to only the REST-like WebsocketAPIClient
14
+ */
15
+ export interface WSAPIClientConfigurableOptions {
16
+ /**
17
+ * Default: true
18
+ *
19
+ * Attach default event listeners, which will console log any high level
20
+ * events (opened/reconnecting/reconnected/etc).
21
+ *
22
+ * If you disable this, you should set your own event listeners
23
+ * on the embedded WS Client `wsApiClient.getWSClient().on(....)`.
24
+ */
25
+ attachEventListeners: boolean;
26
+ }
27
+ /**
28
+ * This is a minimal Websocket API wrapper around the WebsocketClient.
29
+ *
30
+ * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should
31
+ * be used to transmit that message. This is only useful if you wish to use an alternative wss
32
+ * domain that is supported by the SDK.
33
+ *
34
+ * Note: To use testnet, don't set the wsKey - use `testnet: true` in
35
+ * the constructor instead.
36
+ *
37
+ * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some
38
+ * may find the below methods slightly more intuitive.
39
+ *
40
+ * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly:
41
+ * https://github.com/tiagosiebler/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108
42
+ */
43
+ export declare class WebsocketAPIClient {
44
+ private wsClient;
45
+ private options;
46
+ constructor(options?: WSClientConfigurableOptions & Partial<WSAPIClientConfigurableOptions>, logger?: DefaultLogger);
47
+ getWSClient(): WebsocketClient;
48
+ /**
49
+ * Submit a spot order
50
+ */
51
+ submitNewSpotOrder(params: SubmitHFOrderRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIOrderResponse>>;
52
+ /**
53
+ * Modify a spot order
54
+ */
55
+ modifySpotOrder(params: ModifyHFOrderRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<{
56
+ newOrderId: string;
57
+ clientOid: string;
58
+ }>>;
59
+ /**
60
+ * Cancel a spot order
61
+ */
62
+ cancelSpotOrder(params: WSAPICancelOrderRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIOrderResponse>>;
63
+ /**
64
+ * Submit a sync spot order
65
+ */
66
+ submitSyncSpotOrder(params: SubmitHFOrderRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<SubmitHFOrderSyncResponse>>;
67
+ /**
68
+ * Cancel a sync spot order
69
+ */
70
+ cancelSyncSpotOrder(params: WSAPICancelOrderRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<SyncCancelHFOrderResponse>>;
71
+ /**
72
+ * Submit a margin order
73
+ */
74
+ submitMarginOrder(params: SubmitHFMarginOrderRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<MarginSubmitOrderV3Response>>;
75
+ /**
76
+ * Cancel a margin order
77
+ */
78
+ cancelMarginOrder(params: WSAPICancelOrderRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIOrderResponse>>;
79
+ /**
80
+ * Submit a futures order
81
+ */
82
+ submitFuturesOrder(params: Order, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIOrderResponse>>;
83
+ /**
84
+ * Cancel a futures order
85
+ */
86
+ cancelFuturesOrder(params: {
87
+ orderId: string;
88
+ } | {
89
+ clientOid: string;
90
+ symbol: string;
91
+ }, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<{
92
+ cancelledOrderIds: string[];
93
+ } | {
94
+ clientOid: string;
95
+ }>>;
96
+ /**
97
+ * Submit multiple futures orders
98
+ */
99
+ submitMultipleFuturesOrders(params: Order[], wsKey?: WSAPIWsKey): Promise<WSAPIResponse<SubmitMultipleOrdersFuturesResponse[]>>;
100
+ /**
101
+ * Cancel multiple futures orders
102
+ */
103
+ cancelMultipleFuturesOrders(params: BatchCancelOrdersRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<BatchCancelOrderResult[]>>;
104
+ /**
105
+ *
106
+ *
107
+ *
108
+ *
109
+ *
110
+ *
111
+ *
112
+ * Private methods for handling some of the convenience/automation provided by the WS API Client
113
+ *
114
+ *
115
+ *
116
+ *
117
+ *
118
+ *
119
+ *
120
+ */
121
+ connectWSAPI(wsKey: WSAPIWsKey): Promise<unknown>;
122
+ private setupDefaultEventListeners;
123
+ }
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebsocketAPIClient = void 0;
4
+ const websocket_util_js_1 = require("./lib/websocket/websocket-util.js");
5
+ const WebsocketClient_js_1 = require("./WebsocketClient.js");
6
+ /**
7
+ * This is a minimal Websocket API wrapper around the WebsocketClient.
8
+ *
9
+ * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should
10
+ * be used to transmit that message. This is only useful if you wish to use an alternative wss
11
+ * domain that is supported by the SDK.
12
+ *
13
+ * Note: To use testnet, don't set the wsKey - use `testnet: true` in
14
+ * the constructor instead.
15
+ *
16
+ * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some
17
+ * may find the below methods slightly more intuitive.
18
+ *
19
+ * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly:
20
+ * https://github.com/tiagosiebler/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108
21
+ */
22
+ class WebsocketAPIClient {
23
+ wsClient;
24
+ options;
25
+ constructor(options, logger) {
26
+ this.wsClient = new WebsocketClient_js_1.WebsocketClient(options, logger);
27
+ this.options = {
28
+ attachEventListeners: true,
29
+ ...options,
30
+ };
31
+ this.setupDefaultEventListeners();
32
+ }
33
+ getWSClient() {
34
+ return this.wsClient;
35
+ }
36
+ /**
37
+ * Submit a spot order
38
+ */
39
+ submitNewSpotOrder(params, wsKey) {
40
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiSpotV1, 'spot.order', params);
41
+ }
42
+ /**
43
+ * Modify a spot order
44
+ */
45
+ modifySpotOrder(params, wsKey) {
46
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiSpotV1, 'spot.modify', params);
47
+ }
48
+ /**
49
+ * Cancel a spot order
50
+ */
51
+ cancelSpotOrder(params, wsKey) {
52
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiSpotV1, 'spot.cancel', params);
53
+ }
54
+ /**
55
+ * Submit a sync spot order
56
+ */
57
+ submitSyncSpotOrder(params, wsKey) {
58
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiSpotV1, 'spot.sync_order', params);
59
+ }
60
+ /**
61
+ * Cancel a sync spot order
62
+ */
63
+ cancelSyncSpotOrder(params, wsKey) {
64
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiSpotV1, 'spot.sync_cancel', params);
65
+ }
66
+ /**
67
+ * Submit a margin order
68
+ */
69
+ submitMarginOrder(params, wsKey) {
70
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiSpotV1, 'margin.order', params);
71
+ }
72
+ /**
73
+ * Cancel a margin order
74
+ */
75
+ cancelMarginOrder(params, wsKey) {
76
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiSpotV1, 'margin.cancel', params);
77
+ }
78
+ /**
79
+ * Submit a futures order
80
+ */
81
+ submitFuturesOrder(params, wsKey) {
82
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiFuturesV1, 'futures.order', params);
83
+ }
84
+ /**
85
+ * Cancel a futures order
86
+ */
87
+ cancelFuturesOrder(params, wsKey) {
88
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiFuturesV1, 'futures.cancel', params);
89
+ }
90
+ /**
91
+ * Submit multiple futures orders
92
+ */
93
+ submitMultipleFuturesOrders(params, wsKey) {
94
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiFuturesV1, 'futures.multi_order', params);
95
+ }
96
+ /**
97
+ * Cancel multiple futures orders
98
+ */
99
+ cancelMultipleFuturesOrders(params, wsKey) {
100
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.wsApiFuturesV1, 'futures.multi_cancel', params);
101
+ }
102
+ /**
103
+ *
104
+ *
105
+ *
106
+ *
107
+ *
108
+ *
109
+ *
110
+ * Private methods for handling some of the convenience/automation provided by the WS API Client
111
+ *
112
+ *
113
+ *
114
+ *
115
+ *
116
+ *
117
+ *
118
+ */
119
+ connectWSAPI(wsKey) {
120
+ return this.getWSClient().assertIsAuthenticated(wsKey);
121
+ }
122
+ setupDefaultEventListeners() {
123
+ if (this.options.attachEventListeners) {
124
+ /**
125
+ * General event handlers for monitoring the WebsocketClient
126
+ */
127
+ this.wsClient
128
+ .on('open', (data) => {
129
+ console.log(new Date(), 'ws connected', data.wsKey);
130
+ })
131
+ .on('reconnect', ({ wsKey }) => {
132
+ console.log(new Date(), 'ws automatically reconnecting.... ', wsKey);
133
+ })
134
+ .on('reconnected', (data) => {
135
+ console.log(new Date(), 'ws has reconnected ', data?.wsKey);
136
+ })
137
+ .on('authenticated', (data) => {
138
+ console.info(new Date(), 'ws has authenticated ', data?.wsKey);
139
+ })
140
+ .on('exception', (data) => {
141
+ console.error(new Date(), 'ws exception: ', JSON.stringify(data));
142
+ });
143
+ }
144
+ }
145
+ }
146
+ exports.WebsocketAPIClient = WebsocketAPIClient;
147
+ //# sourceMappingURL=WebsocketAPIClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WebsocketAPIClient.js","sourceRoot":"","sources":["../../src/WebsocketAPIClient.ts"],"names":[],"mappings":";;;AACA,yEAA2E;AAyB3E,6DAAuD;AAkBvD;;;;;;;;;;;;;;;GAeG;AACH,MAAa,kBAAkB;IACrB,QAAQ,CAAkB;IAE1B,OAAO,CAA+D;IAE9E,YACE,OACyC,EACzC,MAAsB;QAEtB,IAAI,CAAC,QAAQ,GAAG,IAAI,oCAAe,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAErD,IAAI,CAAC,OAAO,GAAG;YACb,oBAAoB,EAAE,IAAI;YAC1B,GAAG,OAAO;SACX,CAAC;QAEF,IAAI,CAAC,0BAA0B,EAAE,CAAC;IACpC,CAAC;IAEM,WAAW;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,kBAAkB,CAChB,MAA4B,EAC5B,KAAkB;QAElB,OAAO,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CACnC,KAAK,IAAI,8BAAU,CAAC,WAAW,EAC/B,YAAY,EACZ,MAAM,CACP,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,eAAe,CACb,MAA4B,EAC5B,KAAkB;QAElB,OAAO,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CACnC,KAAK,IAAI,8BAAU,CAAC,WAAW,EAC/B,aAAa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eAAe,EAAE,CAAC,IAAI,EAAE,EAAE;gBAC5B,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,EAAE,uBAAuB,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;YACjE,CAAC,CAAC;iBACD,EAAE,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,EAAE;gBACxB,OAAO,CAAC,KAAK,CAAC,IAAI,IAAI,EAAE,EAAE,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;YACpE,CAAC,CAAC,CAAC;QACP,CAAC;IACH,CAAC;CACF;AAjOD,gDAiOC"}
@@ -1,12 +1,16 @@
1
1
  import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js';
2
- import { MessageEventLike, WsKey, WsTopicRequest } from './lib/websocket/websocket-util.js';
2
+ import { WsKey, WsTopicRequest } from './lib/websocket/websocket-util.js';
3
3
  import { WSConnectedResult } from './lib/websocket/WsStore.types.js';
4
- import { WsMarket } from './types/websockets/client.js';
5
- import { WsOperation } from './types/websockets/requests.js';
6
- import { WsAPITopicRequestParamMap, WsAPITopicResponseMap, WsAPIWsKeyTopicMap } from './types/websockets/wsAPI.js';
4
+ import { Exact, WSAPIAuthenticationRequestFromServer, WsAPITopicRequestParamMap, WsAPITopicResponseMap, WsAPIWsKeyTopicMap, WsOperation } from './types/websockets/ws-api.js';
5
+ import { MessageEventLike } from './types/websockets/ws-events.js';
6
+ import { WsMarket } from './types/websockets/ws-general.js';
7
7
  export declare const WS_LOGGER_CATEGORY: {
8
8
  category: string;
9
9
  };
10
+ export interface WSAPIRequestFlags {
11
+ /** If true, will skip auth requirement for WS API connection */
12
+ authIsOptional?: boolean | undefined;
13
+ }
10
14
  /** Any WS keys in this list will ALWAYS skip the authentication process, even if credentials are available */
11
15
  export declare const PUBLIC_WS_KEYS: WsKey[];
12
16
  /**
@@ -18,6 +22,7 @@ export declare class WebsocketClient extends BaseWebsocketClient<WsKey> {
18
22
  private getRESTClient;
19
23
  private getRestClientOptions;
20
24
  private getWSConnectionInfo;
25
+ private signMessage;
21
26
  /**
22
27
  * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library
23
28
  */
@@ -40,15 +45,15 @@ export declare class WebsocketClient extends BaseWebsocketClient<WsKey> {
40
45
  * - These topics will be removed from the topic cache, so they won't be subscribed to again.
41
46
  */
42
47
  unsubscribe(requests: (WsTopicRequest<WsTopic> | WsTopic) | (WsTopicRequest<WsTopic> | WsTopic)[], wsKey: WsKey): void;
43
- /**
44
- * Not supported by Kucoin, do not use
45
- */
46
- sendWSAPIRequest<TWSKey extends keyof WsAPIWsKeyTopicMap, TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], TWSParams extends WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], TWSAPIResponse extends WsAPITopicResponseMap[TWSChannel] | object = WsAPITopicResponseMap[TWSChannel]>(wsKey: TWSKey, channel: TWSChannel, ...params: TWSParams extends undefined ? [] : [TWSParams]): Promise<TWSAPIResponse>;
48
+ sendWSAPIRequest<TWSKey extends keyof WsAPIWsKeyTopicMap, TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], TWSParams extends Exact<WsAPITopicRequestParamMap[TWSOperation]>, TWSAPIResponse extends WsAPITopicResponseMap[TWSOperation] = WsAPITopicResponseMap[TWSOperation]>(wsKey: TWSKey, operation: TWSOperation, params: TWSParams & {
49
+ signRequest?: boolean;
50
+ }, requestFlags?: WSAPIRequestFlags): Promise<TWSAPIResponse>;
47
51
  /**
48
52
  *
49
53
  * Internal methods
50
54
  *
51
55
  */
56
+ private signWSAPIRequest;
52
57
  /**
53
58
  * Whatever url this method returns, it's connected to as-is!
54
59
  *
@@ -73,6 +78,6 @@ export declare class WebsocketClient extends BaseWebsocketClient<WsKey> {
73
78
  * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send)
74
79
  */
75
80
  protected getWsOperationEventsForTopics(topicRequests: WsTopicRequest<string>[], wsKey: WsKey, operation: WsOperation): Promise<string[]>;
76
- protected getWsAuthRequestEvent(wsKey: WsKey): Promise<object>;
81
+ protected getWsAuthRequestEvent(wsKey: WsKey, eventToAuth?: WSAPIAuthenticationRequestFromServer): Promise<object | string | 'waitForEvent' | void>;
77
82
  }
78
83
  export {};