import streamlit as st import requests import time # Function to get the list of available cryptocurrencies @st.cache_data def get_available_cryptos(): url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd" try: response = requests.get(url) response.raise_for_status() data = response.json() # Create a dictionary to map lowercase IDs to their uppercase symbols cryptos = {coin["id"]: coin["symbol"].upper() for coin in data} return cryptos except requests.exceptions.RequestException as e: st.error(f"Error fetching cryptocurrency list: {e}") return {} # Function to get the current price of the selected cryptocurrency in USD def get_crypto_price(crypto_id): url = f"https://api.coingecko.com/api/v3/simple/price?ids={crypto_id}&vs_currencies=usd" try: response = requests.get(url) response.raise_for_status() price_data = response.json() if crypto_id in price_data: return price_data[crypto_id]['usd'] else: st.error(f"Invalid cryptocurrency ID: {crypto_id}") return None except requests.exceptions.RequestException as e: st.error(f"Error fetching data: {e}") return None # Streamlit app layout st.title("Crypto to USD Converter") st.write("Get the current price of cryptocurrencies in USD.") # Fetch the list of available cryptocurrencies available_cryptos = get_available_cryptos() if available_cryptos: selected_crypto = st.selectbox("Select Cryptocurrency:", list(available_cryptos.values())) # Get the crypto ID based on the selected symbol crypto_id = [key for key, value in available_cryptos.items() if value == selected_crypto][0] amount = st.number_input(f"Enter amount of {selected_crypto}:", min_value=0.0, step=0.01) if st.button("Convert to USD"): with st.spinner("Fetching price..."): # Add a delay to avoid hitting the rate limit time.sleep(2) crypto_price = get_crypto_price(crypto_id) if crypto_price is not None: total_usd = crypto_price * amount st.success(f"1 {selected_crypto} = {crypto_price:.2f} USD") st.success(f"{amount} {selected_crypto} = {total_usd:.2f} USD") else: st.warning("Could not fetch the price. Try again later.") else: st.warning("No cryptocurrencies available for conversion at this time.") # Footer information st.markdown("### Note:") st.markdown("Prices are fetched in real-time API. Thank-you, regards Rahul Juneja.")