C#

A C Sharp Bitcoin Price Converter with code explanation

Below is a C# Bitcoin Price Converter program. This program fetches the current price of Bitcoin using a public API and allows the user to convert a given amount of Bitcoin to USD or vice versa. The program uses HttpClient to interact with the API.

Full Code

using System;
using System.Net.Http;
using System.Threading.Tasks;

class BitcoinPriceConverter
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Welcome to the Bitcoin Price Converter!");

        while (true)
        {
            Console.WriteLine("\nChoose an option:");
            Console.WriteLine("1. Convert Bitcoin to USD");
            Console.WriteLine("2. Convert USD to Bitcoin");
            Console.WriteLine("3. Exit");
            Console.Write("Enter your choice: ");

            string choice = Console.ReadLine();

            switch (choice)
            {
                case "1":
                    await ConvertBitcoinToUSD();
                    break;
                case "2":
                    await ConvertUSDToBitcoin();
                    break;
                case "3":
                    Console.WriteLine("Goodbye!");
                    return;
                default:
                    Console.WriteLine("Invalid choice. Please try again.");
                    break;
            }
        }
    }

    static async Task<double> GetBitcoinPriceInUSD()
    {
        try
        {
            using HttpClient client = new HttpClient();
            string apiUrl = "https://api.coindesk.com/v1/bpi/currentprice/USD.json";
            HttpResponseMessage response = await client.GetAsync(apiUrl);

            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine("Failed to fetch the Bitcoin price. Please try again later.");
                return 0;
            }

            string json = await response.Content.ReadAsStringAsync();
            dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
            return (double)data.bpi.USD.rate_float;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while fetching the Bitcoin price: {ex.Message}");
            return 0;
        }
    }

    static async Task ConvertBitcoinToUSD()
    {
        Console.Write("Enter the amount of Bitcoin: ");
        if (!double.TryParse(Console.ReadLine(), out double bitcoinAmount) || bitcoinAmount <= 0)
        {
            Console.WriteLine("Invalid input. Please enter a positive numeric value.");
            return;
        }

        double price = await GetBitcoinPriceInUSD();
        if (price > 0)
        {
            double usdAmount = bitcoinAmount * price;
            Console.WriteLine($"{bitcoinAmount} BTC = {usdAmount:F2} USD (Current BTC Price: {price:F2} USD)");
        }
    }

    static async Task ConvertUSDToBitcoin()
    {
        Console.Write("Enter the amount of USD: ");
        if (!double.TryParse(Console.ReadLine(), out double usdAmount) || usdAmount <= 0)
        {
            Console.WriteLine("Invalid input. Please enter a positive numeric value.");
            return;
        }

        double price = await GetBitcoinPriceInUSD();
        if (price > 0)
        {
            double bitcoinAmount = usdAmount / price;
            Console.WriteLine($"{usdAmount:F2} USD = {bitcoinAmount:F8} BTC (Current BTC Price: {price:F2} USD)");
        }
    }
}

Explanation

  1. Fetching Bitcoin Price:
    • The method GetBitcoinPriceInUSD fetches the current price of Bitcoin in USD from the CoinDesk API:
      • API URL: https://api.coindesk.com/v1/bpi/currentprice/USD.json
    • The method uses HttpClient to send an HTTP GET request to the API and parse the JSON response.
    • The price is extracted using the Newtonsoft.Json library, which deserializes the JSON data.
    string apiUrl = "https://api.coindesk.com/v1/bpi/currentprice/USD.json";
    HttpResponseMessage response = await client.GetAsync(apiUrl);
    string json = await response.Content.ReadAsStringAsync();
    dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
    return (double)data.bpi.USD.rate_float;
    
  2. Converting Bitcoin to USD:
    • The method ConvertBitcoinToUSD takes the user’s input (amount of Bitcoin), validates it, and multiplies it by the current price of Bitcoin (fetched using GetBitcoinPriceInUSD).
    double usdAmount = bitcoinAmount * price;
    Console.WriteLine($"{bitcoinAmount} BTC = {usdAmount:F2} USD");
    

    Example:

    • Input: 0.05 BTC
    • Price: 40000 USD
    • Output: 0.05 BTC = 2000 USD
  3. Converting USD to Bitcoin:
    • The method ConvertUSDToBitcoin takes the user’s input (amount in USD), validates it, and divides it by the current price of Bitcoin to calculate the equivalent Bitcoin value.
    double bitcoinAmount = usdAmount / price;
    Console.WriteLine($"{usdAmount} USD = {bitcoinAmount:F8} BTC");
    

    Example:

    • Input: 2000 USD
    • Price: 40000 USD
    • Output: 2000 USD = 0.05000000 BTC
  4. Input Validation:
    • Both ConvertBitcoinToUSD and ConvertUSDToBitcoin validate user inputs to ensure they are positive numeric values using double.TryParse.
    if (!double.TryParse(Console.ReadLine(), out double bitcoinAmount) || bitcoinAmount <= 0)
    {
        Console.WriteLine("Invalid input. Please enter a positive numeric value.");
        return;
    }
    
  5. Error Handling:
    • The program handles potential errors (e.g., API failure or invalid responses) gracefully, displaying a meaningful message to the user.
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred while fetching the Bitcoin price: {ex.Message}");
    }
    
  6. JSON Parsing:
    • The program uses the Newtonsoft.Json library to parse the API response. Ensure you install the Newtonsoft.Json NuGet package for this to work:
      dotnet add package Newtonsoft.Json
      

Sample Run

Run the program:

Welcome to the Bitcoin Price Converter!

Choose an option:

  1. Convert Bitcoin to USD
  2. Convert USD to Bitcoin
  3. Exit Enter your choice: 1 Enter the amount of Bitcoin: 0.05 0.05 BTC = 2000.00 USD (Current BTC Price: 40000.00 USD)

Another run:

Choose an option: 2. Convert USD to Bitcoin Enter the amount of USD: 15000 15000.00 USD = 0.37500000 BTC (Current BTC Price: 40000.00 USD)

Invalid Input Example:

Enter your choice: 1
Enter the amount of Bitcoin: -0.5
Invalid input.
Please enter a positive numeric value.

Features

1. Live Bitcoin Price:
– Fetches the current Bitcoin price in real-time using the CoinDesk API.

2. Two-Way Conversion:
– Converts Bitcoin to USD and vice versa.

3. Error Handling:
– Handles API errors and invalid user inputs gracefully.

4. Dynamic JSON Parsing:
– Uses the Newtonsoft.Json library to parse JSON responses dynamically.

Ideas for Enhancement

1. **Add Support for Other Currencies**:
– Allow users to choose currencies like EUR, GBP, etc.
– Update the API URL to fetch rates for other currencies.

Example:
string apiUrl = "https://api.coindesk.com/v1/bpi/currentprice/EUR.json";
  1. Historical Prices:
    • Fetch historical Bitcoin prices using the CoinDesk historical API.
  2. Custom Formatting:
    • Display the prices in localized formats for different currencies.
  3. Graphical Interface:
    • Use Windows Forms or WPF to create a GUI version of the converter.
  4. Advanced Options:
    • Allow users to calculate profit/loss based on their Bitcoin holdings and purchase prices.

This C# Bitcoin Price Converter demonstrates how to interact with an external API, validate user input, and perform calculations in real-time.

Related posts

A C Sharp BMI and BMR Calculator program with code explanation

a C Sharp Rock, Paper, Scissors game with code explanation

A C Sharp Hi-Lo Guessing Game