Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stream trades from Binance web socket API in Node.js?

I am trying to use the Binance API to get the latest trades on a crypto-currency pair. Here is the endpoint to the API, say for BTC/USDT: wss://stream.binance.com:9443/ws/btcusdt@trade

I tested this API on https://www.websocket.org/echo.html, and was successful in getting a continuous stream of new trades.

How do I use this API in Node.js to continuously output the trades on the console? Is there any specific library or package you recommend?

like image 748
Uzair Avatar asked Jun 11 '18 08:06

Uzair


Video Answer


1 Answers

I feel kind of stupid for not finding this package earlier. I used ws to accomplish the task. Below are the lines of code I typed:

const WebSocket = require('ws');

const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');

ws.on('message', function incoming(data) {
    console.log(data);
});
like image 169
Uzair Avatar answered Sep 22 '22 07:09

Uzair