WebSocket is not open: readyState 0 (CONNECTING)

1.1k Views Asked by At

I am trying to get real time data from the Alpaca API. At first, I can connect to the API and it streams the data. But after some time it gets me an error.

Here is my code:

const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);

const Alpaca = require('@alpacahq/alpaca-trade-api');
const alpaca = new Alpaca({
  keyId: process.env.ALPACA_API_KEY_ID,
  secretKey: process.env.ALPACA_API_SECRET_KEY,
  paper: true, 
});

io.on('connection', (socket) => {
  console.log(`Client connected with ID: ${socket.id}`);
  let stream = null;

  socket.on('subscribe', (ticker) => {

    console.log(`Subscribing to data for ${ticker}`);

    const stream = alpaca.data_stream_v2;
    stream.onConnect(function () {
        console.log("Connected");
        stream.subscribeForQuotes([(ticker)]);
      });
  
      stream.onStockQuote((quote) => {
        console.log(quote);
        socket.emit('stockData', quote);
      });

      stream.connect();

  });

  socket.on('disconnect', () => {
    console.log(`Client disconnected with ID: ${socket.id}`);
    if (stream) {
      console.log(`Unsubscribing from data for ${stream.ticker}`);
      stream.disconnect();
    }
  });
});

and this is the error I get:

/Users/vivien/Documents/tradingapp/node_modules/ws/lib/websocket.js:394
      throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
      ^

Error: WebSocket is not open: readyState 0 (CONNECTING)
    at WebSocket.send (/Users/vivien/Documents/tradingapp/node_modules/ws/lib/websocket.js:394:13)
    at AlpacaStocksClient.authenticate (/Users/vivien/Documents/tradingapp/node_modules/@alpacahq/alpaca-trade-api/dist/resources/datav2/websocket.js:171:19)
    at WebSocket.<anonymous> (/Users/vivien/Documents/tradingapp/node_modules/@alpacahq/alpaca-trade-api/dist/resources/datav2/websocket.js:108:43)
    at Object.onceWrapper (node:events:509:28)
    at WebSocket.emit (node:events:390:28)
    at WebSocket.setSocket (/Users/vivien/Documents/tradingapp/node_modules/ws/lib/websocket.js:225:10)
    at ClientRequest.<anonymous> (/Users/vivien/Documents/tradingapp/node_modules/ws/lib/websocket.js:882:15)
    at ClientRequest.emit (node:events:390:28)
    at TLSSocket.socketOnData (node:_http_client:527:11)
    at TLSSocket.emit (node:events:390:28)

Do you know why I get this error and what I can do to make it work?

1

There are 1 best solutions below

0
7436284734 On

I am trying to get real time data from the Alpaca API. At first, I can connect to the API and it streams the data. But after some time it gets me an error.

The most possible cause it's because your websocket got disconnected and trying reconnect while you are sending a message. The best you can do is research why it disconnects.