-1

I am trying to get the price only of bitcoin from Binance for each second and store the result in an array. I have the following code, I have to refresh the page everytime I want the last price. I am also not sure how to input that in an array.

     var burl ='https://api.binance.com';

var query ='/api/v3/ticker/price';

query += '?symbol=BTCUSDT'; //&interval=15m&limit=2';

var url = burl + query;

var ourRequest = new XMLHttpRequest();

ourRequest.open('GET',url,true);
ourRequest.onload = function(){

  // Will convert the string to something Javascript can understand
  var result = JSON.parse(ourRequest.responseText); 

  // You can now use it as an array
  console.log(result);
}
ourRequest.send();

I also find a fetch method, I am not sure how to adapt this code to help me solve this issue.

componentDidMount() {
    fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
        .then(response => {
            return response.json();
        })
        .then(data => {
            // Here you need to use an temporary array to store NeededInfo only 
            let tmpArray = []
            for (var i = 0; i < data.results.length; i++) {
                tmpArray.push(data.[i])
            }

            this.setState({
                other: tmpArray
            })
        });
} 

Thank you so much!!

M.J.
  • 15
  • 4
  • Why do you need to put it into your array? Do you need to put new price into array each 3 seconds and to console.log this array? – Alexey Nazarov Sep 23 '20 at 20:00
  • It works great. I really appreciate it. :) :) – M.J. Sep 23 '20 at 20:37
  • I postef this question and no body comment on the problem. Could you please have a look on it. I really appreciate it: https://stackoverflow.com/questions/64074329/login-to-signed-binanceus-api – M.J. Sep 26 '20 at 14:56

1 Answers1

0

To give a request every 3 seconds you need to use setInterval
To push response price to array you need to use array.push(price)

let array = [];
let eachEverySeconds = 3;

function fetchCoinPrice(params) {
  fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
    .then(response => {
        return response.json();
    })
    .then(data => {
        array.push(data.price)
        console.log("tmpArray", array);
    }); 
}

fetchCoinPrice();
setInterval(fetchCoinPrice, eachEverySeconds * 1000);
Alexey Nazarov
  • 2,289
  • 2
  • 12
  • 13