DEV Community

Cover image for REAL-TIME bitcoin price in javascript
Christian Seki
Christian Seki

Posted on • Updated on

REAL-TIME bitcoin price in javascript

Bitcoin is a decentralized digital currency and it's currently trading above $41000 (at the time I write this article).Due to it's volatility it would be quite a boring task to keep an eye on it's price. Lucky us, as we're all programmers so let's automate this!😎

What are we going to code ?

dev-to-websocket

The bridge to cryptocurrencies pricing

There's a lot of exchange in the market but I choose to use Binance to tracking bitcoin price for some reasons:

  1. They expose a websocket server, so we can track cryptocurrencies price real time like.
  2. All we need is to connect to wss://stream.binance.com:9443 WITHOUT AN API KEY !

btw, you can sign up to Binance and start trading anytime.


Initializing the project

If you don't have nodejs installed follow the official website instructions.

Let's start the project and install two tiny dependencies:

npm init -y
npm i ws prompts
Enter fullscreen mode Exit fullscreen mode
  • ws it's a client/server websocket implementation, will be used as a client to connect to binance's websocket server.
  • prompts it's a cli tool, will be used to brings flexibility to our code allowing the user to choose what cryptocurrency to keep it's price tracked.

Coding

const prompts = require('prompts');
const WebSocket = require('ws');

const run = async () => {
  const { symbol } = await prompts({
    type: 'text',
    name: 'symbol',
    message: 'What symbol do you wanna track ?'
  });

  const ws = new WebSocket(`wss://stream.binance.com:9443/ws/${symbol.toLowerCase()}@kline_1m`);

  ws.on('message', async (data) => {
    const incomingData = JSON.parse(data.toString());
    if (incomingData.k) {
      const isClosed = incomingData.k.x;
      const symbolPrice = Number(incomingData.k.c);
      console.log(`${symbol.toUpperCase()} : ${symbolPrice} -- closed = ${isClosed}`);
    }
  });
}

run();
Enter fullscreen mode Exit fullscreen mode

That's it ! Isn't simple? I know that it's a lot of things going on under the hood but let's ignoring for now.

The JSON payload received from the socket it's described in binance websocket official documentation.

Conclusion

From that piece of code you can build an even more elegant bot, maybe do some action when getting the cryptocurrency price, triggering your cellphone to waking you up to buy some cryptocurrency, the sky is the limit!
To be honest I've never make money with that but I just wanted to show you guys an interesting and simple real time application.

Discussion (0)