Skip to content

Commit 1c4a545

Browse files
committed
feat(): websocket API integration for V3, including examples & docs.
1 parent 22c39ca commit 1c4a545

16 files changed

+1377
-51
lines changed

README.md

Lines changed: 240 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@
2222
Updated & performant JavaScript & Node.js SDK for the Bitget V2 REST APIs and WebSockets:
2323

2424
- Complete integration with all Bitget APIs.
25+
- [x] Supports V1 REST APIs & WebSockets
26+
- [x] Supports V2 REST APIs & WebSockets
27+
- [x] Supports V3/UTA REST APIs & WebSockets
28+
- [x] Supports order placement via V3 WebSocket API
2529
- TypeScript support (with type declarations for most API requests & responses).
2630
- Over 100 integration tests making real API calls & WebSocket connections, validating any changes before they reach npm.
2731
- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
@@ -64,7 +68,8 @@ Check out my related JavaScript/TypeScript/Node.js projects:
6468

6569
Most methods pass values as-is into HTTP requests. These can be populated using parameters specified by Bitget's API documentation, or check the type definition in each class within this repository (see table below for convenient links to each class).
6670

67-
- [Bitget API Documentation](https://www.bitget.com/api-doc/common/intro).
71+
- [Bitget API V2 Documentation](https://www.bitget.com/api-doc/common/intro).
72+
- [Bitget API V3/UTA Documentation](https://www.bitget.com/api-doc/uta/intro).
6873
- [REST Endpoint Function List](./docs/endpointFunctionList.md)
6974

7075
## Structure
@@ -85,12 +90,15 @@ The version on npm is the output from the `build` command and can be used in pro
8590
Each REST API group has a dedicated REST client. To avoid confusion, here are the available REST clients and the corresponding API groups:
8691
| Class | Description |
8792
|:------------------------------------: |:---------------------------------------------------------------------------------------------: |
93+
| [RestClientV3](src/rest-client-v3.ts) | [V3/UTA REST APIs for Bitget's Unified Trading Account](https://www.bitget.com/api-doc/uta/intro) |
94+
| [WebsocketClientV3](src/websocket-client-v3.ts) | Universal WS client for Bitget's V3/UTA WebSockets |
95+
| [WebsocketAPIClient](src/websocket-api-client.ts) | Websocket API Client, for RESTlike order placement via Bitget's V3/UTA WebSocket API |
8896
| [RestClientV2](src/rest-client-v2.ts) | [V2 REST APIs](https://www.bitget.com/api-doc/common/intro) |
89-
| [WebsocketClientV2](src/websocket-client-v2.ts) | Universal client for all Bitget's V2 Websockets |
97+
| [WebsocketClientV2](src/websocket-client-v2.ts) | Universal WS client for all Bitget's V2 WebSockets |
9098
| [~~SpotClient~~ (deprecated, use RestClientV2)](src/spot-client.ts) | [~~Spot APIs~~](https://bitgetlimited.github.io/apidoc/en/spot/#introduction) |
9199
| [~~FuturesClient~~ (deprecated, use RestClientV2)](src/futures-client.ts) | [~~Futures APIs~~](https://bitgetlimited.github.io/apidoc/en/mix/#introduction) |
92100
| [~~BrokerClient~~ (deprecated, use RestClientV2)](src/broker-client.ts) | [~~Broker APIs~~](https://bitgetlimited.github.io/apidoc/en/broker/#introduction) |
93-
| [~~WebsocketClient~~ (deprecated, use WebsocketClientV2)](src/websocket-client.ts) | ~~Universal client for all Bitget's V1 Websockets~~ |
101+
| [~~WebsocketClient~~ (deprecated, use WebsocketClientV2)](src/websocket-client.ts) | ~~Universal client for all Bitget's V1 WebSockets~~ |
94102

95103
Examples for using each client can be found in:
96104

@@ -103,14 +111,30 @@ If you're missing an example, you're welcome to request one. Priority will be gi
103111

104112
First, create API credentials on Bitget's website.
105113

106-
All REST endpoints should be included in the [RestClientV2](src/rest-client-v2.ts) class. If any endpoints are missing or need improved types, pull requests are very welcome. You can also open an issue on this repo to request an improvement. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler).
114+
All REST APIs are integrated in each dedicated Rest Client class. See the above table for which REST client to use. If you've upgraded to the Unified Trading Account, you should use the V3 REST APIs and WebSockets.
115+
116+
#### V3 REST APIs
117+
118+
These are only available if you have upgraded to the Unified Trading Account. If not, use the V2 APIs instead.
119+
120+
```javascript
121+
import { RestClientV3 } from 'bitget-api';
122+
// or if you prefer require:
123+
// const { RestClientV3 } = require('bitget-api');
124+
125+
// TODO: REST V3 example here, similar to V2
126+
```
127+
128+
#### V2 REST APIs
107129

108130
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.
109131

110-
If you found the method you're looking for in the API docs, you can also search for the endpoint in the [RestClientV2](src/rest-client-v2.ts) class.
132+
If you found the method you're looking for in the API docs, you can also search for the endpoint in the [RestClientV2](src/rest-client-v2.ts) class. This class has all V2 endpoints available.
111133

112134
```javascript
113-
const { RestClientV2 } = require('bitget-api');
135+
import { RestClientV2 } from 'bitget-api';
136+
// or if you prefer require:
137+
// const { RestClientV2 } = require('bitget-api');
114138

115139
const API_KEY = 'xxx';
116140
const API_SECRET = 'yyy';
@@ -122,7 +146,6 @@ const client = new RestClientV2(
122146
apiSecret: API_SECRET,
123147
apiPass: API_PASS,
124148
},
125-
// requestLibraryOptions
126149
);
127150

128151
// For public-only API calls, simply don't provide a key & secret or set them to undefined
@@ -153,6 +176,213 @@ client
153176

154177
#### WebSockets
155178

179+
All WebSocket functionality is supported via the WebsocketClient. Since there are currently 3 generations of Bitget's API, there are 3 WebsocketClient classes in this Node.js, JavaScript & TypeScript SDK for Bitget.
180+
181+
Use the following guidance to decide which one to use:
182+
- Unified Trading Account / V3 (latest generation):
183+
- For receiving data, use the [WebsocketClientV3](./src/websocket-client-v3.ts).
184+
- For sending orders via WebSockets, use the [WebsocketAPIClient](./src/websocket-api-client.ts).
185+
- V2 (not upgraded to Unified Trading Account yet)
186+
- Use the [WebsocketClientV2](./src/websocket-client-v2.ts).
187+
- V1 (deprecated)
188+
- This is the oldest API group supported by Bitget. You should migrate to V3 or V2 as soon as possible.
189+
- If you're not ready to migrate, you can use the [WebsocketClientLegacyV1](./src/websocket-client-legacy-v1.ts) class in the meantime.
190+
191+
Higher level examples below, while more thorough examples can be found in the examples folder on GitHub.
192+
193+
##### V3 Unified Trading Account
194+
195+
###### Sending orders via WebSockets
196+
197+
The V3 / Unified Trading Account APIs introduce order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API.
198+
199+
There are two approaches to placing orders via the Bitget WebSocket APIs. The recommended route is to use the dedicated WebsocketAPIClient class, included with this SDK.
200+
201+
This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types.
202+
203+
A simple example is below, but for a more thorough example, check the example here: [./examples/V3/ws-api-client-trade.ts](./examples/V3/ws-api-client-trade.ts)
204+
205+
```typescript
206+
import { WebsocketAPIClient } from "bitget-api";
207+
// or if you prefer require:
208+
// const { WebsocketAPIClient } = require("bitget-api");
209+
210+
// Make an instance of the WS API Client class with your API keys
211+
const wsClient = new WebsocketAPIClient(
212+
{
213+
apiKey: API_KEY,
214+
apiSecret: API_SECRET,
215+
apiPass: API_PASS,
216+
217+
// Whether to use the demo trading wss connection
218+
// demoTrading: true,
219+
}
220+
);
221+
222+
async function start() {
223+
// Start using it like a REST API. All actions are sent via a persisted WebSocket connection.
224+
225+
/**
226+
* Place Order
227+
* https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters
228+
*/
229+
try {
230+
const res = await wsClient.submitNewOrder('spot', {
231+
orderType: 'limit',
232+
price: '100',
233+
qty: '0.1',
234+
side: 'buy',
235+
symbol: 'BTCUSDT',
236+
timeInForce: 'gtc',
237+
});
238+
239+
console.log(new Date(), 'WS API "submitNewOrder()" result: ', res);
240+
} catch (e) {
241+
console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e);
242+
}
243+
}
244+
245+
start().catch(e => console.error("Exception in example: ". e));
246+
```
247+
248+
###### Receiving realtime data
249+
250+
Use the WebsocketClientV3 to receive data via the V3 WebSockets
251+
252+
```typescript
253+
import { WebsocketClientV3 } from "bitget-api";
254+
// or if you prefer require:
255+
// const { WebsocketClientV3 } = require("bitget-api");
256+
257+
const API_KEY = "yourAPIKeyHere";
258+
const API_SECRET = "yourAPISecretHere;
259+
const API_PASS = "yourAPIPassHere";
260+
261+
const wsClient = new WebsocketClientV3(
262+
{
263+
// Only necessary if you plan on using private/account websocket topics
264+
apiKey: API_KEY,
265+
apiSecret: API_SECRET,
266+
apiPass: API_PASS,
267+
}
268+
);
269+
270+
// Connect event handlers to process incoming events
271+
wsClient.on('update', (data) => {
272+
console.log('WS raw message received ', data);
273+
// console.log('WS raw message received ', JSON.stringify(data, null, 2));
274+
});
275+
276+
wsClient.on('open', (data) => {
277+
console.log('WS connection opened:', data.wsKey);
278+
});
279+
wsClient.on('response', (data) => {
280+
console.log('WS response: ', JSON.stringify(data, null, 2));
281+
});
282+
wsClient.on('reconnect', ({ wsKey }) => {
283+
console.log('WS automatically reconnecting.... ', wsKey);
284+
});
285+
wsClient.on('reconnected', (data) => {
286+
console.log('WS reconnected ', data?.wsKey);
287+
});
288+
wsClient.on('exception', (data) => {
289+
console.log('WS error', data);
290+
});
291+
292+
/**
293+
* Subscribe to topics as you wish
294+
*/
295+
296+
// You can subscribe to one topic at a time
297+
wsClient.subscribe(
298+
{
299+
topic: 'account',
300+
payload: {
301+
instType: 'UTA', // Note: all account events go on the UTA instType
302+
},
303+
},
304+
WS_KEY_MAP.v3Private, // This parameter points to private or public
305+
);
306+
307+
// Note: all account events go on the UTA instType
308+
const ACCOUNT_INST_TYPE = 'UTA';
309+
const ACCOUNT_WS_KEY = WS_KEY_MAP.v3Private;
310+
311+
// Or multiple at once:
312+
wsClient.subscribe(
313+
[
314+
{
315+
topic: 'account',
316+
payload: {
317+
instType: ACCOUNT_INST_TYPE,
318+
},
319+
},
320+
{
321+
topic: 'position',
322+
payload: {
323+
instType: ACCOUNT_INST_TYPE,
324+
},
325+
},
326+
{
327+
topic: 'fill',
328+
payload: {
329+
instType: ACCOUNT_INST_TYPE,
330+
},
331+
},
332+
{
333+
topic: 'order',
334+
payload: {
335+
instType: ACCOUNT_INST_TYPE,
336+
},
337+
},
338+
],
339+
ACCOUNT_WS_KEY,
340+
);
341+
342+
// Example public events
343+
wsClient.subscribe(
344+
[
345+
{
346+
topic: 'ticker',
347+
payload: {
348+
instType: 'spot',
349+
symbol: 'BTCUSDT',
350+
},
351+
},
352+
{
353+
topic: 'ticker',
354+
payload: {
355+
instType: 'spot',
356+
symbol: 'ETHUSDT',
357+
},
358+
},
359+
{
360+
topic: 'ticker',
361+
payload: {
362+
instType: 'spot',
363+
symbol: 'XRPUSDT',
364+
},
365+
},
366+
{
367+
topic: 'ticker',
368+
payload: {
369+
instType: 'usdt-futures',
370+
symbol: 'BTCUSDT',
371+
},
372+
},
373+
{
374+
topic: 'ticker',
375+
payload: {
376+
instType: 'usdt-futures',
377+
symbol: 'BTCUSDT',
378+
},
379+
},
380+
],
381+
WS_KEY_MAP.v3Public,
382+
);
383+
```
384+
385+
156386
For more examples, including how to use websockets with Bitget, check the [examples](./examples/) and [test](./test/) folders.
157387

158388
---
@@ -164,7 +394,9 @@ For more examples, including how to use websockets with Bitget, check the [examp
164394
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.
165395

166396
```javascript
167-
const { WebsocketClientV2, DefaultLogger } = require('bitget-api');
397+
import { WebsocketClientV2, DefaultLogger } from 'bitget-api';
398+
// or if you prefer require:
399+
// const { WebsocketClientV2, DefaultLogger } = require('bitget-api');
168400

169401
// Disable all logging on the trace level (less console logs)
170402
const customLogger = {

examples/README.md

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,70 @@ These newer examples are for Bitget's V3 APIs and WebSockets. They can be found
1919
Refer to the V3 / UTA API documentation for more information on the V3 APIs:
2020
https://www.bitget.com/api-doc/uta/intro
2121

22-
These APIs require your account to be permanently upgraded to the Unified Trading Account, if you plan on using the account-level REST APIs and WebSockets.
22+
These APIs require your account to be permanently upgraded to the Unified Trading Account, if you plan on using the account-level REST APIs and WebSockets. Once upgraded, the V2 APIs are no longer available to you.
23+
24+
### WebSocket API (WS API)
25+
26+
The V3/UTA API introduces order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API.
27+
28+
There are two approaches to placing orders via the Bitget WebSocket APIs
29+
30+
#### WebsocketAPIClient (recommended)
31+
32+
This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types.
33+
34+
This is the recommended approach to easily start sending orders via an automatically persisted WebSocket connection. A simple example is below, but for a more thorough example, check the example here: [./V3/ws-api-client-trade.ts](./V3/ws-api-client-trade.ts)
35+
36+
```typescript
37+
import { WebsocketAPIClient } from "bitget-api";
38+
// or if you prefer require:
39+
// const { WebsocketAPIClient } = require("bitget-api");
40+
41+
// Make an instance of the WS API Client class with your API keys
42+
const wsClient = new WebsocketAPIClient(
43+
{
44+
apiKey: API_KEY,
45+
apiSecret: API_SECRET,
46+
apiPass: API_PASS,
47+
48+
// Whether to use the demo trading wss connection
49+
// demoTrading: true,
50+
}
51+
);
52+
53+
async function start() {
54+
// Start using it like a REST API. All actions are sent via a persisted WebSocket connection.
55+
56+
/**
57+
* Place Order
58+
* https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters
59+
*/
60+
try {
61+
const res = await wsClient.submitNewOrder('spot', {
62+
orderType: 'limit',
63+
price: '100',
64+
qty: '0.1',
65+
side: 'buy',
66+
symbol: 'BTCUSDT',
67+
timeInForce: 'gtc',
68+
});
69+
70+
console.log(new Date(), 'WS API "submitNewOrder()" result: ', res);
71+
} catch (e) {
72+
console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e);
73+
}
74+
}
75+
76+
start().catch(e => console.error("Exception in example: ". e));
77+
```
78+
79+
#### ws.sendWSAPIRequest(wsKey, command, category, operation)
80+
81+
This is the "raw" integration within the existing WebSocket client. It uses an automatically persisted & authenticated connection to send events through Bitget's WebSocket API. It automatically tracks and connects outgoing requests with incoming responses, and returns promises that resolve/reject when a matching response is received.
82+
83+
Refer to [V3/ws-api-trade-raw.ts](./V3/ws-api-trade-raw.ts) to see an example.
84+
85+
Note: The WebsocketClient is built around this. For a more user friendly experience, it is recommended to use the WebsocketClient for WS API requests. It uses this method but has the convenience of behaving similar to a REST API (while all communication automatically happens over a persisted WebSocket connection).
2386

2487
## V2
2588

0 commit comments

Comments
 (0)