Skip to content

Commit 1580e9c

Browse files
authored
Merge pull request #59 from JJ-Cro/wsapiReadme
chore(): updated readme, added endpoint map for wsclient
2 parents 4237e78 + 54d5d54 commit 1580e9c

File tree

2 files changed

+156
-150
lines changed

2 files changed

+156
-150
lines changed

README.md

Lines changed: 81 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -252,108 +252,114 @@ See [WebsocketClient](./src/WebsocketClient.ts) for further information and make
252252

253253
### Websocket API
254254

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.
256264

257265
- event-driven:
258-
- send requests via `client.sendWSAPIRequest(wsKey, channel, params).catch(e => console.error('WS API
259-
exception for channel', channel, e))`, 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
260267
- handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)`
261268
- promise-driven:
262269
- send requests via `const result = await client.sendWSAPIRequest(wsKey, channel, params)`, which returns a promise
263270
- await each call
264271
- use try/catch blocks to handle promise rejections
265272

266-
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.
267280

268281
```javascript
269-
const { WebsocketClient } = require('gateio-api');
282+
const { WebsocketAPIClient } = require('gateio-api');
270283

271284
const API_KEY = 'xxx';
272-
const PRIVATE_KEY = 'yyy';
285+
const API_SECRET = 'yyy';
273286

274287
async function start() {
275-
const client = new WebsocketClient({
288+
// Make an instance of the WS API Client
289+
const wsClient = new WebsocketAPIClient({
276290
apiKey: API_KEY,
277-
apiSecret: PRIVATE_KEY,
291+
apiSecret: API_SECRET,
278292
// Automatically re-auth WS API, if we were auth'd before and get reconnected
279293
reauthWSAPIOnReconnect: true,
280294
});
281295

282-
/**
283-
* Setup basic event handlers for core connectivity events.
284-
* Note for this approach, the `response` and `update` events are not needed (but you can use them too/instead if you prefer).
285-
**/
286-
287-
// Successfully connected
288-
client.on('open', (data) => {
289-
console.log(new Date(), 'ws connected ', data?.wsKey);
290-
});
291-
292-
// Something happened, attempting to reconnect
293-
client.on('reconnect', (data) => {
294-
console.log(new Date(), 'ws reconnect: ', data);
295-
});
296-
297-
// Reconnect successful
298-
client.on('reconnected', (data) => {
299-
console.log(new Date(), 'ws reconnected: ', data);
300-
});
301-
302-
// Connection closed. If unexpected, expect reconnect -> reconnected.
303-
client.on('close', (data) => {
304-
console.error(new Date(), 'ws close: ', data);
305-
});
306-
307-
client.on('exception', (data) => {
308-
console.error(new Date(), 'ws exception: ', data);
309-
});
310-
311-
client.on('authenticated', (data) => {
312-
console.error(new Date(), 'ws authenticated: ', data);
313-
});
314-
315296
try {
316-
/**
317-
* All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method.
318-
*/
319-
320-
// The WSKey identifies which connection this request is for.
321-
// (e.g. "spotV4" | "perpFuturesUSDTV4" | "perpFuturesBTCV4" | "deliveryFuturesUSDTV4" | "deliveryFuturesBTCV4" | "optionsV4")
322-
const wsKey = 'spotV4';
323-
324-
/**
325-
* To authenticate, send an empty request to "spot.login". The SDK will handle all the parameters.
326-
*
327-
* 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.
328-
*/
329-
console.log(new Date(), 'try authenticate');
330-
const loginResult = await client.sendWSAPIRequest(wsKey, 'spot.login');
331-
console.log(new Date(), 'authenticated!', loginResult);
332-
333-
/**
334-
* For other channels, you should include any parameters for the request (the payload) in your call.
335-
*
336-
* Note that internal parameters such as "signature" etc are all handled automatically by the SDK. Only the core request parameters are needed.
337-
*/
338-
console.log(new Date(), 'try get order status');
339-
const orderStatus = await client.sendWSAPIRequest(
340-
wsKey,
341-
'spot.order_status',
342-
{
343-
order_id: '600995435390',
344-
currency_pair: 'BTC_USDT',
345-
},
346-
);
347-
348-
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);
349353
} catch (e) {
350-
console.error(`WS API Error: `, e);
354+
console.error('WS API Error:', e);
351355
}
352356
}
353357

354358
start();
355359
```
356360

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+
357363
---
358364

359365
## Customise Logging

0 commit comments

Comments
 (0)