bybit-api 3.10.30 → 4.0.0-beta.1

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 (146) hide show
  1. package/README.md +301 -178
  2. package/lib/index.d.ts +0 -11
  3. package/lib/index.js +0 -11
  4. package/lib/index.js.map +1 -1
  5. package/lib/rest-client-v5.d.ts +1 -1
  6. package/lib/rest-client-v5.js +1 -1
  7. package/lib/spot-client-v3.d.ts +8 -81
  8. package/lib/spot-client-v3.js +7 -172
  9. package/lib/spot-client-v3.js.map +1 -1
  10. package/lib/types/index.d.ts +1 -2
  11. package/lib/types/index.js +1 -2
  12. package/lib/types/index.js.map +1 -1
  13. package/lib/types/request/index.d.ts +0 -1
  14. package/lib/types/request/index.js +0 -1
  15. package/lib/types/request/index.js.map +1 -1
  16. package/lib/types/request/v5-account.d.ts +1 -1
  17. package/lib/types/request/v5-asset.d.ts +1 -1
  18. package/lib/types/request/v5-market.d.ts +1 -1
  19. package/lib/types/request/v5-position.d.ts +1 -1
  20. package/lib/types/request/v5-pre-upgrade.d.ts +1 -1
  21. package/lib/types/request/v5-spot-leverage-token.d.ts +1 -1
  22. package/lib/types/request/v5-trade.d.ts +1 -1
  23. package/lib/types/request/v5-user.d.ts +1 -1
  24. package/lib/types/response/v5-account.d.ts +1 -1
  25. package/lib/types/response/v5-asset.d.ts +1 -1
  26. package/lib/types/response/v5-market.d.ts +1 -1
  27. package/lib/types/response/v5-position.d.ts +1 -1
  28. package/lib/types/response/v5-spot-leverage-token.d.ts +1 -1
  29. package/lib/types/response/v5-trade.d.ts +1 -1
  30. package/lib/types/response/v5-user.d.ts +1 -1
  31. package/lib/types/{request/spot.js → shared-v5.js} +1 -1
  32. package/lib/types/shared-v5.js.map +1 -0
  33. package/lib/types/shared.d.ts +1 -19
  34. package/lib/types/websockets/index.d.ts +3 -0
  35. package/lib/types/websockets/index.js +20 -0
  36. package/lib/types/websockets/index.js.map +1 -0
  37. package/lib/types/websockets/ws-api.d.ts +73 -0
  38. package/lib/types/websockets/ws-api.js +10 -0
  39. package/lib/types/websockets/ws-api.js.map +1 -0
  40. package/lib/types/websockets/ws-confirmations.d.ts +13 -0
  41. package/lib/types/{websocket.events.js → websockets/ws-confirmations.js} +1 -1
  42. package/lib/types/websockets/ws-confirmations.js.map +1 -0
  43. package/lib/types/{websocket.events.d.ts → websockets/ws-events.d.ts} +9 -3
  44. package/lib/types/websockets/ws-events.js +11 -0
  45. package/lib/types/websockets/ws-events.js.map +1 -0
  46. package/lib/types/{websockets.d.ts → websockets/ws-general.d.ts} +35 -10
  47. package/lib/types/{v5-shared.js → websockets/ws-general.js} +1 -1
  48. package/lib/types/websockets/ws-general.js.map +1 -0
  49. package/lib/util/BaseRestClient.d.ts +1 -1
  50. package/lib/util/BaseRestClient.js +15 -39
  51. package/lib/util/BaseRestClient.js.map +1 -1
  52. package/lib/util/BaseWSClient.d.ts +221 -0
  53. package/lib/util/BaseWSClient.js +733 -0
  54. package/lib/util/BaseWSClient.js.map +1 -0
  55. package/lib/util/index.d.ts +1 -2
  56. package/lib/util/index.js +1 -2
  57. package/lib/util/index.js.map +1 -1
  58. package/lib/util/logger.d.ts +2 -5
  59. package/lib/util/logger.js +3 -12
  60. package/lib/util/logger.js.map +1 -1
  61. package/lib/util/requestUtils.d.ts +7 -10
  62. package/lib/util/requestUtils.js +6 -33
  63. package/lib/util/requestUtils.js.map +1 -1
  64. package/lib/util/typeGuards.d.ts +7 -1
  65. package/lib/util/typeGuards.js +41 -5
  66. package/lib/util/typeGuards.js.map +1 -1
  67. package/lib/util/webCryptoAPI.d.ts +10 -0
  68. package/lib/util/webCryptoAPI.js +69 -0
  69. package/lib/util/webCryptoAPI.js.map +1 -0
  70. package/lib/util/websockets/WsStore.d.ts +71 -0
  71. package/lib/util/websockets/WsStore.js +269 -0
  72. package/lib/util/websockets/WsStore.js.map +1 -0
  73. package/lib/util/websockets/WsStore.types.d.ts +50 -0
  74. package/lib/util/websockets/WsStore.types.js +14 -0
  75. package/lib/util/websockets/WsStore.types.js.map +1 -0
  76. package/lib/util/websockets/index.d.ts +3 -0
  77. package/lib/util/websockets/index.js +20 -0
  78. package/lib/util/websockets/index.js.map +1 -0
  79. package/lib/util/websockets/websocket-util.d.ts +92 -0
  80. package/lib/util/websockets/websocket-util.js +280 -0
  81. package/lib/util/websockets/websocket-util.js.map +1 -0
  82. package/lib/websocket-client.d.ts +107 -114
  83. package/lib/websocket-client.js +427 -716
  84. package/lib/websocket-client.js.map +1 -1
  85. package/package.json +4 -4
  86. package/lib/account-asset-client-v3.d.ts +0 -87
  87. package/lib/account-asset-client-v3.js +0 -154
  88. package/lib/account-asset-client-v3.js.map +0 -1
  89. package/lib/account-asset-client.d.ts +0 -46
  90. package/lib/account-asset-client.js +0 -108
  91. package/lib/account-asset-client.js.map +0 -1
  92. package/lib/contract-client.d.ts +0 -136
  93. package/lib/contract-client.js +0 -251
  94. package/lib/contract-client.js.map +0 -1
  95. package/lib/copy-trading-client.d.ts +0 -60
  96. package/lib/copy-trading-client.js +0 -114
  97. package/lib/copy-trading-client.js.map +0 -1
  98. package/lib/inverse-client.d.ts +0 -104
  99. package/lib/inverse-client.js +0 -213
  100. package/lib/inverse-client.js.map +0 -1
  101. package/lib/inverse-futures-client.d.ts +0 -217
  102. package/lib/inverse-futures-client.js +0 -224
  103. package/lib/inverse-futures-client.js.map +0 -1
  104. package/lib/linear-client.d.ts +0 -112
  105. package/lib/linear-client.js +0 -225
  106. package/lib/linear-client.js.map +0 -1
  107. package/lib/spot-client.d.ts +0 -46
  108. package/lib/spot-client.js +0 -131
  109. package/lib/spot-client.js.map +0 -1
  110. package/lib/types/request/spot.d.ts +0 -79
  111. package/lib/types/request/spot.js.map +0 -1
  112. package/lib/types/v5-shared.js.map +0 -1
  113. package/lib/types/websocket.events.js.map +0 -1
  114. package/lib/types/websockets.js +0 -3
  115. package/lib/types/websockets.js.map +0 -1
  116. package/lib/types/ws-events/failed-topic-subscription-confirmation.d.ts +0 -4
  117. package/lib/types/ws-events/failed-topic-subscription-confirmation.js +0 -3
  118. package/lib/types/ws-events/failed-topic-subscription-confirmation.js.map +0 -1
  119. package/lib/types/ws-events/succeeded-topic-subscription-confirmation.d.ts +0 -4
  120. package/lib/types/ws-events/succeeded-topic-subscription-confirmation.js +0 -3
  121. package/lib/types/ws-events/succeeded-topic-subscription-confirmation.js.map +0 -1
  122. package/lib/types/ws-events/topic-subscription-confirmation.d.ts +0 -7
  123. package/lib/types/ws-events/topic-subscription-confirmation.js +0 -3
  124. package/lib/types/ws-events/topic-subscription-confirmation.js.map +0 -1
  125. package/lib/unified-margin-client.d.ts +0 -140
  126. package/lib/unified-margin-client.js +0 -270
  127. package/lib/unified-margin-client.js.map +0 -1
  128. package/lib/usdc-option-client.d.ts +0 -110
  129. package/lib/usdc-option-client.js +0 -196
  130. package/lib/usdc-option-client.js.map +0 -1
  131. package/lib/usdc-perpetual-client.d.ts +0 -97
  132. package/lib/usdc-perpetual-client.js +0 -191
  133. package/lib/usdc-perpetual-client.js.map +0 -1
  134. package/lib/util/WsStore.d.ts +0 -57
  135. package/lib/util/WsStore.js +0 -97
  136. package/lib/util/WsStore.js.map +0 -1
  137. package/lib/util/browser-support.d.ts +0 -1
  138. package/lib/util/browser-support.js +0 -26
  139. package/lib/util/browser-support.js.map +0 -1
  140. package/lib/util/node-support.d.ts +0 -2
  141. package/lib/util/node-support.js +0 -21
  142. package/lib/util/node-support.js.map +0 -1
  143. package/lib/util/websocket-util.d.ts +0 -68
  144. package/lib/util/websocket-util.js +0 -506
  145. package/lib/util/websocket-util.js.map +0 -1
  146. /package/lib/types/{v5-shared.d.ts → shared-v5.d.ts} +0 -0
