binance 3.0.0-beta.1 → 3.0.0-beta.11

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 (80) hide show
  1. package/README.md +305 -75
  2. package/index.js +1 -1
  3. package/lib/coinm-client.d.ts +40 -22
  4. package/lib/coinm-client.js +4 -16
  5. package/lib/coinm-client.js.map +1 -1
  6. package/lib/index.d.ts +2 -0
  7. package/lib/index.js +2 -0
  8. package/lib/index.js.map +1 -1
  9. package/lib/main-client.d.ts +94 -30
  10. package/lib/main-client.js +68 -36
  11. package/lib/main-client.js.map +1 -1
  12. package/lib/portfolio-client.js.map +1 -1
  13. package/lib/types/coin.d.ts +1 -0
  14. package/lib/types/futures.d.ts +15 -5
  15. package/lib/types/futures.js.map +1 -1
  16. package/lib/types/portfolio-margin.d.ts +0 -9
  17. package/lib/types/shared.d.ts +14 -13
  18. package/lib/types/spot.d.ts +174 -11
  19. package/lib/types/spot.js.map +1 -1
  20. package/lib/types/websockets/ws-api-requests.d.ts +480 -2
  21. package/lib/types/websockets/ws-api-responses.d.ts +565 -1
  22. package/lib/types/websockets/ws-api.d.ts +157 -60
  23. package/lib/types/websockets/ws-api.js +47 -3
  24. package/lib/types/websockets/ws-api.js.map +1 -1
  25. package/lib/types/websockets/ws-events-formatted.d.ts +18 -14
  26. package/lib/types/websockets/ws-events-raw.d.ts +4 -2
  27. package/lib/types/websockets/ws-general.d.ts +8 -18
  28. package/lib/usdm-client.d.ts +45 -27
  29. package/lib/usdm-client.js +7 -19
  30. package/lib/usdm-client.js.map +1 -1
  31. package/lib/util/BaseRestClient.js +20 -6
  32. package/lib/util/BaseRestClient.js.map +1 -1
  33. package/lib/util/BaseWSClient.d.ts +14 -3
  34. package/lib/util/BaseWSClient.js +87 -30
  35. package/lib/util/BaseWSClient.js.map +1 -1
  36. package/lib/util/beautifier-maps.d.ts +32 -0
  37. package/lib/util/beautifier-maps.js +41 -0
  38. package/lib/util/beautifier-maps.js.map +1 -1
  39. package/lib/util/beautifier.d.ts +1 -0
  40. package/lib/util/beautifier.js +44 -9
  41. package/lib/util/beautifier.js.map +1 -1
  42. package/lib/util/browser-support.d.ts +1 -1
  43. package/lib/util/browser-support.js +1 -41
  44. package/lib/util/browser-support.js.map +1 -1
  45. package/lib/util/node-support.js +7 -5
  46. package/lib/util/node-support.js.map +1 -1
  47. package/lib/util/requestUtils.d.ts +23 -5
  48. package/lib/util/requestUtils.js +130 -29
  49. package/lib/util/requestUtils.js.map +1 -1
  50. package/lib/util/rounding.d.ts +8 -0
  51. package/lib/util/rounding.js +41 -0
  52. package/lib/util/rounding.js.map +1 -0
  53. package/lib/util/typeGuards.d.ts +31 -3
  54. package/lib/util/typeGuards.js +105 -8
  55. package/lib/util/typeGuards.js.map +1 -1
  56. package/lib/util/webCryptoAPI.js +20 -45
  57. package/lib/util/webCryptoAPI.js.map +1 -1
  58. package/lib/util/websockets/WsStore.js +7 -2
  59. package/lib/util/websockets/WsStore.js.map +1 -1
  60. package/lib/util/websockets/enum.d.ts +11 -0
  61. package/lib/util/websockets/enum.js +24 -0
  62. package/lib/util/websockets/enum.js.map +1 -0
  63. package/lib/util/websockets/rest-client-cache.d.ts +3 -3
  64. package/lib/util/websockets/rest-client-cache.js +9 -9
  65. package/lib/util/websockets/rest-client-cache.js.map +1 -1
  66. package/lib/util/websockets/user-data-stream-manager.js +7 -8
  67. package/lib/util/websockets/user-data-stream-manager.js.map +1 -1
  68. package/lib/util/websockets/websocket-util.d.ts +36 -8
  69. package/lib/util/websockets/websocket-util.js +176 -74
  70. package/lib/util/websockets/websocket-util.js.map +1 -1
  71. package/lib/websocket-api-client.d.ts +401 -0
  72. package/lib/websocket-api-client.js +647 -0
  73. package/lib/websocket-api-client.js.map +1 -0
  74. package/lib/websocket-client-legacy.d.ts +5 -3
  75. package/lib/websocket-client-legacy.js +14 -13
  76. package/lib/websocket-client-legacy.js.map +1 -1
  77. package/lib/websocket-client.d.ts +26 -11
  78. package/lib/websocket-client.js +269 -174
  79. package/lib/websocket-client.js.map +1 -1
  80. package/package.json +3 -3
