简体   繁体   English

在 node.js 发起与 Twelvedata 服务器的 Socket 连接

[英]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 .我无法发出十二数据 API给出的订阅事件。 Also, I don't know how to pass the parameters as suggested by the twelvedata's documentation in node.js.另外,我不知道如何按照 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.这个 object 用作向十二数据服务器发出事件的参数,然后服务器用数据 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)如何通过网络套接字发出订阅事件,如下面的屏幕截图所示(这是来自 twelvedata 网站的示例) 在此处输入图像描述 套接字连接

How can I pass the information regarding the subscribe event and the parameters to the web socket as shown in the screenshots如何将有关订阅事件的信息和参数传递给 web 套接字,如屏幕截图所示

The websocket subscribe event is performed via the send function, rather than as an on listener. websocket 订阅事件是通过发送 function 执行的,而不是作为监听器。

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'){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM