itriad
itriad

Reputation: 41

Read JSON array from websocket data feed in node.js

I am a beginner in javascript and coding in general. what i'm trying to do is to get the bid price (array) from this websocket data feed but i'm struggling,in my code i try to print(console.log) only the "bidPrice"and not everything else like "asksize","bidsize" etc etc when i run my code i get only undefined and not the "bidPrice", what is missing here? thank you for any help

here the result (cmd) when i run the code not good!!!!

C:\Users\Desktop\codesource>node wss.js
Connection opened
undefined
undefined
undefined

here is my code in node.js:

fs = require('fs');
var WebSocket = require('ws');
var ws = new WebSocket('wss://www.bitmex.com/realtime');
ws.on('open', function() {
    console.log('Connection opened');

    //out
    ws.send(JSON.stringify({"op": "subscribe", "args": ["quote:XBTUSD"]}));



});
//in            
ws.on('message',function(message){var response = JSON.parse(message) 

 fs.writeFile('helloworld.txt', JSON.stringify(message));
 fs.writeFile('helloworld.json', JSON.stringify(message));


    var data = message;

    var json = JSON.parse(data);

    console.log(json["bidPrice"]);

});

here is data coming from bitmex websocket

Connection opened
{ info: 'Welcome to the BitMEX Realtime API.',enter code here
  version: '1.2.0',
  timestamp: '2016-12-28T22:27:15.000Z',
  docs: 'https://www.bitmex.com/app/wsAPI',
  heartbeatEnabled: false }
{ success: true,
  subscribe: 'quote:XBTUSD',
  request: { op: 'subscribe', args: [ 'quote:XBTUSD' ] } }
{ table: 'quote',
  keys: [],
  types:
   { timestamp: 'timestamp',
     symbol: 'symbol',
     bidSize: 'long',
     bidPrice: 'float',
     askPrice: 'float',
     askSize: 'long' },
  foreignKeys: { symbol: 'instrument' },
  attributes: { timestamp: 'sorted', symbol: 'grouped' },
  action: 'partial',
  data:
   [ { timestamp: '2016-12-28T22:26:54.645Z',
       symbol: 'XBTUSD',
       bidSize: 12,
       bidPrice: 969.59,
       askPrice: 971.06,
       askSize: 499 } ] }

it seems it doesn't work too

console.log(response.data[0].bidPrice);


Connection opened
C:\Users\jalal\Desktop\codesource\wss.js:24
        console.log(response.data[0].bidPrice);
                                 ^

TypeError: Cannot read property '0' of undefined
    at WebSocket.<anonymous> (C:\Users\jalal\Desktop\codesource\wss.js:24:27)
    at emitTwo (events.js:106:13)
    at WebSocket.emit (events.js:191:7)
    at Receiver.ontext (C:\Users\jalal\Desktop\codesource\node_modules\ws\lib\WebSocket.js:841:10)

Upvotes: 1

Views: 2694

Answers (1)

Matt Altepeter
Matt Altepeter

Reputation: 956

Change

console.log(json["bidPrice"]);

to

console.log(response.data[0].bidPrice);

FYI you do not need the variables data and json

Upvotes: 1

Related Questions