0

I want to connect to the GDAX websocket api with an in browser application built with react and webpack. I cannot use the offiicial gdax-node or gdax-toolkit api's because they are not compatible with webpack. I decided to try connecting to the websocket myself using socket.io, but the code below never establishes a connection. In the code below my "subscribing" log message after connect never appears. How do I get this code to connect or at least show an error message?

const io = require('socket.io-client');

var subscribe = {
  "type": "subscribe",
  "channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}]
};

function subscribeToTimer(cb) {
  console.log('Opening socket');
  var socket = io.connect('wss://ws-feed.gdax.com');

  socket.on('connection', function(socket) {
    console.log('Subscribing');

    socket.on('disconnect', function(socket) {
      console.log('Clinet disconnected.');
    });    
  });

  //socket.on('message', timestamp => cb(null, timestamp));
  socket.on('message', data => { console.log(data); });
  socket.on('error', data => { console.log(data); });
}
export { subscribeToTimer };
  • How are you calling `subscribeToTimer`? With your current code example, we won't know how this piece of code is invoked. – Mario Tacke Feb 16 '18 at 22:59
  • Just something like this. When I run the code I can see that the function is being involked because I see the "Opening socket" message, but not the "Subscribing" or "Client disconnected" messages. subscribeToTimer((err: Error, input: TradeMessage) => this.addRow(input)); – SpeculatorSeth Feb 16 '18 at 23:54

2 Answers2

0

Socket.io is not the appropriate library to use for this. I switched it to using global's websocket and it works fine.

function subscribeToTimer(cb) {
  console.log('Opening socket');
  const socket = new WebSocket('wss://ws-feed.gdax.com');

  socket.addEventListener('message', function(event) {
    console.log('new message', event.data);
  });

  socket.addEventListener('open', function(event) {
    console.log('Subscribing');


    var subscribe = '{"type": "subscribe", "channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}]}';
    socket.send(subscribe);

    socket.addEventListener('close', function(event) {
      console.log('Client disconnected.');
    });    
  });

  //socket.addEventListener('message', timestamp => cb(null, timestamp));
}
0

Since gdax only exposed the wss url to public and socket.io does not support wss or ws connection, we have to find work around. Here global.websocket is enough to make connection in the browser. Or you could also check out this library. It simply wraps the ws package and when you build by webpack for browser usage, it will replace the main by browser.js.

xwa130
  • 579
  • 4
  • 6