gateio-api 1.1.11 → 1.1.12

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 (54) hide show
  1. package/README.md +93 -86
  2. package/dist/cjs/WebsocketAPIClient.d.ts +136 -0
  3. package/dist/cjs/WebsocketAPIClient.js +197 -0
  4. package/dist/cjs/WebsocketAPIClient.js.map +1 -0
  5. package/dist/cjs/WebsocketClient.d.ts +14 -2
  6. package/dist/cjs/WebsocketClient.js +102 -20
  7. package/dist/cjs/WebsocketClient.js.map +1 -1
  8. package/dist/cjs/index.d.ts +1 -0
  9. package/dist/cjs/index.js +1 -0
  10. package/dist/cjs/index.js.map +1 -1
  11. package/dist/cjs/lib/BaseRestClient.js +17 -0
  12. package/dist/cjs/lib/BaseRestClient.js.map +1 -1
  13. package/dist/cjs/lib/BaseWSClient.d.ts +14 -3
  14. package/dist/cjs/lib/BaseWSClient.js +95 -24
  15. package/dist/cjs/lib/BaseWSClient.js.map +1 -1
  16. package/dist/cjs/lib/logger.d.ts +1 -0
  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 +13 -2
  20. package/dist/cjs/lib/websocket/WsStore.js +44 -19
  21. package/dist/cjs/lib/websocket/WsStore.js.map +1 -1
  22. package/dist/cjs/lib/websocket/WsStore.types.d.ts +10 -3
  23. package/dist/cjs/lib/websocket/WsStore.types.js +1 -1
  24. package/dist/cjs/lib/websocket/WsStore.types.js.map +1 -1
  25. package/dist/cjs/types/websockets/wsAPI.d.ts +193 -38
  26. package/dist/cjs/types/websockets/wsAPI.js +0 -5
  27. package/dist/cjs/types/websockets/wsAPI.js.map +1 -1
  28. package/dist/mjs/WebsocketAPIClient.d.ts +136 -0
  29. package/dist/mjs/WebsocketAPIClient.js +193 -0
  30. package/dist/mjs/WebsocketAPIClient.js.map +1 -0
  31. package/dist/mjs/WebsocketClient.d.ts +14 -2
  32. package/dist/mjs/WebsocketClient.js +102 -20
  33. package/dist/mjs/WebsocketClient.js.map +1 -1
  34. package/dist/mjs/index.d.ts +1 -0
  35. package/dist/mjs/index.js +1 -0
  36. package/dist/mjs/index.js.map +1 -1
  37. package/dist/mjs/lib/BaseRestClient.js +17 -0
  38. package/dist/mjs/lib/BaseRestClient.js.map +1 -1
  39. package/dist/mjs/lib/BaseWSClient.d.ts +14 -3
  40. package/dist/mjs/lib/BaseWSClient.js +95 -24
  41. package/dist/mjs/lib/BaseWSClient.js.map +1 -1
  42. package/dist/mjs/lib/logger.d.ts +1 -0
  43. package/dist/mjs/lib/requestUtils.d.ts +11 -0
  44. package/dist/mjs/lib/requestUtils.js.map +1 -1
  45. package/dist/mjs/lib/websocket/WsStore.d.ts +13 -2
  46. package/dist/mjs/lib/websocket/WsStore.js +39 -14
  47. package/dist/mjs/lib/websocket/WsStore.js.map +1 -1
  48. package/dist/mjs/lib/websocket/WsStore.types.d.ts +10 -3
  49. package/dist/mjs/lib/websocket/WsStore.types.js +1 -1
  50. package/dist/mjs/lib/websocket/WsStore.types.js.map +1 -1
  51. package/dist/mjs/types/websockets/wsAPI.d.ts +193 -38
  52. package/dist/mjs/types/websockets/wsAPI.js +0 -5
  53. package/dist/mjs/types/websockets/wsAPI.js.map +1 -1
  54. package/package.json +6 -2
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Node.js & JavaScript SDK for Gate.io REST APIs, WebSockets & WebSocket API
1
+ # Node.js & JavaScript SDK for Gate.com (Gate.io) REST APIs, WebSockets & WebSocket API
2
2
 
3
3
  <p align="center">
4
4
  <a href="https://www.npmjs.com/package/gateio-api">
@@ -18,27 +18,27 @@
18
18
 
19
19
  [1]: https://www.npmjs.com/package/gateio-api
20
20
 
