import requests
import pandas as pd
import streamlit as st
from decouple import config
from apscheduler.schedulers.background import BackgroundScheduler
# Bitquery API key
bitquery_api_key = config("BITQUERY_API_KEY", default="API_KEY")
# Ethereum address you want to query
ethereum_address = "0xc99B3eF8eFD7eE8AC2F67b12862f9704dbD230FA"
# Wrapped Ether (WETH) contract address on Ethereum Mainnet
weth_contract_address = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
# Construct the API URL for Bitquery
api_url = 'https://graphql.bitquery.io/'
# GraphQL query to fetch token balances
query = f"""
{{
ethereum(network: ethereum) {{
address(address: {{is: "{ethereum_address}"}}) {{
balances {{
currency {{
address
symbol
tokenType
name
}}
value
}}
}}
}}
}}
"""
# Set headers with the Bitquery API key
headers = {'X-API-KEY': bitquery_api_key}
# Function to fetch data
def fetch_data():
try:
# Send the GraphQL query
response = requests.post(api_url, json={'query': query}, headers=headers)
response.raise_for_status() # Raises a HTTPError if the response status is 4xx, 5xx
except requests.exceptions.RequestException as e:
print(f"Error: Cannot fetch data from Bitquery API. {str(e)}")
return
data = response.json()
ethereum_data = data.get('data', {}).get('ethereum', {})
ethwalletbalance = pd.DataFrame() # Define the DataFrame outside the if-block
if ethereum_data:
addresses_data = ethereum_data.get('address', [])[0]['balances']
for address_data in addresses_data:
balances = address_data.get('balances', [])
for balance in balances:
value = balance.get('value', 0)
token_address = balance['currency'].get('address', '')
token_price_usd = 0 # Initialize token price
if token_address == weth_contract_address:
# Use 1 ETH as the price for WETH
token_price_usd = 1.0
# Fetch token price in USD from CoinGecko using the token's contract address
coingecko_api_url = "https://api.coingecko.com/api/v3/simple/token_price/ethereum"
coingecko_params = {
'contract_addresses': token_address,
'vs_currencies': 'usd'
}
try:
coingecko_response = requests.get(coingecko_api_url, params=coingecko_params)
coingecko_response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error: Cannot fetch data from CoinGecko API. {str(e)}")
return
if coingecko_response.status_code == 429: # Rate limit error
print("Error: CoinGecko rate limit exceeded. Please try again later.")
return
coingecko_data = coingecko_response.json()
token_price_usd = coingecko_data.get(token_address.lower(), {}).get('usd', 0)
# Calculate token balance in USD
token_balance_usd = value * token_price_usd
# Create a data row for the DataFrame
data_row = {
'ETH_Balance': token_balance_usd
}
ethwalletbalance = ethwalletbalance.append(data_row, ignore_index=True)
# Display the dataframe in Streamlit
st.dataframe(ethwalletbalance.style.highlight_max(axis=0))
# Schedule the task to run daily at 2 PM Brazil time
scheduler = BackgroundScheduler()
scheduler.add_job(fetch_data, 'cron', day_of_week='mon-sun', hour=6, minute=36, second=0, timezone='America/Sao_Paulo')
scheduler.start()
# This is the Streamlit part of your code
st.title("Ethereum Wallet Balance")
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.