Skip to content

Commit

Permalink
feat(): better examples
Browse files Browse the repository at this point in the history
  • Loading branch information
tiagosiebler committed Jun 4, 2024
1 parent bea0ec2 commit fec7070
Show file tree
Hide file tree
Showing 3 changed files with 143 additions and 16 deletions.
47 changes: 31 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,15 +135,15 @@ const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';

const wsConfig = {
key: API_KEY,
secret: PRIVATE_KEY,
apiKey: API_KEY,
apiSecret: PRIVATE_KEY,

/*
The following parameters are optional:
*/

// defaults to false == testnet. Set to true for livenet.
// livenet: true
// Livenet is used by default, use this to enable testnet:
// useTestnet: true

// how long to wait (in ms) before deciding the connection should be terminated & reconnected
// pongTimeout: 1000,
Expand All @@ -163,28 +163,44 @@ const wsConfig = {

const ws = new WebsocketClient(wsConfig);

const tickersRequestWithParams = {
topic: 'spot.tickers',
params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
/**
* Subscribing to data:
**/

const userOrders = {
topic: 'spot.orders',
payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
};

const userTrades = {
topic: 'spot.usertrades',
payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
};

const rawTradesRequestWithParams = {
topic: 'spot.trades',
params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
const userPriceOrders = {
topic: 'spot.priceorders',
payload: ['!all'],
};

// subscribe to multiple topics at once
ws.subscribe([tickersRequestWithParams, rawTradesRequestWithParams], 'spotV4');
ws.subscribe([userOrders, userTrades, userPriceOrders], 'spotV4');

// and/or subscribe to individual topics on demand
ws.subscribe(
{
topic: 'spot.trades',
params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'],
topic: 'spot.priceorders',
payload: ['!all'],
},
'spotV4',
);

// Some topics don't need params, for those you can just subscribe with a string (or use a topic + payload object as above)
ws.subscribe('spot.balances', 'spotV4');

/**
* Handling events:
**/

// Listen to events coming from websockets. This is the primary data source
ws.on('update', (data) => {
console.log('data', data);
Expand All @@ -195,7 +211,7 @@ ws.on('open', ({ wsKey, event }) => {
console.log('connection open for websocket with ID: ' + wsKey);
});

// Optional: Listen to responses to websocket queries (e.g. the response after subscribing to a topic)
// Optional: Listen to responses to websocket queries (e.g. the reply after subscribing to a topic)
ws.on('response', (response) => {
console.log('response', response);
});
Expand All @@ -211,13 +227,12 @@ ws.on('exception', (data) => {
});

// Optional: Listen to raw error events.
// Note: responses to invalid topics are currently only sent in the "response" event.
ws.on('error', (err) => {
console.error('ERR', err);
});
```

See [websocket-client.ts](./src/websocket-client.ts) for further information.
See [websocket-client.ts](./src/websocket-client.ts) for further information and make sure to check the [examples](./examples/) folder for much more detail.

---

Expand Down
112 changes: 112 additions & 0 deletions examples/ws-private-perp-futures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { LogParams, WebsocketClient } from '../src';
import { WsTopicRequest } from '../src/lib/websocket/websocket-util';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const account = {
key: process.env.API_KEY || 'apiKeyHere',
secret: process.env.API_SECRET || 'apiSecretHere',
};

const customLogger = {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
trace: (...params: LogParams): void => {
// console.log(new Date(), 'trace', ...params);
},
info: (...params: LogParams): void => {
console.log(new Date(), 'info', ...params);
},
error: (...params: LogParams): void => {
console.error(new Date(), 'error', ...params);
},
};

async function start() {
const client = new WebsocketClient(
{
apiKey: account.key,
apiSecret: account.secret,
},
customLogger,
);

// console.log('auth with: ', account);
client.on('open', (data) => {
console.log('connected ', data?.wsKey);
});

// Data received
client.on('update', (data) => {
console.info('data received: ', JSON.stringify(data));
});

// Something happened, attempting to reconenct
client.on('reconnect', (data) => {
console.log('reconnect: ', data);
});

// Reconnect successful
client.on('reconnected', (data) => {
console.log('reconnected: ', data);
});

// Connection closed. If unexpected, expect reconnect -> reconnected.
client.on('close', (data) => {
console.error('close: ', data);
});

// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
client.on('response', (data) => {
console.info('server reply: ', JSON.stringify(data), '\n');
});

client.on('exception', (data) => {
console.error('exception: ', data);
});

client.on('authenticated', (data) => {
console.error('authenticated: ', data);
});

try {
// TODO: many private topics use your user ID
const myUserID = '20011';

/**
* Either send one topic (with params) at a time
*/
// client.subscribe({
// topic: 'futures.usertrades',
// payload: [myUserID, '!all'],
// }, 'spotV4');

/**
* Or send multiple topics in a batch (grouped by ws connection (WsKey))
* You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call:
*/

const userBalances: WsTopicRequest = {
topic: 'futures.balances',
payload: [myUserID],
};

const userTrades: WsTopicRequest = {
topic: 'futures.usertrades',
payload: [myUserID, '!all'],
};

const userLiquidates: WsTopicRequest = {
topic: 'futures.liquidates',
payload: [myUserID, '!all'],
};

client.subscribe(
[userBalances, userTrades, userLiquidates],
'perpFuturesUSDTV4',
);
} catch (e) {
console.error(`Req error: `, e);
}
}

start();
File renamed without changes.

0 comments on commit fec7070

Please sign in to comment.