Search code examples
websocketnodestradier

Tradier API websockets stream node.js example is not receiving any events


I have the following nodejs code per this and this:

const WebSocket = require('ws');
const ws = new WebSocket('wss://ws.tradier.com/v1/markets/events');

request({
  method: 'post',
  url: 'https://api.tradier.com/v1/markets/events/session',
  form: {
    
  },
  headers: {
    'Authorization': 'Bearer MY_API_KEY_NOT_SHOWN',
    'Accept': 'application/json'
  }
}, (error, response, body) => {
    console.log(response.statusCode);
    console.log(body);
    let data = JSON.parse(body)
    let sessionId = data.stream.sessionid
    streamPrice(sessionId)
});

function streamPrice(sessionId){
  console.log(sessionId)
  ws.on('open', function open() {
    console.log('Connected, sending subscription commands...');
    ws.send(`{"symbols": ["TSLA"], "sessionid": "${sessionId}", "linebreak": true}`);
  });
  ws.on('message', function incoming(data) {
    console.log(data);
  });
  ws.on('error', function error(data) {
    console.log(data);
  });
}

I get a 200 OK back from the API request to create the web sockets session, and I have a valid session ID:

200
{"stream":{"url":"https:\/\/stream.tradier.com\/v1\/markets\/events","sessionid":"6ba4158d-8ff8-46c3-b005-***********"}}
6ba4158d-8ff8-46c3-b005-*********** 

However, the ws.on() events never fire. I am not getting any errors. The session does close after a period of time, presumably due to inactivity. But it's not inactivity on my code's part...

Is there something wrong in my code / something I'm missing to make this work?


Solution

  • I was able to identify the issue myself. The problem is I was opening the websocket too early.

    I moved the following line inside of streamingPrice scope instead of the global scope to resolve.

    const ws = new WebSocket('wss://ws.tradier.com/v1/markets/events');