21
- Updated & performant JavaScript & Node.js SDK for the Gate.io REST APIs and WebSockets:
21
+ Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST APIs and WebSockets:
22
22
 
23
- - Extensive integration with Gate.io REST APIs and WebSockets.
23
+ - Extensive integration with Gate.com (Gate.io) REST APIs and WebSockets.
24
24
  - TypeScript support (with type declarations for most API requests & responses).
25
- - Gate.io REST APIs for Gate.io Spot, Margin, Perpetual Futures, Delivery Futures, Options & Announcements APIs.
25
+ - Gate.com REST APIs for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options & Announcements APIs.
26
26
  - Strongly typed on most requests and responses.
27
- - Extremely robust & performant JavaScript/Node.js Gate.io SDK.
27
+ - Extremely robust & performant JavaScript/Node.js Gate.com SDK.
28
28
  - Actively maintained with a modern, promise-driven interface.
29
- - Support for seamless API authentication for private Gate.io REST API and WebSocket calls.
30
- - Gate.io Spot, Margin, Perpetual Futures, Delivery Futures & Options.
29
+ - Support for seamless API authentication for private Gate.com REST API and WebSocket calls.
30
+ - Gate.com Spot, Margin, Perpetual Futures, Delivery Futures & Options.
31
31
  - Event driven messaging.
32
32
  - Smart websocket persistence
33
33
  - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.
34
34
  - Automatically handle listenKey persistence and expiration/refresh.
35
35
  - Emit `reconnected` event when dropped connection is restored.
36
- - Websocket API for Gate.io Spot, Margin, Perpetual Futures & Delivery Futures.
36
+ - Websocket API for Gate.com Spot, Margin, Perpetual Futures & Delivery Futures.
37
37
  - Automatic connectivity via existing WebsocketClient, just call sendWSAPIRequest to trigger a request.
38
38
  - Automatic authentication, just call sendWSAPIRequest with channel & parameters.
39
39
  - Choose between two interfaces for WS API communication:
40
40
  - Event-driven interface, fire & forget via sendWSAPIRequest and receive async replies via wsClient's event emitter.
41
- - Promise-driven interface, simply call and await sendWSAPIRequest for a REST-API-like behaviour with the WS API.
41
+ - Promise-driven interface, simply use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration.
42
42
  - Proxy support via axios integration.
43
43
  - Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders).
44
44
 
@@ -78,7 +78,7 @@ Check out my related JavaScript/TypeScript/Node.js projects:
78
78
 
79
79
  Most methods accept JS objects. These can be populated using parameters specified by gateio's API documentation.
80
80
 