package/README.md CHANGED
@@ -21,34 +21,64 @@
21
21
 
22
22
  Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets:
23
23
 
24
- - Extensive integration with Binance REST APIs and WebSockets.
25
- - TypeScript support (with type declarations for most API requests & responses).
26
- - Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, USDM & CoinM Futures.
27
- - Strongly typed on most requests and responses.
28
- - Automated end-to-end tests on most API calls, ensuring no breaking changes are released.
29
- - Extremely robust & performant JavaScript/Node.js Binance SDK with significant trading volume in production (livenet).
24
+ - Professional, robust & performant Binance SDK with leading trading volume in production (livenet).
25
+ - Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs.
26
+ - Complete TypeScript support (with type declarations for all API requests & responses).
27
+ - Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures.
28
+ - Strongly typed requests and responses.
29
+ - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm.
30
30
  - Actively maintained with a modern, promise-driven interface.
31
- - Support for all authentication mechanisms:
31
+ - Support for all authentication mechanisms available on Binance:
32
32
  - HMAC
33
33
  - RSA
34
34
  - Ed25519 (required for WS API).
35
- - Passing a private key as a secret will automatically revert to RSA/Ed25519 authentication (depending on key format).
36
- - Supports Websockets for Binance Spot, Margin, Isolated Margin, USDM & CoinM Futures.
35
+ - Passing a private key as a secret will automatically detect whether to switch to RSA or Ed25519 authentication.
36
+ - Supports WebSockets for all available product groups on Binance including Spot, Margin, Isolated Margin, Portfolio, Options, USDM & CoinM Futures.
37
37
  - Event driven messaging.
38
- - Smart websocket persistence
39
- - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.
38
+ - Smart WebSocket persistence
39
+ - Automatically handle silent WebSocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.
40
40
  - Automatically handle listenKey persistence and expiration/refresh.
41
41
  - Emit `reconnected` event when dropped connection is restored.
42
- - Strongly typed on most websocket events, with typeguards available for TypeScript users.
42
+ - Strongly typed on most WebSocket events, with typeguards available for TypeScript users.
43
43
  - Optional:
44
- - Automatic beautification of Websocket events (from one-letter keys to descriptive words, and strings with floats to numbers).
44
+ - Automatic beautification of WebSocket events (from one-letter keys to descriptive words, and strings with floats to numbers).
45
45
  - Automatic beautification of REST responses (parsing numbers in strings to numbers).
46
+ - Supports WebSocket API on all available product groups, including Spot & Futures:
47
+ - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or;
48
+ - 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.
46
49
  - Heavy automated end-to-end testing with real API calls.
47
50
  - End-to-end testing before any release.
48
51
  - Real API calls in e2e tests.
49
52
  - Proxy support via axios integration.
50
53
  - Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders).
