Abdullah Ch
Abdullah Ch

Reputation: 2181

Initate Socket connection with Twelvedata server in node js


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

//setting up env
dotenv.config()


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

ws.on('subscribe', (stream) => {
  console.log('stream ==>', stream);
})

I cannot emit subscribe event given by the twelvedata API. Also, I don't know how to pass the parameters as suggested by the twelvedata's documentation in node js.

For Example:-



{ "action": "subscribe", 
  "params": {
    "symbols": [{
        "symbol": "AAPL",
        "exchange": "NASDAQ"
      }, {
        "symbol": "RY", 
        "mic_code": "XNYS"
      }, {
        "symbol": "DJI",
        "type": "Index"
      }
  ]
 }
}


This object is used as a parameter to emit event to the twelvedata server and the server then responds with the data stream.

How can I emit the subscribe event through web-sockets as stated by the below screenshot (this is an example from the twelvedata website) enter image description here Socket Connection

How can I pass the information regarding the subscribe event and the parameters to the web socket as shown in the screenshots

Upvotes: 1

Views: 142

Answers (1)

Stephen Ecker
Stephen Ecker

Reputation: 86

The websocket subscribe event is performed via the send function, rather than as an on listener.

this.ws.send(JSON.stringify(subObject));

And when the server sends you information, you would listen to it via message

        this.ws.on('message', async (msg) =>{
        let buffToJson = JSON.parse(msg.toString('utf8'))
        
        if(buffToJson.event === 'price'){

Upvotes: 1

Related Questions