Background
As someone who worked with data for entire of my career, I always love to learn how to build a useful live data dashboard. One of the problems for build a live data dashboard comes with live data. Most live data are behind a hefty price wall and not really accessible to most people. However, Binance has a wonderful public Websocket API and it is really useful for anyone to learn!
In this blog, I am going to share my experience in learning websocket. This is the link to the final product.
Websocket API
The websocket API we are going to use is the miniticker, which we can receive the latest closing price. According to the document, this is the payload
{
"e": "24hrMiniTicker", // Event type
"E": 123456789, // Event time
"s": "BNBBTC", // Symbol
"c": "0.0025", // Close price
"o": "0.0010", // Open price
"h": "0.0025", // High price
"l": "0.0010", // Low price
"v": "10000", // Total traded base asset volume
"q": "18" // Total traded quote asset volume
}
In order to receive the miniTicker socket stream, we would need to subscribe to it. What it means is that, we need to send below json to websocket url, say if we want to subscribe to BTCUSDT and ETHUSDT
{
"method": "SUBSCRIBE",
"params":
[
"btcusdt@miniTicker",
"ethusdt@miniTicker"
],
"id": 1
}
Finally, the market data websocket url is wss://data-stream.binance.vision
. Now, we are good to go 😎
Trying the websocket API
Most morden web browser support websocket, so we just need to open the developer console to try
const ws = new WebSocket('wss://data-stream.binance.vision/ws');
ws.onmessage = function (e) { console.log(e.data) };
ws.send('{"method":"SUBSCRIBE","params":["btcusdt@miniTicker"],"id":0}');
we should see log messages like below
{"e":"24hrMiniTicker","E":1686600526157,"s":"BTCUSDT","c":"25813.21000000","o":"26116.47000000","h":"26206.88000000","l":"25602.11000000","v":"32722.94617000","q":"846855564.49409930"}
...
{"e":"24hrMiniTicker","E":1686600527217,"s":"BTCUSDT","c":"25813.20000000","o":"26114.91000000","h":"26206.88000000","l":"25602.11000000","v":"32711.86119000","q":"846566058.39423260"}
WIP
https://codesandbox.io/s/binance-websocket-l2dglq?file=/src/ContextProvider.tsx
Top comments (1)
use
``` to bring your code to life