81
- - [Gate.io API Documentation](https://www.gate.io/docs/developers/apiv4/en/)
81
+ - [Gate.com/gate.io API Documentation](https://www.gate.com/docs/developers/apiv4/en/)
82
82
  - [REST Endpoint Function List](./docs/endpointFunctionList.md)
83
83
  - [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/gateio-api)
84
84
 
@@ -95,11 +95,11 @@ This project uses typescript. Resources are stored in 2 key structures:
95
95
 
96
96
  Create API credentials
97
97
 
98
- - [Gate.io API Key Management](https://www.gate.io/myaccount/api_key_manage)
98
+ - [Gate.com API Key Management](https://www.gate.com/myaccount/api_key_manage)
99
99
 
100
100
  ### REST API
101
101
 
102
- To use any of Gate.io's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the `RestClient`:
102
+ To use any of Gate.com's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the `RestClient`:
103
103
 
104
104
  ```javascript
105
105
  const { RestClient } = require('gateio-api');
@@ -252,107 +252,114 @@ See [WebsocketClient](./src/WebsocketClient.ts) for further information and make
252
252
 
253
253
  ### Websocket API
254
254
 
255
- The [WebsocketClient](./src/WebsocketClient.ts) supports this exchange's Websocket API. There are two ways to use the WS API, depending on individual preference:
255
+ Gate.com supports sending requests (commands) over an active WebSocket connection. This is called the WebSocket API.
256
+
257
+ The WebSocket API is available through two approaches, depending on individual preference:
258
+
259
+ #### Event Driven API
260
+
261
+ The WebSocket API is available in the [WebsocketClient](./src/WebsocketClient.ts) via the `sendWSAPIRequest(wsKey, channel, params)` method.
262
+
263
+ 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.
256
264
 
257
265
  - event-driven:
258
- - send requests via `client.sendWSAPIRequest(wsKey, channel, params)`, fire and forget, don't use await
266
+ - send requests via `client.sendWSAPIRequest(wsKey, channel, params).catch(e => console.error('WS API exception for channel', channel, e))`, fire and forget, don't use await
259
267
  - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)`
260
268
  - promise-driven:
261
269
  - send requests via `const result = await client.sendWSAPIRequest(wsKey, channel, params)`, which returns a promise
262
270
  - await each call
263
271
  - use try/catch blocks to handle promise rejections
264
272
 
265
- The below example demonstrates the promise-driven approach, which behaves similar to a REST API. For more detailed examples, refer to the [examples](./examples/) folder (e.g the [ws-private-spot-wsapi.ts](./examples/ws-private-spot-wsapi.ts) example).
273
+ #### REST-like API
274
+
275
+ 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 RestClient).
276
+
277
+ 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.
278
+
279
+ Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets.
266
280
 
267
281
  ```javascript
268
- const { WebsocketClient } = require('gateio-api');
282
+ const { WebsocketAPIClient } = require('gateio-api');
269
283
 
270
284
  const API_KEY = 'xxx';
271
- const PRIVATE_KEY = 'yyy';
285
+ const API_SECRET = 'yyy';
272
286
 
273
287
  async function start() {
274
- const client = new WebsocketClient({
288
+ // Make an instance of the WS API Client
289
+ const wsClient = new WebsocketAPIClient({
275
290
  apiKey: API_KEY,
276
- apiSecret: PRIVATE_KEY,
291
+ apiSecret: API_SECRET,
277
292
  // Automatically re-auth WS API, if we were auth'd before and get reconnected
278
293
  reauthWSAPIOnReconnect: true,
279
294
  });
280
295
 
281
- /**
282
- * Setup basic event handlers for core connectivity events.
283
- * Note for this approach, the `response` and `update` events are not needed (but you can use them too/instead if you prefer).
284
- **/
285
-
286
- // Successfully connected
287
- client.on('open', (data) => {
288
- console.log(new Date(), 'ws connected ', data?.wsKey);
289
- });
290
-
291
- // Something happened, attempting to reconnect
292
- client.on('reconnect', (data) => {
293
- console.log(new Date(), 'ws reconnect: ', data);
294
- });
295
-
296
- // Reconnect successful
297
- client.on('reconnected', (data) => {
298
- console.log(new Date(), 'ws reconnected: ', data);
299
- });
300
-
301
- // Connection closed. If unexpected, expect reconnect -> reconnected.
302
- client.on('close', (data) => {
303
- console.error(new Date(), 'ws close: ', data);
304
- });
305
-
306
- client.on('exception', (data) => {
307
- console.error(new Date(), 'ws exception: ', data);
308
- });
309
-
310
- client.on('authenticated', (data) => {
311
- console.error(new Date(), 'ws authenticated: ', data);
312
- });
313
-
314
296
  try {
315
- /**
316
- * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method.
317
- */
318
-
319
- // The WSKey identifies which connection this request is for.
320
- // (e.g. "spotV4" | "perpFuturesUSDTV4" | "perpFuturesBTCV4" | "deliveryFuturesUSDTV4" | "deliveryFuturesBTCV4" | "optionsV4")
321
- const wsKey = 'spotV4';
322
-
323
- /**
324
- * To authenticate, send an empty request to "spot.login". The SDK will handle all the parameters.
325
- *
326
- * By default (reauthWSAPIOnReconnect: true), if we get reconnected later on (e.g. connection temporarily lost), we will try to re-authenticate the WS API automatically when the connection is restored.
327
- */
328
- console.log(new Date(), 'try authenticate');
329
- const loginResult = await client.sendWSAPIRequest(wsKey, 'spot.login');
330
- console.log(new Date(), 'authenticated!', loginResult);
331
-
332
- /**
333
- * For other channels, you should include any parameters for the request (the payload) in your call.
334
- *
335
- * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. Only the core request parameters are needed.
336
- */
337
- console.log(new Date(), 'try get order status');
338
- const orderStatus = await client.sendWSAPIRequest(
339
- wsKey,
340
- 'spot.order_status',
341
- {
342
- order_id: '600995435390',
343
- currency_pair: 'BTC_USDT',
344
- },
345
- );
346
-
347
- console.log(new Date(), 'orderStatus result!', orderStatus);
297
+ // Connection will authenticate automatically before first request
298
+ // Make WebSocket API calls, very similar to a REST API:
299
+
300
+ /* ============ SPOT TRADING EXAMPLES ============ */
301
+
302
+ // Submit a new spot order
303
+ const newOrder = await wsClient.submitNewSpotOrder({
304
+ text: 't-my-custom-id',
305
+ currency_pair: 'BTC_USDT',
306
+ type: 'limit',
307
+ account: 'spot',
308
+ side: 'buy',
309
+ amount: '1',
310
+ price: '10000',
311
+ });
312
+ console.log('Order result:', newOrder.data);
313
+
314
+ // Cancel a spot order
315
+ const cancelOrder = await wsClient.cancelSpotOrder({
316
+ order_id: '1700664330',
317
+ currency_pair: 'BTC_USDT',
318
+ account: 'spot',
319
+ });
320
+ console.log('Cancel result:', cancelOrder.data);
321
+
322
+ // Get spot order status
323
+ const orderStatus = await wsClient.getSpotOrderStatus({
324
+ order_id: '1700664330',
325
+ currency_pair: 'BTC_USDT',
326
+ account: 'spot',
327
+ });
328
+ console.log('Order status:', orderStatus.data);
329
+
330
+ /* ============ FUTURES TRADING EXAMPLES ============ */
331
+
332
+ // Submit a new futures order
333
+ const newFuturesOrder = await wsClient.submitNewFuturesOrder({
334
+ contract: 'BTC_USDT',
335
+ size: 10,
336
+ price: '31503.28',
337
+ tif: 'gtc',
338
+ text: 't-my-custom-id',
339
+ });
340
+ console.log('Futures order result:', newFuturesOrder.data);
341
+
342
+ // Cancel a futures order
343
+ const cancelFuturesOrder = await wsClient.cancelFuturesOrder({
344
+ order_id: '74046514',
345
+ });
346
+ console.log('Cancel futures order result:', cancelFuturesOrder.data);
347
+
348
+ // Get futures order status
349
+ const futuresOrderStatus = await wsClient.getFuturesOrderStatus({
350
+ order_id: '74046543',
351
+ });
352
+ console.log('Futures order status:', futuresOrderStatus.data);
348
353
  } catch (e) {
349
- console.error(`WS API Error: `, e);
354
+ console.error('WS API Error:', e);
350
355
  }
351
356
  }
352
357
 
353
358
  start();
354
359
  ```
355
360
 
361
+ For more detailed examples using any approach, refer to the [examples](./examples/) folder (e.g. [ws-api-client.ts](./examples/ws-api-client.ts)).
362
+
356
363
  ---
357
364
 
358
365
  ## Customise Logging
@@ -0,0 +1,136 @@
1
+ import { DefaultLogger } from './lib/logger.js';
2
+ import { WSClientConfigurableOptions } from './types/websockets/client.js';
3
+ import { WSAPIFuturesOrder, WSAPIFuturesOrderAmendReq, WSAPIFuturesOrderBatchPlaceRespItem, WSAPIFuturesOrderCancelCPReq, WSAPIFuturesOrderCancelIdsRespItem, WSAPIFuturesOrderCancelReq, WSAPIFuturesOrderListReq, WSAPIFuturesOrderPlaceReq, WSAPIFuturesOrderStatusReq, WSAPIResponse, WSAPISpotOrder, WSAPISpotOrderAmendReq, WSAPISpotOrderCancelCPReq, WSAPISpotOrderCancelIdsReq, WSAPISpotOrderCancelIdsRespItem, WSAPISpotOrderCancelReq, WSAPISpotOrderListReq, WSAPISpotOrderPlaceReq, WSAPISpotOrderStatusReq, WSAPIWsKey } from './types/websockets/wsAPI.js';
4
+ import { WebsocketClient } from './WebsocketClient.js';
5
+ /**
6
+ * Configurable options specific to only the REST-like WebsocketAPIClient
7
+ */
8
+ export interface WSAPIClientConfigurableOptions {
9
+ /**
10
+ * Default: true
11
+ *
12
+ * Attach default event listeners, which will console log any high level
13
+ * events (opened/reconnecting/reconnected/etc).
14
+ *
15
+ * If you disable this, you should set your own event listeners
16
+ * on the embedded WS Client `wsApiClient.getWSClient().on(....)`.
17
+ */
18
+ attachEventListeners: boolean;
19
+ }
20
+ /**
21
+ * This is a minimal Websocket API wrapper around the WebsocketClient.
22
+ *
23
+ * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should
24
+ * be used to transmit that message. This is only useful if you wish to use an alternative wss
25
+ * domain that is supported by the SDK.
26
+ *
27
+ * Note: To use testnet, don't set the wsKey - use `testnet: true` in
28
+ * the constructor instead.
29
+ *
30
+ * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some
31
+ * may find the below methods slightly more intuitive.
32
+ *
33
+ * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly:
34
+ * https://github.com/tiagosiebler/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119
35
+ */
36
+ export declare class WebsocketAPIClient {
37
+ private wsClient;
38
+ private options;
39
+ constructor(options?: WSClientConfigurableOptions & Partial<WSAPIClientConfigurableOptions>, logger?: DefaultLogger);
40
+ getWSClient(): WebsocketClient;
41
+ setTimeOffsetMs(newOffset: number): void;
42
+ /**
43
+ * Submit a spot order
44
+ */
45
+ submitNewSpotOrder(params: WSAPISpotOrderPlaceReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPISpotOrder>>;
46
+ /**
47
+ * Cancel a spot order
48
+ */
49
+ cancelSpotOrder(params: WSAPISpotOrderCancelReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPISpotOrder>>;
50
+ /**
51
+ * Cancel all spot orders with the given id list
52
+ */
53
+ cancelSpotOrderById(params: WSAPISpotOrderCancelIdsReq[], wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPISpotOrderCancelIdsRespItem[]>>;
54
+ /**
55
+ * Cancel a spot order for a given symbol
56
+ */
57
+ cancelSpotOrderForSymbol(params: WSAPISpotOrderCancelCPReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPISpotOrder[]>>;
58
+ /**
59
+ * Update a spot order
60
+ */
61
+ updateSpotOrder(params: WSAPISpotOrderAmendReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPISpotOrder>>;
62
+ /**
63
+ * Get the status of a spot order
64
+ */
65
+ getSpotOrderStatus(params: WSAPISpotOrderStatusReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPISpotOrder>>;
66
+ /**
67
+ * Get all spot orders
68
+ */
69
+ getSpotOrders(params: WSAPISpotOrderListReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPISpotOrder[]>>;
70
+ /**
71
+ * Submit a futures order.
72
+ *
73
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
74
+ */
75
+ submitNewFuturesOrder(params: WSAPIFuturesOrderPlaceReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIFuturesOrder>>;
76
+ /**
77
+ * Submit a batch of futures orders
78
+ *
79
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
80
+ */
81
+ submitNewFuturesBatchOrder(params: WSAPIFuturesOrderPlaceReq[], wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIFuturesOrderBatchPlaceRespItem[]>>;
82
+ /**
83
+ * Cancel a futures order
84
+ *
85
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
86
+ */
87
+ cancelFuturesOrder(params: WSAPIFuturesOrderCancelReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIFuturesOrder>>;
88
+ /**
89
+ * Cancel futures orders by id list
90
+ *
91
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
92
+ */
93
+ cancelFuturesOrderById(params: string[], wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIFuturesOrderCancelIdsRespItem[]>>;
94
+ /**
95
+ * Cancel all open futures orders
96
+ *
97
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
98
+ */
99
+ cancelFuturesAllOpenOrders(params: WSAPIFuturesOrderCancelCPReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIFuturesOrder[]>>;
100
+ /**
101
+ * Update a futures order
102
+ *
103
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
104
+ */
105
+ updateFuturesOrder(params: WSAPIFuturesOrderAmendReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIFuturesOrder>>;
106
+ /**
107
+ * Get all futures orders
108
+ *
109
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
110
+ */
111
+ getFuturesOrders(params: WSAPIFuturesOrderListReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIFuturesOrder[]>>;
112
+ /**
113
+ * Get futures order status
114
+ *
115
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
116
+ */
117
+ getFuturesOrderStatus(params: WSAPIFuturesOrderStatusReq, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<WSAPIFuturesOrder>>;
118
+ /**
119
+ *
120
+ *
121
+ *
122
+ *
123
+ *
124
+ *
125
+ *
126
+ * Private methods for handling some of the convenience/automation provided by the WS API Client
127
+ *
128
+ *
129
+ *
130
+ *
131
+ *
132
+ *
133
+ *
134
+ */
135
+ private setupDefaultEventListeners;
136
+ }
@@ -0,0 +1,197 @@
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/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119
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
+ setTimeOffsetMs(newOffset) {
37
+ return this.getWSClient().setTimeOffsetMs(newOffset);
38
+ }
39
+ /*
40
+ *
41
+ * SPOT - Trading requests
42
+ *
43
+ */
44
+ /**
45
+ * Submit a spot order
46
+ */
47
+ submitNewSpotOrder(params, wsKey) {
48
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.spotV4, 'spot.order_place', params);
49
+ }
50
+ /**
51
+ * Cancel a spot order
52
+ */
53
+ cancelSpotOrder(params, wsKey) {
54
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.spotV4, 'spot.order_cancel', params);
55
+ }
56
+ /**
57
+ * Cancel all spot orders with the given id list
58
+ */
59
+ cancelSpotOrderById(params, wsKey) {
60
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.spotV4, 'spot.order_cancel_ids', params);
61
+ }
62
+ /**
63
+ * Cancel a spot order for a given symbol
64
+ */
65
+ cancelSpotOrderForSymbol(params, wsKey) {
66
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.spotV4, 'spot.order_cancel_cp', params);
67
+ }
68
+ /**
69
+ * Update a spot order
70
+ */
71
+ updateSpotOrder(params, wsKey) {
72
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.spotV4, 'spot.order_amend', params);
73
+ }
74
+ /**
75
+ * Get the status of a spot order
76
+ */
77
+ getSpotOrderStatus(params, wsKey) {
78
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.spotV4, 'spot.order_status', params);
79
+ }
80
+ /**
81
+ * Get all spot orders
82
+ */
83
+ getSpotOrders(params, wsKey) {
84
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.spotV4, 'spot.order_list', params);
85
+ }
86
+ /*
87
+ *
88
+ * Futures - Trading requests
89
+ *
90
+ */
91
+ /**
92
+ * Submit a futures order.
93
+ *
94
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
95
+ */
96
+ submitNewFuturesOrder(params, wsKey) {
97
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.perpFuturesUSDTV4, 'futures.order_place', params);
98
+ }
99
+ /**
100
+ * Submit a batch of futures orders
101
+ *
102
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
103
+ */
104
+ submitNewFuturesBatchOrder(params, wsKey) {
105
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.perpFuturesUSDTV4, 'futures.order_batch_place', params);
106
+ }
107
+ /**
108
+ * Cancel a futures order
109
+ *
110
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
111
+ */
112
+ cancelFuturesOrder(params, wsKey) {
113
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.perpFuturesUSDTV4, 'futures.order_cancel', params);
114
+ }
115
+ /**
116
+ * Cancel futures orders by id list
117
+ *
118
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
119
+ */
120
+ cancelFuturesOrderById(params, wsKey) {
121
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.perpFuturesUSDTV4, 'futures.order_cancel_ids', params);
122
+ }
123
+ /**
124
+ * Cancel all open futures orders
125
+ *
126
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
127
+ */
128
+ cancelFuturesAllOpenOrders(params, wsKey) {
129
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.perpFuturesUSDTV4, 'futures.order_cancel_cp', params);
130
+ }
131
+ /**
132
+ * Update a futures order
133
+ *
134
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
135
+ */
136
+ updateFuturesOrder(params, wsKey) {
137
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.perpFuturesUSDTV4, 'futures.order_amend', params);
138
+ }
139
+ /**
140
+ * Get all futures orders
141
+ *
142
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
143
+ */
144
+ getFuturesOrders(params, wsKey) {
145
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.perpFuturesUSDTV4, 'futures.order_list', params);
146
+ }
147
+ /**
148
+ * Get futures order status
149
+ *
150
+ * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection
151
+ */
152
+ getFuturesOrderStatus(params, wsKey) {
153
+ return this.wsClient.sendWSAPIRequest(wsKey || websocket_util_js_1.WS_KEY_MAP.perpFuturesUSDTV4, 'futures.order_status', params);
154
+ }
155
+ /**
156
+ *
157
+ *
158
+ *
159
+ *
160
+ *
161
+ *
162
+ *
163
+ * Private methods for handling some of the convenience/automation provided by the WS API Client
164
+ *
165
+ *
166
+ *
167
+ *
168
+ *
169
+ *
170
+ *
171
+ */
172
+ setupDefaultEventListeners() {
173
+ if (this.options.attachEventListeners) {
174
+ /**
175
+ * General event handlers for monitoring the WebsocketClient
176
+ */
177
+ this.wsClient
178
+ .on('open', (data) => {
179
+ console.log(new Date(), 'ws connected', data.wsKey);
180
+ })
181
+ .on('reconnect', ({ wsKey }) => {
182
+ console.log(new Date(), 'ws automatically reconnecting.... ', wsKey);
183
+ })
184
+ .on('reconnected', (data) => {
185
+ console.log(new Date(), 'ws has reconnected ', data?.wsKey);
186
+ })
187
+ .on('authenticated', (data) => {
188
+ console.info(new Date(), 'ws has authenticated ', data?.wsKey);
189
+ })
190
+ .on('exception', (data) => {
191
+ console.error(new Date(), 'ws exception: ', JSON.stringify(data));
192
+ });
193
+ }
194
+ }
195
+ }
196
+ exports.WebsocketAPIClient = WebsocketAPIClient;
197
+ //# sourceMappingURL=WebsocketAPIClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WebsocketAPIClient.js","sourceRoot":"","sources":["../../src/WebsocketAPIClient.ts"],"names":[],"mappings":";;;AACA,yEAA+D;AAwB/D,6DAAuD;AAkBvD;;;;;;;;;;;;;;;GAeG;AACH,MAAa,kBAAkB;IACrB,QAAQ,CAAkB;IAE1B,OAAO,CAA+D;IAE9E,YACE,OACyC,EACzC,MAAsB;QAEtB,IAAI,CAAC,QAAQ,GAAG,IAAI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E,CAAC,IAAI,EAAE,EAAE;gBAC1B,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,qBAAqB,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;YAC9D,CAAC,CAAC;iBACD,EAAE,CAAC,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;AAnTD,gDAmTC"}
@@ -3,10 +3,14 @@ import { MessageEventLike } from './lib/requestUtils.js';
3
3
  import { WsKey, WsMarket, WsTopicRequest } from './lib/websocket/websocket-util.js';
4
4
  import { WSConnectedResult } from './lib/websocket/WsStore.types.js';
5
5
  import { WsOperation } from './types/websockets/requests.js';
6
- import { WsAPITopicRequestParamMap, WsAPITopicResponseMap, WsAPIWsKeyTopicMap } from './types/websockets/wsAPI.js';
6
+ import { WsAPITopicRequestParamMap, WsAPITopicResponseMap, WSAPIWsKey, WsAPIWsKeyTopicMap } from './types/websockets/wsAPI.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
  /**
11
15
  * WS topics are always a string for gate. Some exchanges use complex objects
12
16
  */
@@ -18,6 +22,13 @@ export declare class WebsocketClient extends BaseWebsocketClient<WsKey> {
18
22
  * Returns array of promises that individually resolve when each connection is successfully opened.
19
23
  */
20
24
  connectAll(): Promise<WSConnectedResult | undefined>[];
25
+ /**
26
+ * Ensures the WS API connection is active and ready.
27
+ *
28
+ * You do not need to call this, but if you call this before making any WS API requests,
29
+ * it can accelerate the first request (by preparing the connection in advance).
30
+ */
31
+ connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise<unknown>;
21
32
  /**
22
33
  * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters).
23
34
  * Objects should be formatted as {topic: string, params: object}.
@@ -59,7 +70,7 @@ export declare class WebsocketClient extends BaseWebsocketClient<WsKey> {
59
70
  * @param params - Any request parameters for the payload (contents of req_param in the docs). Signature generation is automatic, only send parameters such as order ID as per the docs.
60
71
  * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response
61
72
  */
62
- 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>;
73
+ 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 void | never ? undefined : TWSParams, requestFlags?: WSAPIRequestFlags): Promise<TWSAPIResponse>;
63
74
  /**
64
75
  *
65
76
  * Internal methods - not intended for public use
@@ -86,6 +97,7 @@ export declare class WebsocketClient extends BaseWebsocketClient<WsKey> {
86
97
  * Not in use for gate.io
87
98
  */
88
99
  protected getPrivateWSKeys(): WsKey[];
100
+ protected isAuthOnConnectWsKey(wsKey: WsKey): boolean;
89
101
  /** Force subscription requests to be sent in smaller batches, if a number is returned */
90
102
  protected getMaxTopicsPerSubscribeEvent(_wsKey: WsKey): number | null;
91
103
  /**