Gdax web socket API with continuous ticker feed

In this example I will demonstrate how to use the Gdax web socket API to get the data. The data we will be focusing on here today is the ticker data type. This has some information like the current price of the crypto currency we are interested in. In our case we want to know the Lite Coin to USD price for one unit. You can modify the code to put whatever currency you are interested in.

var currencyType = "LTC-USD";

Gdax supports a few different ones, but some other ones are ETH-USD and BTC-USD.

First thing we do is to open a new web socket.

this.websocket = new Gdax.WebsocketClient([currencyType], 'https://ws-feed.gdax.com', null, { heartbeat: true });

Once we have this web socket, we can listen for the open event; then subscribe to the channels.

this.websocket.on('open', s => {
  var subscribeMessage = // JSON formatted message....
  logger("Connected")
  self.websocket.socket.send(JSON.stringify(subscribeMessage));
});

We then listen on the message event from the web socket, and then filter only data types of “ticker”, you can experiment with the code, there are several different types of data types, some other ones are “l2update” which will update the order book, and then you have “done” which will have a reason property, this will let you know if it was filled or what not.

this.websocket.on('message', data => {
  if (data !== null && data.type === 'ticker') {
  logger("Price is " + data.price);
  }
});

That is about it, if you want to take a look at the full source code feel free to grab it here.

Last thing, if we for some reason get disconnected from the feed(which is very likely to occur) we can always listen for the close event, and just call the connect() method again. Like so:

self.websocket.on('close', () => {
  logger("Closed connection!");
  // Attempt to reconnect
  self.connect();
});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.