How to get Bitcoin prices from the web in Python

1 min

One way to get Bitcoin prices from the web in Python is to use the requests library to make a request to a cryptocurrency price API, such as Coinmarketcap. Then use the json() method to parse the API response which will be in json format.

Here's an example of how to get the current Bitcoin price in USD on coinmarketcap:

import requests

url = ''
headers = {'X-CMC_PRO_API_KEY': 'YOUR_API_KEY'}
response = requests.get(url, headers=headers)
data = response.json()
btc_price = data['data']['BTC']['quote']['USD']['price']
print(f'Bitcoin price: ${btc_price:.2f}')

You will need to sign up for an API key to use this service.

Another way is using libraries such as ccxt that has built in support for multiple crypto currency exchanges and provides a unified way to access the data.

It's important to keep in mind that the method you choose to get Bitcoin prices from the web will depend on the specific requirements of your project, such as the format of the data and the amount of data you need to handle.

Here is how to to it with ccxt:

import ccxt

exchange = ccxt.binance({
    'rateLimit': 2000,
    'enableRateLimit': True,

symbol = 'BTC/USDT'

orderbook = exchange.fetch_order_book(symbol)
bid = orderbook['bids'][0][0] if len (orderbook['bids']) > 0 else None
ask = orderbook['asks'][0][0] if len (orderbook['asks']) > 0 else None

print(f'Bid: {bid}, Ask: {ask}')