node.jsexpresswebsocketwstwelvedata

Connect to a third party server (twelvedata) from my own express server through web socket connection string


I want to connect to the twelevedata server through its provided socket connection to receive information.


import * as dotenv from 'dotenv' 
import WebSocket from 'ws';
import express from 'express'

const app = express();

//setting up env
dotenv.config()

// setting up the websocket
const ws = new WebSocket(`wss://ws.twelvedata.com/v1/quotes/price?apikey=${process.env.API_KEY_TWELVEDATA}`);


const payload = {
  "action": "subscribe",
  "params": {
  "symbols": "AAPL,INFY,TRP,QQQ,IXIC,EUR/USD,USD/JPY,BTC/USD,ETH/BTC"
  },
}




ws.on('connection',function (steam) {

  ws.on('open', (data) => {
    console.log("data ==>",data);
    ws.emit('subscribe',payload)
  })
    
  ws.on('subscribe', (data) => {
    console.log("data ==>",data);
  })
})

const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`I am listening at ${port}`);
});

I created a websocket with my websocket connection on an express application but I am unable to receive any information from the twelvedata server regarding the subscribe event that I have emitted !

This is how the websocket should work as shown by the twelvedata website (look into the screen shots)

enter image description here enter image description here

I am unable to connect and emit the subscribe event given by the twelvedata's documentation


Solution

  • 
    // sending the parameters
     ws.on('open', function open() {
        ws.send(JSON.stringify(payload));
      });
      
      ws.on('message', function message(data) {
        // receiving data
        console.log('data ===>: ', JSON.parse(data));
      });
    

    ws.send did the charm for me