0

I am trying to do maths on a number within a JSON object (the price of a stock ticker).

I want it to be a variable called 'btcusd_price', that I can then use to do arithmetic with.

How do I get a variable i can work with?

https://tonicdev.com/npm/bitfinex

var Bitfinex = require('bitfinex');

var bitfinex = new Bitfinex('your_key', 'your_secret');

var btcusd_price;

btcusd_price = bitfinex.ticker("btcusd", function(err, data) {
  if(err) {
    console.log('Error');
    return;
  }
  console.log(data.last_price);
  return data.last_price;
});

typeof btcusd_price;
console.log(btcusd_price); //i'm trying to work with the price, but it seems to be 'undefined'?

1 Answers1

0

You have to set the values when they are available, the code is async and you were using the value before it is applied to btcusd_price. Note that the proper way to use the variable is when the callback executes its code.

Please, see the working code below:

Bitfinex = require('bitfinex');

var bitfinex = new Bitfinex('your_key', 'your_secret');

var btcusd_price;

bitfinex.ticker("btcusd", function(err, data) {
  if(err) {
    console.log('Error');
    return;
  }

  btcusd_price = data.last_price;
  console.log(typeof btcusd_price);
  console.log(btcusd_price);
});
bpinhosilva
  • 692
  • 1
  • 5
  • 15