Search code examples
javascriptcoinbase-api

Get % gain/ loss of BTC in the last 24 hour period - Coinbase


I am looking to get the % change of the cryptocurrency Bitcoin vs USD.

Something similar to the way Coinbase works it out on their website (the red -10% for example): btc price vs usd

I attempted to find this via the Coinbase API but wasn't able to.

Closest I got was this public endpoint: https://api.coinbase.com/v2/prices/BTC-USD/spot

But the response looks like this:

{
    "data": {
        "base": "BTC",
        "currency": "USD",
        "amount": "31208.85"
    }
}

Does not have any metrics for the last 24 hours.

Perhaps I am looking in the wrong section but is this possible? Or do I have to calculate this % myself?


Solution

  • Instead look to the Coinbase Pro API, specifically 24 hour stats.

    GET https://api.pro.coinbase.com/products/BTC-USD/stats
    

    Which gives you:

    { 
      "open":"34977.48",
      "high":"35679.45",
      "low":"30150",
      "volume":"45646.70203384",
      "last":"30373.21",
      "volume_30day":"1027072.33957844"
    }
    

    From this you can calculate the percentage change, assuming the above is data:

    > (data.last - data.open)/data.open*100
    > -13.163526932186093