package/README.md CHANGED
@@ -19,21 +19,65 @@
19
19
 
20
20
  [1]: https://www.npmjs.com/package/bybit-api
21
21
 
22
- Node.js & JavaScript SDK for the Bybit REST APIs and WebSockets:
22
+ Node.js, JavaScript & TypeScript SDK for the Bybit REST APIs and WebSockets:
23
23
 
24
- - Complete integration with all Bybit REST APIs & WebSockets.
24
+ - Complete integration with all Bybit REST APIs & WebSockets, including the WebSocket API.
25
25
  - Actively maintained with a modern, promise-driven interface.
26
26
  - TypeScript support (with type declarations for most API requests & responses).
27
- - Over 450 end-to-end tests making real API calls & WebSocket connections, validating any changes before they reach npm.
27
+ - Thorough end-to-end tests making real API calls & WebSocket connections, validating any changes before they reach npm.
28
+ - Proxy support via axios integration.
28
29
  - Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
29
30
  - Event driven messaging.
30
31
  - Smart websocket persistence
31
32
  - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.
32
33
  - Automatically handle listenKey persistence and expiration/refresh.
33
34
  - Emit `reconnected` event when dropped connection is restored.
34
- - Proxy support via axios integration.
35
+ - WebSocket API integration, with two design patterns to choose from:
36
+ - Asynchronous promise-driven responses:
37
+ - This behaves very much like a REST API. No need to subscribe to asynchronous events.
38
+ - Send commands with the await sendWSAPIRequest(...) method.
39
+ - Await responses to commands directly in the fully typed sendWSAPIRequest() call.
40
+ - The method directly returns a promise. Use a try/catch block for convenient error handling without the complexity of asynchronous WebSockets.
41
+ - See example for more details: [examples/ws-api-promises.ts](./examples/ws-api-promises.ts)
42
+ - Asynchronous event-driven responses:
43
+ - Subscribe to `response` and `error` events from WebsocketClient's event emitter.
44
+ - Send commands with the sendWSAPIRequest(...) method.
45
+ - Responses to commands will arrive via the `response` and `error` events.
46
+ - See example for more details: [examples/ws-api-events.ts](./examples/ws-api-events.ts)
35
47
  - Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders).