51
54
 
55
+ ## Table of Contents
56
+
57
+ - [Installation](#installation)
58
+ - [Examples](#examples)
59
+ - [REST API Examples](./examples/REST)
60
+ - [WebSocket Examples](./examples/WebSockets)
61
+ - [WebSocket Consumers](./examples/WebSockets/)
62
+ - [WebSocket API](./examples/WebSockets/ws-api-client.ts)
63
+ - [Issues & Discussion](#issues--discussion)
64
+ - [Related Projects](#related-projects)
65
+ - [Documentation Links](#documentation)
66
+ - [Usage](#usage)
67
+ - [REST API Clients](#rest-api-clients)
68
+ - [REST Main Client](#rest-main-client)
69
+ - [REST USD-M Futures](#rest-usd-m-futures)
70
+ - [REST COIN-M Futures](#rest-coin-m-futures)
71
+ - [WebSockets](#websockets)
72
+ - [WebSocket Consumers](#websocket-consumers)
73
+ - [WebSocket API](#websocket-api)
74
+ - [Event Driven API](#event-driven-api)
75
+ - [Promise Driven API](#async-await-api)
76
+ - [Customise Logging](#customise-logging)
77
+ - [Frontend Usage](#browserfrontend-usage)
78
+ - [Import](#import)
79
+ - [Webpack](#webpack)
80
+ - [Contributions & Thanks](#contributions--thanks)
81
+
52
82
  ## Installation
53
83
 
54
84
  `npm install binance --save`
@@ -90,15 +120,12 @@ Check out my related JavaScript/TypeScript/Node.js projects:
90
120
 
91
121
  Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation.
92
122
 
93
- - [Binance API Documentation](https://developers.binance.com/docs)
94
-
123
+ - Binance API Documentation
95
124
  - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs)
96
125
  - [ Derivatives ](https://developers.binance.com/docs/derivatives)
97
126
  - [ Margin ](https://developers.binance.com/docs/margin_trading)
98
127
  - [ Wallet ](https://developers.binance.com/docs/wallet)
99
-
100
128
  - [Find all products here](https://developers.binance.com/en)
101
-
102
129
  - [REST Endpoint Function List](./docs/endpointFunctionList.md)
103
130
  - [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance)
104
131
 
@@ -117,6 +144,8 @@ This project uses typescript. Resources are stored in 3 key structures:
117
144
  Create API credentials at Binance
118
145
 
119
146
  - [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO)
147
+ - [Testnet](https://testnet.binance.vision/).
148
+ - [Testnet Futures](testnet.binancefuture.com).
120
149
 
121
150
  ## REST API Clients
122
151
 
@@ -125,15 +154,40 @@ There are several REST API modules as there are some differences in each API gro
125
154
  1. `MainClient` for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management.
126
155
  2. `USDMClient` for USD-M futures APIs.
127
156
  3. `CoinMClient` for COIN-M futures APIs.
128
-
129
- Vanilla Options connectors are not yet available, though contributions are welcome!
130
-
131
- ### REST Spot/Margin/etc
132
-
133
- Start by importing the spot client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.
157
+ 4. `PortfolioClient` for Portfolio Margin APIs.
158
+
159
+ Vanilla Options is not yet available. Please get in touch if you're looking for this.
160
+
161
+ ### REST Main Client
162
+
163
+ The MainClient covers all endpoints under the main "api*.binance.com" subdomains, including but not limited to endpoints in the following product groups:
164
+ - Spot
165
+ - Cross & isolated margin
166
+ - Convert
167
+ - Wallet
168
+ - Futures management (transfers & history)
169
+ - Sub account management
170
+ - Misc transfers
171
+ - Auto & dual invest
172
+ - Staking
173
+ - Mining
174
+ - Loans & VIP loans
175
+ - Simple Earn
176
+ - NFTs
177
+ - C2C
178
+ - Exchange Link
179
+
180
+ Refer to the following links for a complete list of available endpoints:
181
+ - [Binance Node.js & JavaScript SDK Endpoint Map](https://github.com/tiagosiebler/binance/blob/master/docs/endpointFunctionList.md)
182
+ - [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints)
183
+
184
+ Start by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub.
134
185
 
135
186
  ```javascript
136
- const { MainClient } = require('binance');
187
+ import { MainClient } from 'binance';
188
+
189
+ // or, if you prefer `require()`:
190
+ // const { MainClient } = require('binance');
137
191
 
138
192
  const API_KEY = 'xxx';
139
193
  const API_SECRET = 'yyy';
@@ -141,6 +195,8 @@ const API_SECRET = 'yyy';
141
195
  const client = new MainClient({
142
196
  api_key: API_KEY,
143
197
  api_secret: API_SECRET,
198
+ // Connect to testnet environment
199
+ // testnet: true,
144
200
  });
145
201
 
146
202
  client
@@ -162,14 +218,17 @@ client
162
218
  });
163
219
  ```
164
220
 
165
- See [spot-client.ts](./src/main-client.ts) for further information.
221
+ See [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc.
166
222
 
167
223
  ### REST USD-M Futures
168
224
 
169
- Start by importing the usd-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.
225
+ Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls.
170
226
 
171
227
  ```javascript
172
- const { USDMClient } = require('binance');
228
+ import { USDMClient } from 'binance';
229
+
230
+ // or, if you prefer `require()`:
231
+ // const { USDMClient } = require('binance');
173
232
 
174
233
  const API_KEY = 'xxx';
175
234
  const API_SECRET = 'yyy';
@@ -177,6 +236,8 @@ const API_SECRET = 'yyy';
177
236
  const client = new USDMClient({
178
237
  api_key: API_KEY,
179
238
  api_secret: API_SECRET,
239
+ // Connect to testnet environment
240
+ // testnet: true,
180
241
  });
181
242
 
182
243
  client
@@ -189,13 +250,19 @@ client
189
250
  });
190
251
 
191
252
  client
192
- .get24hrChangeStatististics()
253
+ .submitNewOrder({
254
+ side: 'SELL',
255
+ symbol: 'BTCUSDT',
256
+ type: 'MARKET',
257
+ quantity: 0.001,
258
+ })
193
259
  .then((result) => {
194
- console.log('get24hrChangeStatististics inverse futures result: ', result);
260
+ console.log('submitNewOrder result: ', result);
195
261
  })
196
262
  .catch((err) => {
197
- console.error('get24hrChangeStatististics inverse futures error: ', err);
263
+ console.error('submitNewOrder error: ', err);
198
264
  });
265
+
199
266
  ```
200
267
 
201
268
  See [usdm-client.ts](./src/usdm-client.ts) for further information.
@@ -205,7 +272,10 @@ See [usdm-client.ts](./src/usdm-client.ts) for further information.
205
272
  Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.
206
273
 
207
274
  ```javascript
208
- const { CoinMClient } = require('binance');
275
+ import { CoinMClient } from 'binance';
276
+
277
+ // or, if you prefer `require()`:
278
+ // const { CoinMClient } = require('binance');
209
279
 
210
280
  const API_KEY = 'xxx';
211
281
  const API_SECRET = 'yyy';
@@ -213,6 +283,8 @@ const API_SECRET = 'yyy';
213
283
  const client = new CoinMClient({
214
284
  api_key: API_KEY,
215
285
  api_secret: API_SECRET,
286
+ // Connect to testnet environment
287
+ // testnet: true,
216
288
  });
217
289
 
218
290
  client
@@ -229,29 +301,37 @@ See [coinm-client.ts](./src/coinm-client.ts) for further information.
229
301
 
230
302
  ## WebSockets
231
303
 
304
+ ### WebSocket Consumers
305
+
232
306
  All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required.
233
307
 
308
+ The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance:
309
+
234
310
  ```javascript
235
- const { WebsocketClient } = require('binance');
311
+ import { WebsocketClient } from 'binance';
312
+
313
+ // or, if you prefer `require()`:
314
+ // const { WebsocketClient } = require('binance');
236
315
 
237
316
  const API_KEY = 'xxx';
238
317
  const API_SECRET = 'yyy';
239
318
 
240
- // optionally override the logger
241
- const logger = {
242
- ...DefaultLogger,
243
- silly: (...params) => {},
244
- };
245
-
319
+ /**
320
+ * The WebsocketClient will manage individual connections for you, under the hood.
321
+ * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest.
322
+ */
246
323
  const wsClient = new WebsocketClient(
247
324
  {
248
325
  api_key: key,
249
326
  api_secret: secret,
327
+ // Optional: when enabled, the SDK will try to format incoming data into more readable objects.
328
+ // Beautified data is emitted via the "formattedMessage" event
250
329
  beautify: true,
251
330
  // Disable ping/pong ws heartbeat mechanism (not recommended)
252
- // disableHeartbeat: true
331
+ // disableHeartbeat: true,
332
+ // Connect to testnet environment
333
+ // testnet: true,
253
334
  },
254
- logger,
255
335
  );
256
336
 
257
337
  // receive raw events
@@ -261,7 +341,7 @@ wsClient.on('message', (data) => {
261
341
 
262
342
  // notification when a connection is opened
263
343
  wsClient.on('open', (data) => {
264
- console.log('connection opened open:', data.wsKey, data.ws.target.url);
344
+ console.log('connection opened open:', data.wsKey, data.wsUrl);
265
345
  });
266
346
 
267
347
  // receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats.
@@ -270,8 +350,8 @@ wsClient.on('formattedMessage', (data) => {
270
350
  });
271
351
 
272
352
  // read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS)
273
- wsClient.on('reply', (data) => {
274
- console.log('log reply: ', JSON.stringify(data, null, 2));
353
+ wsClient.on('response', (data) => {
354
+ console.log('log response: ', JSON.stringify(data, null, 2));
275
355
  });
276
356
 
277
357
  // receive notification when a ws connection is reconnecting automatically
@@ -285,60 +365,212 @@ wsClient.on('reconnected', (data) => {
285
365
  });
286
366
 
287
367
  // Recommended: receive error events (e.g. first reconnection failed)
288
- wsClient.on('error', (data) => {
368
+ wsClient.on('exception', (data) => {
289
369
  console.log('ws saw error ', data?.wsKey);
290
370
  });
291
371
 
292
- // Call methods to subcribe to as many websockets as you want.
293
- // Each method spawns a new connection, unless a websocket already exists for that particular request topic.
294
- // wsClient.subscribeSpotAggregateTrades(market);
295
- // wsClient.subscribeSpotTrades(market);
296
- // wsClient.subscribeSpotKline(market, interval);
297
- // wsClient.subscribeSpotSymbolMini24hrTicker(market);
298
- // wsClient.subscribeSpotAllMini24hrTickers();
299
- // wsClient.subscribeSpotSymbol24hrTicker(market);
300
- // wsClient.subscribeSpotAll24hrTickers();
301
- // wsClient.subscribeSpotSymbolBookTicker(market);
302
- // wsClient.subscribeSpotAllBookTickers();
303
- // wsClient.subscribeSpotPartialBookDepth(market, 5);
304
- // wsClient.subscribeSpotDiffBookDepth(market);
372
+ /**
373
+ * Subscribe to public topics either one at a time or many in an array
374
+ */
375
+
376
+ // E.g. one at a time, routed to the coinm futures websockets:
377
+ wsClient.subscribe('btcusd@indexPrice', 'coinm');
378
+ wsClient.subscribe('btcusd@miniTicker', 'coinm');
379
+
380
+ // Or send many topics at once to a stream, e.g. the usdm futures stream:
381
+ wsClient.subscribe(
382
+ [
383
+ 'btcusdt@aggTrade',
384
+ 'btcusdt@markPrice',
385
+ '!ticker@arr',
386
+ '!miniTicker@arr',
387
+ ],
388
+ 'usdm',
389
+ );
390
+
391
+ // spot & margin topics should go to "main"
392
+ // (similar how the MainClient is for REST APIs in that product group)
393
+ wsClient.subscribe(
394
+ [
395
+ // All Market Rolling Window Statistics Streams
396
+ // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams
397
+ '!ticker_1h@arr',
398
+ // Individual Symbol Book Ticker Streams
399
+ // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams
400
+ 'btcusdt@bookTicker',
401
+ // Average Price
402
+ // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price
403
+ 'btcusdt@avgPrice',
404
+ // Partial Book Depth Streams
405
+ // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams
406
+ 'btcusdt@depth10@100ms',
407
+ // Diff. Depth Stream
408
+ // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream
409
+ 'btcusdt@depth',
410
+ ],
411
+ // Look at the `WS_KEY_URL_MAP` for a list of values here:
412
+ // https://github.com/tiagosiebler/binance/blob/master/src/util/websockets/websocket-util.ts
413
+ // "main" connects to wss://stream.binance.com:9443/stream
414
+ // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams
415
+ 'main',
416
+ );
417
+
418
+ /**
419
+ * For the user data stream, these convenient subscribe methods open a dedicated
420
+ * connection with the listen key workflow:
421
+ */
305
422
 
306
423
  wsClient.subscribeSpotUserDataStream();
307
424
  wsClient.subscribeMarginUserDataStream();
308
425
  wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT');
309
-
310
426
  wsClient.subscribeUsdFuturesUserDataStream();
311
-
312
- // each method also restores the WebSocket object, which can be interacted with for more control
313
- // const ws1 = wsClient.subscribeSpotSymbolBookTicker(market);
314
- // const ws2 = wsClient.subscribeSpotAllBookTickers();
315
- // const ws3 = wsClient.subscribeSpotUserDataStream(listenKey);
316
-
317
- // optionally directly open a connection to a URL. Not recommended for production use.
318
- // const ws4 = wsClient.connectToWsUrl(`wss://stream.binance.com:9443/ws/${listenKey}`, 'customDirectWsConnection1');
319
427
  ```
320
428
 
321
429
  See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples.
322
430
 
431
+ ### WebSocket API
432
+
433
+ Some of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API.
434
+
435
+ Note: the WebSocket API requires the use of Ed25519 keys. HMAC & RSA keys are not supported by Binance for the WebSocket API (as of Apr 2025).
436
+
437
+ #### Event Driven API
438
+
439
+ The WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method.
440
+
441
+ 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.
442
+
443
+ #### Async Await API
444
+
445
+ 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).
446
+
447
+ 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.
448
+
449
+ Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets.
450
+
451
+ ```typescript
452
+ import { WebsocketAPIClient } from 'binance';
453
+
454
+ // or, if you prefer `require()`:
455
+ // const { WebsocketAPIClient } = require('binance');
456
+
457
+ /**
458
+ * The WS API only works with an Ed25519 API key.
459
+ *
460
+ * Check the rest-private-ed25519.md in this folder for more guidance
461
+ * on preparing this Ed25519 API key.
462
+ */
463
+
464
+ const publicKey = `-----BEGIN PUBLIC KEY-----
465
+ MCexampleQTxwLU9o=
466
+ -----END PUBLIC KEY-----
467
+ `;
468
+
469
+ const privateKey = `-----BEGIN PRIVATE KEY-----
470
+ MC4CAQAexamplewqj5CzUuTy1
471
+ -----END PRIVATE KEY-----
472
+ `;
473
+
474
+ // API Key returned by binance, generated using the publicKey (above) via Binance's website
475
+ const apiKey = 'TQpJexamplerobdG';
476
+
477
+ // Make an instance of the WS API Client
478
+ const wsClient = new WebsocketAPIClient({
479
+ api_key: apiKey,
480
+ api_secret: privateKey,
481
+ beautify: true,
482
+
483
+ // Enforce testnet ws connections, regardless of supplied wsKey
484
+ // testnet: true,
485
+ });
486
+
487
+ // Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first!
488
+ // https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow
489
+ // wsClient.setTimeOffsetMs(-5000);
490
+
491
+ // Optional, see above. Can be used to prepare a connection before sending commands
492
+ // await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI);
493
+
494
+ // Make WebSocket API calls, very similar to a REST API:
495
+
496
+ wsClient
497
+ .getFuturesAccountBalanceV2({
498
+ timestamp: Date.now(),
499
+ recvWindow: 5000,
500
+ })
501
+ .then((result) => {
502
+ console.log('getFuturesAccountBalanceV2 result: ', result);
503
+ })
504
+ .catch((err) => {
505
+ console.error('getFuturesAccountBalanceV2 error: ', err);
506
+ });
507
+
508
+ wsClient
509
+ .submitNewFuturesOrder('usdm', {
510
+ side: 'SELL',
511
+ symbol: 'BTCUSDT',
512
+ type: 'MARKET',
513
+ quantity: 0.001,
514
+ timestamp: Date.now(),
515
+ // recvWindow: 5000,
516
+ })
517
+ .then((result) => {
518
+ console.log('getFuturesAccountBalanceV2 result: ', result);
519
+ })
520
+ .catch((err) => {
521
+ console.error('getFuturesAccountBalanceV2 error: ', err);
522
+ });
523
+ ```
524
+
323
525
  ---
324
526
 
325
527
  ## Customise Logging
326
528
 
327
- Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired.
529
+ Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired.
328
530
 
329
531
  ```javascript
330
- const { WebsocketClient, DefaultLogger } = require('binance');
532
+ import { WebsocketClient, DefaultLogger } from 'binance';
331
533
 
332
- // Enable all logging on the silly level
333
- DefaultLogger.silly = (...params) => {
334
- console.log('sillyLog: ', params);
534
+ // or, if you prefer `require()`:
535
+ // const { WebsocketClient, DefaultLogger } = require('binance');
536
+
537
+ // Enable all logging on the trace level (disabled by default)
538
+ DefaultLogger.trace = (...params) => {
539
+ console.trace('trace: ', params);
335
540
  };
336
541
 
542
+ // Pass the updated logger as the 2nd parameter
337
543
  const ws = new WebsocketClient(
338
- api_key: 'xxx',
339
- api_secret: 'yyyy',
544
+ {
545
+ api_key: key,
546
+ api_secret: secret,
547
+ beautify: true,
548
+ },
340
549
  DefaultLogger
341
550
  );
551
+
552
+ // Or, create a completely custom logger with the 3 available functions
553
+ const customLogger = {
554
+ trace: (...params: LogParams): void => {
555
+ console.trace(new Date(), params);
556
+ },
557
+ info: (...params: LogParams): void => {
558
+ console.info(new Date(), params);
559
+ },
560
+ error: (...params: LogParams): void => {
561
+ console.error(new Date(), params);
562
+ },
563
+ }
564
+
565
+ // Pass the custom logger as the 2nd parameter
566
+ const ws = new WebsocketClient(
567
+ {
568
+ api_key: key,
569
+ api_secret: secret,
570
+ beautify: true,
571
+ },
572
+ customLogger
573
+ );
342
574
  ```
343
575
 
344
576
  ## Browser/Frontend Usage
@@ -381,8 +613,6 @@ Build a bundle using webpack:
381
613
 
382
614
  The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.
383
615
 
384
- However, note that browser usage will lead to CORS errors due to Binance.
385
-
386
616
  ---
387
617
 
388
618
  <!-- template_contributions -->
package/index.js CHANGED
@@ -1 +1 @@
1
- module.exports = require('lib/index');
1
+ module.exports = require('lib/index');