Skip to content

Commit

Permalink
Merge pull request #383 from tiagosiebler/obspotexample
Browse files Browse the repository at this point in the history
v2.9.1: add typeguard for formatted orderbook events, with example
  • Loading branch information
tiagosiebler authored Jan 17, 2024
2 parents de767a5 + 203b750 commit 023c46f
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 7 deletions.
70 changes: 70 additions & 0 deletions examples/ws-public-spot-orderbook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import {
WebsocketClient,
DefaultLogger,
isWsPartialBookDepthEventFormatted,
getContextFromWsKey,
} from '../src';

// or, with the npm package
/*
import {
WebsocketClient,
DefaultLogger,
isWsFormattedTrade,
} from 'binance';
*/

(async () => {
const logger = {
...DefaultLogger,
// silly: () => {},
};

const wsClient = new WebsocketClient(
{
beautify: true,
},
logger,
);

/**
* Simple example for receiving depth snapshots from spot orderbooks
*/
wsClient.on('formattedMessage', (data) => {
if (isWsPartialBookDepthEventFormatted(data)) {
const context = getContextFromWsKey(data.wsKey);

if (!context?.symbol) {
throw new Error(`Failed to extract context from event?`);
}

console.log(`ws book event for "${context.symbol.toUpperCase()}"`, data);
return;
}

console.log('log formattedMessage: ', data);
});

wsClient.on('open', (data) => {
console.log('connection opened open:', data.wsKey, data.ws.target.url);
});
wsClient.on('reply', (data) => {
console.log('log reply: ', JSON.stringify(data, null, 2));
});
wsClient.on('reconnecting', (data) => {
console.log('ws automatically reconnecting.... ', data?.wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});

// Request subscription to the following symbol trade events:
const symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT'];
// const symbols = ['BTCUSDT'];

// Loop through symbols
for (const symbol of symbols) {
console.log('subscribing to trades for: ', symbol);
wsClient.subscribePartialBookDepths(symbol, 20, 1000, 'spot');
}
})();
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "binance",
"version": "2.9.0",
"version": "2.9.1",
"description": "Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & end-to-end tests.",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
6 changes: 3 additions & 3 deletions src/types/websockets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw
s: string;
i: number;
r: string;
}
};
}

export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted
Expand All @@ -706,7 +706,7 @@ export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted
symbol: string;
orderId: number;
reason: string;
}
};
}

export interface WsMessageFuturesUserDataOrderTradeUpdateEventRaw
Expand Down Expand Up @@ -883,4 +883,4 @@ export interface WsMessageForceOrderRaw extends WsSharedBase {
z: string;
T: number;
};
}
}
7 changes: 7 additions & 0 deletions src/util/typeGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
WsMessageKlineFormatted,
WsMessageKlineRaw,
WsMessageMarkPriceUpdateEventFormatted,
WsMessagePartialBookDepthEventFormatted,
WsMessageRollingWindowTickerFormatted,
WsMessageRollingWindowTickerRaw,
WsMessageSpotBalanceUpdateFormatted,
Expand Down Expand Up @@ -117,6 +118,12 @@ export function isWsAggTradeFormatted(
return !Array.isArray(data) && data.eventType === 'aggTrade';
}

export function isWsPartialBookDepthEventFormatted(
data: WsFormattedMessage,
): data is WsMessagePartialBookDepthEventFormatted {
return !Array.isArray(data) && data.eventType === 'partialBookDepth';
}

export function isWsFormattedUserDataEvent(
data: WsFormattedMessage,
): data is WsUserDataEvents {
Expand Down
8 changes: 7 additions & 1 deletion src/websocket-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1558,7 +1558,13 @@ export class WebsocketClient extends EventEmitter {
}

/**
* Subscribe to partial book depths. Note, spot only supports 1000ms or 100ms for updateMs, while futures only support 100, 250 or 500ms.
* Subscribe to partial book depths (snapshots).
*
* Note:
* - spot only supports 1000ms or 100ms for updateMs
* - futures only support 100, 250 or 500ms for updateMs
*
* Use getContextFromWsKey(data.wsKey) to extract symbol from events
*/
public subscribePartialBookDepths(
symbol: string,
Expand Down

0 comments on commit 023c46f

Please sign in to comment.