Home » Bitcoin convertor using python and a free api

Bitcoin convertor using python and a free api

by pqzrmred71

To convert Bitcoin (BTC) to USD, EUR, and GBP using a free API, you can use the requests library in Python to access live exchange rates from an API such as the Coindesk API.

This API provides real-time Bitcoin price data, including rates in multiple currencies.

Here’s the Python code to do this along with an explanation:

Code

import requests

def get_bitcoin_rates():
    url = "https://api.coindesk.com/v1/bpi/currentprice.json"
    
    try:
        # Send a GET request to the Coindesk API
        response = requests.get(url)
        response.raise_for_status()  # Raise an error for bad responses
        
        # Parse the JSON response
        data = response.json()
        
        # Extract rates for USD, EUR, and GBP
        usd_rate = data['bpi']['USD']['rate_float']
        eur_rate = data['bpi']['EUR']['rate_float']
        gbp_rate = data['bpi']['GBP']['rate_float']
        
        return usd_rate, eur_rate, gbp_rate

    except requests.RequestException as e:
        print(f"Error fetching data: {e}")
        return None

def convert_bitcoin(amount_btc):
    rates = get_bitcoin_rates()
    
    if rates:
        usd_rate, eur_rate, gbp_rate = rates
        
        # Convert the Bitcoin amount to each currency
        usd_value = amount_btc * usd_rate
        eur_value = amount_btc * eur_rate
        gbp_value = amount_btc * gbp_rate
        
        print(f"{amount_btc} BTC is equivalent to:")
        print(f"${usd_value:.2f} USD")
        print(f"€{eur_value:.2f} EUR")
        print(f"£{gbp_value:.2f} GBP")
    else:
        print("Failed to retrieve exchange rates.")

# Example: Convert 1 Bitcoin
amount_btc = float(input("Enter the amount in BTC: "))
convert_bitcoin(amount_btc)

Explanation

  1. Import Required Library:
    • requests: This library allows us to make HTTP requests to retrieve data from the Coindesk API.
  2. get_bitcoin_rates Function:
    • This function fetches the latest Bitcoin rates in USD, EUR, and GBP.
    • Set the URL:
      • url = “https://api.coindesk.com/v1/bpi/currentprice.json”: Coindesk API endpoint that provides the current Bitcoin price index (BPI) in multiple currencies.
    • Send GET Request:
      • response = requests.get(url): Sends a GET request to the API endpoint.
      • response.raise_for_status(): Checks for HTTP errors and raises an exception if the request was unsuccessful.
    • Parse the JSON Response:
      • data = response.json(): Parses the JSON data returned by the API.
    • Extract Rates:
      • usd_rate, eur_rate, and gbp_rate: Access the exchange rates for USD, EUR, and GBP in rate_float format from the JSON data.
      • These values are returned as a tuple (usd_rate, eur_rate, gbp_rate).
    • Error Handling:
      • The try-except block handles potential network or data parsing errors and prints an error message if something goes wrong.
  3. convert_bitcoin Function:
    • This function takes the amount of Bitcoin (amount_btc) to be converted into USD, EUR, and GBP.
    • Fetch Rates:
      • rates = get_bitcoin_rates(): Calls get_bitcoin_rates() to get the latest exchange rates. If the API request fails, rates will be None.
    • Calculate Conversion Values:
      • If rates are available, the code extracts usd_rate, eur_rate, and gbp_rate.
      • Multiplies amount_btc by each rate to calculate the equivalent amount in each currency:
        • usd_value = amount_btc * usd_rate
        • eur_value = amount_btc * eur_rate
        • gbp_value = amount_btc * gbp_rate
    • Display Results:
      • Prints the equivalent value in USD, EUR, and GBP with two decimal places.
    • Error Handling:
      • If rates are unavailable (None), an error message is printed.
  4. Run the Program:
    • The user is prompted to enter an amount in BTC.
    • convert_bitcoin(amount_btc) is called to display the conversions.

Sample Output

>>> %Run get_bitcoin_rates.py
Enter the amount in BTC: 1
1.0 BTC is equivalent to:
$69622.78 USD
€64023.92 EUR
£53854.26 GBP

Notes

  • API Rate Limits: The Coindesk API is free but may have rate limits. Avoid making too many requests in a short period.
  • Error Handling: The code includes error handling for network issues and invalid API responses.
  • Currency Symbols: $, €, and £ symbols are used for USD, EUR, and GBP respectively.
  • Exchange Rates: Rates fluctuate frequently, so this program gives the current rate at the time of the request.

Summary

This program uses the Coindesk API to fetch real-time Bitcoin exchange rates in USD, EUR, and GBP. It converts a specified amount of Bitcoin into these currencies and displays the results.

The program handles errors gracefully, making it reliable for quick currency conversions.

You may also like