36
48
 
49
+ # Table of Contents
50
+
51
+ ## Overview
52
+ - [Installation](#installation)
53
+ - [Issues & Discussion](#issues--discussion)
54
+ - [Related Projects](#related-projects)
55
+ - [Documentation](#documentation)
56
+
57
+ ## Structure & Usage
58
+ - [Structure](#structure)
59
+ - [API Clients](#api-clients)
60
+ - [REST API USAGE](#rest-api-usage)
61
+
62
+ ## WebSocket Integration
63
+ - [WebSockets](#websockets)
64
+ - [WebSocket Subscriptions - Consuming Events](#websocket-subscriptions---consuming-events)
65
+ - [Websocket API - Sending Orders via WebSockets](#websocket-api---sending-orders-via-websockets)
66
+ - [Consumer Load Balancing](#balancing-load-across-multiple-connections)
67
+
68
+ ## Additional Features
69
+ - [Logging](#logging)
70
+ - [Customise Logging](#customise-logging)
71
+ - [Debug HTTP Requests](#debug-http-requests)
72
+ - [Browser Usage](#browser-usage)
73
+ - [Import](#import)
74
+ - [Webpack](#webpack)
75
+
76
+ ## Contributing
77
+ - [Contributions & Thanks](#contributions--thanks)
78
+
79
+ ------
80
+
37
81
  ## Installation
38
82
 
39
83
  `npm install --save bybit-api`
@@ -68,7 +112,7 @@ Check out my related JavaScript/TypeScript/Node.js projects:
68
112
 
69
113
  ## Documentation
70
114
 
71
- Most methods accept JS objects. These can be populated using parameters specified by Bybit's API documentation, or check the type definition in each class within the github repository (see table below for convenient links to each class).
115
+ Most methods accept JS objects. These can be populated using parameters specified by Bybit's API documentation, or check the type definition in each class within the github repository (see table below for convenient links to each class). TypeScript is definitely recommended, but not required.
72
116
 
73
117
  - [Bybit API Docs](https://bybit-exchange.github.io/docs/v5/intro)
74
118
  - [REST Endpoint Function List](./docs/endpointFunctionList.md)
@@ -76,137 +120,113 @@ Most methods accept JS objects. These can be populated using parameters specifie
76
120
 
77
121
  ## Structure
78
122
 
79
- This connector is fully compatible with both TypeScript and pure JavaScript projects, while the connector is written in TypeScript. A pure JavaScript version can be built using `npm run build`, which is also the version published to [npm](https://www.npmjs.com/package/bybit-api).
123
+ The SDK is written in TypeScript, but fully compatible with both TypeScript and pure JavaScript projects. A pure JavaScript version can be built using `npm run build`. The output of the `build` command is the version published to npm, packaged as a JavaScript module (with types available for you TypeScript users).
80
124
 
81
- The version on npm is the output from the `build` command and can be used in projects without TypeScript (although TypeScript is definitely recommended).
82
125
 
83
- - [src](./src) - the whole connector written in TypeScript
126
+ - [src](./src) - the complete SDK written in TypeScript.
84
127
  - [lib](./lib) - the JavaScript version of the project (built from TypeScript). This should not be edited directly, as it will be overwritten with each release.
85
128
  - [examples](./examples) - examples & demonstrations. Contributions are welcome!
129
+ - [test](./test) - automated end-to-end tests that run before every release, making real API calls.
86
130
 
87
131
  ---
88
132
 
89
- ## REST API Clients
90
-
91
- Bybit has several API groups (originally one per product). Each generation is labelled with the version number (e.g. v1/v2/v3/v5). New projects & developments should use the newest available API generation (e.g. use the V5 APIs instead of V3).
92
-
93
- Refer to the [V5 interface mapping page](https://bybit-exchange.github.io/docs/v5/intro#v5-and-v3-interface-mapping-list) for more information on which V5 endpoints can be used instead of previous V3 endpoints.
94
-
95
- Here are the available REST clients and the corresponding API groups described in the documentation:
96
-
97
- | Class | Description |
98
- | :----------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
99
- | [ **V5 API** ] | The new unified V5 APIs (successor to previously fragmented APIs for all API groups). To learn more about the V5 API, please read the [V5 upgrade guideline](https://bybit-exchange.github.io/docs/v5/upgrade-guide). |
100
- | [RestClientV5](src/rest-client-v5.ts) | Unified V5 all-in-one REST client for all [V5 REST APIs](https://bybit-exchange.github.io/docs/v5/intro) |
101
- | [WebsocketClient](src/websocket-client.ts) | All WebSocket Events (Public & Private for all API categories) |
102
- | [ **Derivatives v3** ] | The Derivatives v3 APIs (successor to the Futures V2 APIs) |
103
- | [UnifiedMarginClient](src/unified-margin-client.ts) | [Derivatives (v3) Unified Margin APIs](https://bybit-exchange.github.io/docs/derivatives/unified/place-order) |
104
- | [ContractClient](src/contract-client.ts) | [Derivatives (v3) Contract APIs](https://bybit-exchange.github.io/docs/derivatives/contract/place-order). |
105
- | [ **Other** ] | Other standalone API groups |
106
- | [CopyTradingClient](src/copy-trading-client.ts) | [Copy Trading APIs](https://bybit-exchange.github.io/docs/category/copy-trade) |
107
- | [AccountAssetClientV3](src/account-asset-client-v3.ts) | [Account Asset V3 APIs](https://bybit-exchange.github.io/docs/account-asset/internal-transfer) |
133
+ Examples for using each client can be found in:
108
134
 
109
- ---
135
+ - the [examples](./examples) folder.
136
+ - the [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) repository.
110
137
 
111
- ### Deprecated/Obsolete APIs
138
+ If you're missing an example, you're welcome to request one. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler).
112
139
 
113
- The following API clients are for previous generation REST APIs and will be removed in the next major release. Some have already stopped working (because bybit stopped supporting them). You should use the V5 APIs for all new development.
140
+ ## API Clients
114
141
 
115
- <details>
116
- <summary>Click me to see the list of APIs</summary>
142
+ You should be using the V5 APIs. If you aren't, you should upgrade your project to use the V5 APIs as soon as possible. Bybit used to have several API groups (originally one per product), but the V5 API is currently the latest standard.
117
143
 
118
- | Class | Description |
119
- | :--------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------: |
120
- | [ **Futures v2** ] | The Futures v2 APIs |
121
- | [~~InverseClient~~](src/inverse-client.ts) | [Inverse Perpetual Futures (v2) APIs](https://bybit-exchange.github.io/docs/futuresV2/inverse/) |
122
- | [~~LinearClient~~](src/linear-client.ts) | [USDT Perpetual Futures (v2) APIs](https://bybit-exchange.github.io/docs/futuresV2/linear/#t-introduction) |
123
- | [~~InverseFuturesClient~~](src/inverse-futures-client.ts) | [Inverse Futures (v2) APIs](https://bybit-exchange.github.io/docs/futuresV2/inverse_futures/#t-introduction) |
124
- | [ **Spot** ] | The spot APIs |
125
- | [SpotClientV3](src/spot-client-v3.ts) | [Spot Market (v3) APIs](https://bybit-exchange.github.io/docs/spot/public/instrument) |
126
- | [~~SpotClient~~](src/spot-client.ts) (deprecated, SpotClientV3 recommended) | [Spot Market (v1) APIs](https://bybit-exchange.github.io/docs/spot/v1/#t-introduction) |
127
- | [ **USDC Contract** ] | The USDC Contract APIs |
128
- | [USDCPerpetualClient](src/usdc-perpetual-client.ts) | [USDC Perpetual APIs](https://bybit-exchange.github.io/docs/usdc/option/?console#t-querydeliverylog) |
129
- | [USDCOptionClient](src/usdc-option-client.ts) | [USDC Option APIs](https://bybit-exchange.github.io/docs/usdc/option/#t-introduction) |
130
- | [~~AccountAssetClient~~](src/account-asset-client.ts) (deprecated, AccountAssetClientV3 recommended) | [Account Asset V1 APIs](https://bybit-exchange.github.io/docs/account_asset/v1/#t-introduction) |
144
+ Refer to the [V5 interface mapping page](https://bybit-exchange.github.io/docs/v5/intro#v5-and-v3-interface-mapping-list) for more information on which V5 endpoints can be used instead of previous V3 endpoints. To learn more about the V5 API, please read the [V5 upgrade guideline](https://bybit-exchange.github.io/docs/v5/upgrade-guide).
131
145
 
132
- </details>
146
+ Here are the available REST clients and the corresponding API groups described in the documentation:
133
147
 
134
- ---
148
+ | Class | Description |
149
+ | :----------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------: |
150
+ | [ **V5 API** ] | The new unified V5 APIs (successor to previously fragmented APIs for all API groups). |
151
+ | [RestClientV5](src/rest-client-v5.ts) | Unified V5 all-in-one REST client for all [V5 REST APIs](https://bybit-exchange.github.io/docs/v5/intro) |
152
+ | [WebsocketClient](src/websocket-client.ts) | All WebSocket Events (Public & Private for all API categories) |
135
153
 
136
- Examples for using each client can be found in:
137
154
 
138
- - the [examples](./examples) folder.
139
- - the [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) repository.
140
-
141
- If you're missing an example, you're welcome to request one. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler).
142
-
143
- ### Usage
155
+ ## REST API Usage
144
156
 
145
157
  Create API credentials on Bybit's website:
146
158
 
147
159
  - [Livenet](https://bybit.com/app/user/api-management?affiliate_id=9410&language=en-US&group_id=0&group_type=1)
148
160
  - [Testnet](https://testnet.bybit.com/app/user/api-management)
149
161
 
150
- All REST clients have can be used in a similar way. However, method names, parameters and responses may vary depending on the API category you're using!
151
-
152
- Not sure which function to call or which parameters to use? Click the class name in the table above to look at all the function names (they are in the same order as the official API docs), and check the API docs for a list of endpoints/parameters/responses.
153
162
 
154
163
  The following is a minimal example for using the REST clients included with this SDK. For more detailed examples, refer to the [examples](./examples/) folder in the repository on GitHub:
155
164
 
156
165
  ```typescript
157
- const {
158
- InverseClient,
159
- LinearClient,
160
- InverseFuturesClient,
161
- SpotClientV3,
162
- UnifiedMarginClient,
163
- USDCOptionClient,
164
- USDCPerpetualClient,
165
- AccountAssetClient,
166
- CopyTradingClient,
167
- RestClientV5,
168
- } = require('bybit-api');
166
+ const { RestClientV5 } = require('bybit-api');
167
+ // or
168
+ // import { RestClientV5 } from 'bybit-api';
169
169
 
170
170
  const restClientOptions = {
171
- /** Your API key. Optional, if you plan on making private api calls */
172
- key?: string;
171
+ /** Your API key */
172
+ key: 'apiKeyHere',
173
173
 
174
- /** Your API secret. Optional, if you plan on making private api calls */
175
- secret?: string;
174
+ /** Your API secret */
175
+ secret: 'apiSecretHere',
176
176
 
177
177
  /** Set to `true` to connect to testnet. Uses the live environment by default. */
178
- testnet?: boolean;
178
+ // testnet: true,
179
+
180
+ /**
181
+ * Set to `true` to use Bybit's V5 demo trading:
182
+ * https://bybit-exchange.github.io/docs/v5/demo
183
+ *
184
+ * Note: to use demo trading, you should have `testnet` disabled
185
+ */
186
+ // demoTrading: true,
179
187
 
180
188
  /** Override the max size of the request window (in ms) */
181
- recv_window?: number;
189
+ // recv_window: 5000, // 5000 = 5 seconds
182
190
 
183
- /** Default: false. If true, we'll throw errors if any params are undefined */
184
- strict_param_validation?: boolean;
191
+ /**
192
+ * Enable keep alive for REST API requests (via axios).
193
+ * See: https://github.com/tiagosiebler/bybit-api/issues/368
194
+ */
195
+ // keepAlive: true,
196
+
197
+ /**
198
+ * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over
199
+ * sockets being kept alive. Only relevant if keepAlive is set to true.
200
+ * Default: 1000 (defaults comes from https agent)
201
+ */
202
+ // keepAliveMsecs: 1000, // 1000 = 1 second
185
203
 
186
204
  /**
187
- * Optionally override API protocol + domain
188
- * e.g baseUrl: 'https://api.bytick.com'
205
+ * Optionally override API domain used:
206
+ * apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK',
189
207
  **/
190
- baseUrl?: string;
191
208
 
192
- /** Default: true. whether to try and post-process request exceptions. */
193
- parse_exceptions?: boolean;
209
+ // apiRegion: 'bytick',
194
210
 
195
211
  /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */
196
- parseAPIRateLimits?: boolean;
212
+ // parseAPIRateLimits: true,
197
213
 
198
- /** Default: false. Enable to throw error if rate limit parser fails */
199
- throwOnFailedRateLimitParse?: boolean;
214
+ /**
215
+ * Allows you to provide a custom "signMessage" function,
216
+ * e.g. to use node crypto's much faster createHmac method
217
+ *
218
+ * Look at examples/fasterHmacSign.ts for a demonstration:
219
+ */
220
+ // customSignMessageFn: (message: string, secret: string) => Promise<string>;
200
221
  };
201
222
 
202
223
  const API_KEY = 'xxx';
203
224
  const API_SECRET = 'yyy';
204
- const useTestnet = false;
205
225
 
206
226
  const client = new RestClientV5({
207
227
  key: API_KEY,
208
228
  secret: API_SECRET,
209
- testnet: useTestnet,
229
+ // demoTrading: true,
210
230
  // Optional: enable to try parsing rate limit values from responses
211
231
  // parseAPIRateLimits: true
212
232
  },
@@ -214,7 +234,7 @@ const client = new RestClientV5({
214
234
  );
215
235
 
216
236
  // For public-only API calls, simply don't provide a key & secret or set them to undefined
217
- // const client = new RestClientV5({});
237
+ // const client = new RestClientV5();
218
238
 
219
239
  client.getAccountInfo()
220
240
  .then(result => {
@@ -224,7 +244,7 @@ client.getAccountInfo()
224
244
  console.error("getAccountInfo error: ", err);
225
245
  });
226
246
 
227
- client.getOrderbook({ category: 'linear', symbol: 'BTCUSD' })
247
+ client.getOrderbook({ category: 'linear', symbol: 'BTCUSDT' })
228
248
  .then(result => {
229
249
  console.log("getOrderBook result: ", result);
230
250
  })
@@ -233,131 +253,252 @@ client.getOrderbook({ category: 'linear', symbol: 'BTCUSD' })
233
253
  });
234
254
  ```
235
255
 
236
- ## WebSockets
237
-
238
- All API groups can be used via a shared `WebsocketClient`. However, to listen to multiple API groups at once, you will need to make one WebsocketClient instance per API group.
239
-
240
- The WebsocketClient can be configured to a specific API group using the market parameter. These are the currently available API groups:
241
- | API Category | Market | Description |
242
- |:----------------------------: |:-------------------: |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
243
- | V5 Subscriptions | `market: 'v5'` | The [v5](https://bybit-exchange.github.io/docs/v5/ws/connect) websocket topics for all categories under one market. Use the subscribeV5 method when subscribing to v5 topics. |
244
-
245
256
  ---
246
257
 
247
- ### Older Websocket APIs
248
-
249
- The following API groups are still available in the WebsocketClient but are deprecated and may no longer work. They will be removed in the next major release:
250
-
251
- <details>
252
- <summary>Click me to see the table</summary>
253
-
254
- | API Category | Market | Description |
255
- | :------------------------------: | :-------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
256
- | ~~Unified Margin - Options~~ | `market: 'unifiedOption'` | The [derivatives v3](https://bybit-exchange.github.io/docs/derivativesV3/unified_margin/#t-websocket) category for unified margin. Note: public topics only support options topics. If you need USDC/USDT perps, use `unifiedPerp` instead. |
257
- | ~~Unified Margin - Perps~~ | `market: 'unifiedPerp'` | The [derivatives v3](https://bybit-exchange.github.io/docs/derivativesV3/unified_margin/#t-websocket) category for unified margin. Note: public topics only support USDT/USDC perpetual topics - use `unifiedOption` if you need public options topics. |
258
- | ~~Futures v2 - Inverse Perps~~ | `market: 'inverse'` | The [inverse v2 perps](https://bybit-exchange.github.io/docs/futuresV2/inverse/#t-websocket) category. |
259
- | ~~Futures v2 - USDT Perps~~ | `market: 'linear'` | The [USDT/linear v2 perps](https://bybit-exchange.github.io/docs/futuresV2/linear/#t-websocket) category. |
260
- | ~~Futures v2 - Inverse Futures~~ | `market: 'inverse'` | The [inverse futures v2](https://bybit-exchange.github.io/docs/futuresV2/inverse_futures/#t-websocket) category uses the same market as inverse perps. |
261
- | ~~Spot v3~~ | `market: 'spotv3'` | The [spot v3](https://bybit-exchange.github.io/docs/spot/v3/#t-websocket) category. |
262
- | ~~Spot v1~~ | `market: 'spot'` | The older [spot v1](https://bybit-exchange.github.io/docs/spot/v1/#t-websocket) category. Use the `spotv3` market if possible, as the v1 category does not have automatic re-subscribe if reconnected. |
263
- | ~~Copy Trading~~ | `market: 'linear'` | The [copy trading](https://bybit-exchange.github.io/docs/copy_trading/#t-websocket) category. Use the linear market to listen to all copy trading topics. |
264
- | ~~USDC Perps~~ | `market: 'usdcPerp` | The [USDC perps](https://bybit-exchange.github.io/docs/usdc/perpetual/#t-websocket) category. |
265
- | ~~USDC Options~~ | `market: 'usdcOption'` | The [USDC options](https://bybit-exchange.github.io/docs/usdc/option/#t-websocket) category. |
266
- | ~~Contract v3 USDT~~ | `market: 'contractUSDT'` | The [Contract V3](https://bybit-exchange.github.io/docs/derivativesV3/contract/#t-websocket) category (USDT perps) |
267
- | ~~Contract v3 Inverse~~ | `market: 'contractInverse'` | The [Contract V3](https://bybit-exchange.github.io/docs/derivativesV3/contract/#t-websocket) category (inverse perps) |
268
-
269
- </details
258
+ ## WebSockets
270
259
 
271
- ---
260
+ The WebsocketClient will automatically use the latest V5 WebSocket endpoints by default. To use a different endpoint, use the `market` parameter. Except for the WebSocket API - this can be accessed without any special configuration.
272
261
 
273
- ### WebSocket Examples
262
+ ## WebSocket Subscriptions - Consuming events
274
263
 
275
264
  Here's a minimal example for using the websocket client. For more complete examples, look into the ws-\* examples in the [examples](./examples/) folder in the repo on GitHub.
276
265
 
277
266
  ```javascript
278
267
  const { WebsocketClient } = require('bybit-api');
268
+ // or
269
+ // import { WebsocketClient } from 'bybit-api';
279
270
 
280
271
  const API_KEY = 'xxx';
281
272
  const PRIVATE_KEY = 'yyy';
282
273
 
283
274
  const wsConfig = {
284
- key: API_KEY,
285
- secret: PRIVATE_KEY,
275
+ /**
276
+ * API credentials are optional. They are only required if you plan on using
277
+ * any account-specific topics or the WS API
278
+ */
279
+ key: 'yourAPIKeyHere',
280
+ secret: 'yourAPISecretHere',
286
281
 
287
282
  /*
288
283
  The following parameters are optional:
289
284
  */
290
285
 
291
- // Connects to livenet by default. Set testnet to true to use the testnet environment.
286
+ /**
287
+ * Set to `true` to connect to Bybit's testnet environment.
288
+ * - If demo trading, `testnet` should be set to false!
289
+ * - If testing a strategy, use demo trading instead. Testnet market
290
+ * data is very different from real market conditions.
291
+ */
292
292
  // testnet: true
293
293
 
294
- // If you can, use the v5 market (the newest generation of Bybit's websockets)
295
- market: 'v5',
296
-
297
- // how long to wait (in ms) before deciding the connection should be terminated & reconnected
298
- // pongTimeout: 1000,
294
+ /**
295
+ * Set to `true` to connect to Bybit's V5 demo trading:
296
+ * https://bybit-exchange.github.io/docs/v5/demo
297
+ *
298
+ * Only the "V5" "market" is supported here.
299
+ */
300
+ // demoTrading; true;
301
+
302
+ // recv window size for websocket authentication (higher latency connections
303
+ // (VPN) can cause authentication to fail if the recv window is too small)
304
+ // recvWindow: 5000,
299
305
 
300
- // how often to check (in ms) that WS connection is still alive
306
+ /** How often to check if the connection is alive (in ms) */
301
307
  // pingInterval: 10000,
302
308
 
303
- // how long to wait before attempting to reconnect (in ms) after connection is closed
304
- // reconnectTimeout: 500,
305
-
306
- // recv window size for authenticated websocket requests (higher latency connections (VPN) can cause authentication to fail if the recv window is too small)
307
- // recvWindow: 5000,
308
-
309
- // config options sent to RestClient (used for time sync). See RestClient docs.
310
- // restOptions: { },
309
+ /**
310
+ * How long to wait (in ms) for a pong (heartbeat reply) before assuming the
311
+ * connection is dead
312
+ */
313
+ // pongTimeout: 1000,
311
314
 
312
- // config for axios used for HTTP requests. E.g for proxy support
313
- // requestOptions: { }
315
+ /** Delay in milliseconds before respawning the connection */
316
+ // reconnectTimeout: 500,
314
317
 
315
318
  // override which URL to use for websocket connections
316
319
  // wsUrl: 'wss://stream.bytick.com/realtime'
320
+
321
+ /**
322
+ * Allows you to provide a custom "signMessage" function, e.g. to use node's
323
+ * much faster createHmac method
324
+ *
325
+ * Look at examples/fasterHmacSign.ts for a demonstration:
326
+ */
327
+ // customSignMessageFn: (message: string, secret: string) => Promise<string>;
317
328
  };
318
329
 
319
330
  const ws = new WebsocketClient(wsConfig);
320
331
 
321
- // (before v5) subscribe to multiple topics at once
322
- ws.subscribe(['position', 'execution', 'trade']);
323
-
324
- // (before v5) and/or subscribe to individual topics on demand
325
- ws.subscribe('kline.BTCUSD.1m');
326
-
327
332
  // (v5) subscribe to multiple topics at once
328
333
  ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear');
329
334
 
330
- // (v5) and/or subscribe to individual topics on demand
335
+ // Or one at a time
336
+ ws.subscribeV5('kline.5.BTCUSDT', 'linear');
337
+ ws.subscribeV5('kline.5.ETHUSDT', 'linear');
338
+
339
+ // Private/public topics can be used in the same WS client instance, even for
340
+ // different API groups (linear, options, spot, etc)
331
341
  ws.subscribeV5('position', 'linear');
332
342
  ws.subscribeV5('publicTrade.BTC', 'option');
333
343
 
344
+ /**
345
+ * The Websocket Client will automatically manage all connectivity & authentication for you.
346
+ *
347
+ * If a network issue occurs, it will automatically:
348
+ * - detect it,
349
+ * - remove the dead connection,
350
+ * - replace it with a new one,
351
+ * - resubscribe to everything you were subscribed to.
352
+ *
353
+ * When this happens, you will see the "reconnected" event.
354
+ */
355
+
334
356
  // Listen to events coming from websockets. This is the primary data source
335
357
  ws.on('update', (data) => {
336
- console.log('update', data);
358
+ console.log('data received', JSON.stringify(data, null, 2));
337
359
  });
338
360
 
339
- // Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics)
361
+ // Optional: Listen to websocket connection open event
362
+ // (automatic after subscribing to one or more topics)
340
363
  ws.on('open', ({ wsKey, event }) => {
341
- console.log('connection open for websocket with ID: ' + wsKey);
364
+ console.log('connection open for websocket with ID: ', wsKey);
342
365
  });
343
366
 
344
- // Optional: Listen to responses to websocket queries (e.g. the response after subscribing to a topic)
367
+ // Optional: Listen to responses to websocket queries
368
+ // (e.g. the response after subscribing to a topic)
345
369
  ws.on('response', (response) => {
346
370
  console.log('response', response);
347
371
  });
348
372
 
349
- // Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected.
373
+ // Optional: Listen to connection close event.
374
+ // Unexpected connection closes are automatically reconnected.
350
375
  ws.on('close', () => {
351
376
  console.log('connection closed');
352
377
  });
353
378
 
354
- // Optional: Listen to raw error events. Recommended.
379
+ // Listen to raw error events. Recommended.
355
380
  ws.on('error', (err) => {
356
381
  console.error('error', err);
357
382
  });
383
+
384
+ ws.on('reconnect', ({ wsKey }) => {
385
+ console.log('ws automatically reconnecting.... ', wsKey);
386
+ });
387
+
388
+ ws.on('reconnected', (data) => {
389
+ console.log('ws has reconnected ', data?.wsKey);
390
+ });
358
391
  ```
359
392
 
360
- See [websocket-client.ts](./src/websocket-client.ts) for further information.
393
+ ## Websocket API - Sending orders via WebSockets
394
+
395
+ Bybit supports sending, amending and cancelling orders over a WebSocket connection. The [WebsocketClient](./src/WebsocketClient.ts) fully supports Bybit's WebSocket API.
396
+
397
+ Links for reference:
398
+ - [Bybit WebSocket API Documentation](https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline)
399
+ - [WebSocket API Example Node.js/TypeScript/JavaScript](./examples/ws-api-promises.ts).
400
+
401
+ Note: as of January 2024, the demo trading environment does not support the WebSocket API.
402
+
403
+ There are two ways to use the WS API, depending on individual preference:
404
+ - event-driven:
405
+ - send requests via `client.sendWSAPIRequest(wsKey, operation, params)`, fire and forget, don't use await
406
+ - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)`
407
+ - See example for more details: [examples/ws-api-events.ts](./examples/ws-api-events.ts)
408
+ - promise-driven:
409
+ - send requests via `const result = await client.sendWSAPIRequest(wsKey, operation, params)`, which returns a promise
410
+ - await each call
411
+ - use try/catch blocks to handle promise rejections
412
+ - See example for more details: [examples/ws-api-promises.ts](./examples/ws-api-promises.ts)
413
+
414
+ The below example demonstrates the promise-driven approach, which behaves similar to a REST API. The WebSocket API even accepts the same parameters as the corresponding REST API endpoints, so this approach should be compatible with existing REST implementations. Connectivity, authentication, and processing requests wrapped in promises - these are all handled automatically by the WebsocketClient without additional configuration.
415
+
416
+ ```javascript
417
+ const { WS_KEY_MAP, WebsocketClient } = require('bybit-api');
418
+
419
+ // or
420
+ // import { WS_KEY_MAP, WebsocketClient } from 'bybit-api';
421
+
422
+ // Create an instance of the WebsocketClient.
423
+ // This will automatically handle connectivity and authentication for you.
424
+ const wsClient = new WebsocketClient(
425
+ {
426
+ key: 'yourApiKeyHere',
427
+ secret: 'yourApiSecretHere',
428
+
429
+ // Whether to use the testnet environment.
430
+ // Create testnet API keys here: https://testnet.bybit.com/app/user/api-management
431
+ // testnet: true,
432
+
433
+ // Whether to use the livenet demo trading environment
434
+ // Note: As of Jan 2025, demo trading only supports consuming events, it does
435
+ // NOT support the WS API.
436
+ // demoTrading: false,
437
+ }
438
+ );
439
+
440
+ // This example is wrapped in an async function, so "await" can be used
441
+ async function main() {
442
+ /**
443
+ * Optional. Can be used to prepare a connection before sending
444
+ * commands (e.g. as part of your startup process).
445
+ *
446
+ * This is not necessary and will happen automatically when
447
+ * sending a command, if you aren't connected/authenticated yet.
448
+ */
449
+ // await wsClient.connectWSAPI();
450
+
451
+ try {
452
+ console.log('Step 1: Create an order');
453
+
454
+ // The type for `wsAPISubmitOrderResult` is automatically
455
+ // resolved to `WSAPIResponse<OrderResultV5, "order.create">`
456
+ const wsAPISubmitOrderResult = await wsClient.sendWSAPIRequest(
457
+ WS_KEY_MAP.v5PrivateTrade,
458
+ 'order.create',
459
+ {
460
+ symbol: 'BTCUSDT',
461
+ side: 'Buy',
462
+ orderType: 'Limit',
463
+ price: '50000',
464
+ qty: '1',
465
+ category: 'linear',
466
+ },
467
+ );
468
+
469
+ console.log(
470
+ `Step 1: Order result (order ID: "${wsAPISubmitOrderResult.data.orderId}"): `,
471
+ wsAPISubmitOrderResult,
472
+ );
473
+ } catch (e) {
474
+ console.error('Step 1: Order submit exception: ', e);
475
+ }
476
+ }
477
+
478
+ // Start executing the example workflow
479
+ main();
480
+
481
+ ```
482
+
483
+ See the [examples/ws-api-promises.ts](./examples/ws-api-promises.ts) example for a more detailed explanation.
484
+
485
+ ---
486
+
487
+ ### Balancing load across multiple connections
488
+
489
+ The WebsocketClient will automatically prepare one connection per API group, for all topics in that API group. Any topics that you subscribe to on that WebSocket client will automatically be added to the same connection.
490
+
491
+ To spread your subscribed topics over multiple connections, e.g. to reduce the throughput of an individual connectionk, you can make one instance of the WebsocketClient per connection group.
492
+
493
+ ```typescript
494
+ const wsClientGroup1 = new WebsocketClient();
495
+ const wsClientGroup2 = new WebsocketClient();
496
+
497
+ // Attach event listeners to each WS Client
498
+ // Divide your desired topics into separate groups
499
+ ```
500
+
501
+ Important: do not subscribe to the same topics on both clients or you will receive duplicate messages (once per WS client).
361
502
 
362
503
  ---
363
504
 
@@ -370,13 +511,13 @@ Pass a custom logger (or mutate the imported DefaultLogger class) which supports
370
511
  ```javascript
371
512
  const { WebsocketClient, DefaultLogger } = require('bybit-api');
372
513
 
373
- // Disable all logging on the silly level
514
+ // Enable all logging on the trace level (disabled by default)
374
515
  const customLogger = {
375
516
  ...DefaultLogger,
376
- silly: () => {},
517
+ trace: (...params) => console.log('trace', ...params),
377
518
  };
378
519
 
379
- const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, customLogger);
520
+ const wsClient = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, customLogger);
380
521
  ```
381
522
 
382
523
  ### Debug HTTP requests
@@ -391,16 +532,13 @@ This is the "modern" way, allowing the package to be directly imported into fron
391
532
 
392
533
  1. Install these dependencies
393
534
  ```sh
394
- npm install crypto-browserify stream-browserify
535
+ npm install stream-browserify
395
536
  ```
396
537
  2. Add this to your `tsconfig.json`
397
538
  ```json
398
539
  {
399
540
  "compilerOptions": {
400
541
  "paths": {
401
- "crypto": [
402
- "./node_modules/crypto-browserify"
403
- ],
404
542
  "stream": [
405
543
  "./node_modules/stream-browserify"
406
544
  ]
@@ -437,23 +575,8 @@ Have my projects helped you? Share the love, there are many ways you can show yo
437
575
  - Or buy me all the coffee:
438
576
  - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` <!-- metamask -->
439
577
 
440
- <!---
441
- old ones:
442
- - BTC: `1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk`
443
- - BTC(SegWit): `bc1ql64wr9z3khp2gy7dqlmqw7cp6h0lcusz0zjtls`
444
- - ETH(ERC20): `0xe0bbbc805e0e83341fadc210d6202f4022e50992`
445
- - USDT(TRC20): `TA18VUywcNEM9ahh3TTWF3sFpt9rkLnnQa
446
- -->
447
578
  <!-- template_contributions_end -->
448
579
 
449
- #### pixtron
450
-
451
- An early generation of this library was started by @pixtron. If this library helps you to trade better on bybit, feel free to donate a coffee to @pixtron:
452
-
453
- - BTC `1Fh1158pXXudfM6ZrPJJMR7Y5SgZUz4EdF`
454
- - ETH `0x21aEdeC53ab7593b77C9558942f0c9E78131e8d7`
455
- - LTC `LNdHSVtG6UWsriMYLJR3qLdfVNKwJ6GSLF`
456
-
457
580
  ### Contributions & Pull Requests
458
581
 
459
582
  Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.