May 21, 2024 at 13:26
Linux Mint has a taskbar applet that keeps track of crypto investments, allowing me to keep track of the price of Doge from the corner of my eye. This is fine for what it is, but it’s clearly not informative enough. So I wrote a bot that pings my crypto portfolio into a Slack channel every morning. It goes a little something like this:
crypto_bot.py
import requests
import json
from urllib import request, parse
from slack_lib.py import send_message_to_slack
def get_crypto_data(cryptos):
#limited to 30 calls/min, 10k/mo.
url = "https://api.coingecko.com/api/v3/simple/price"
params = {
"ids": ",".join(cryptos),
"vs_currencies": "usd",
"include_24hr_change": "true"
}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
return None
def format_price(crypto, price):
if crypto in ["bitcoin", "ethereum"]:
return f"${price:,.2f}"
elif crypto == "dogecoin":
return f"${price:.3f}"
elif crypto == "shiba-inu":
return f"${price:.6f}"
# These are hardcoded values, but could easily pull from an external source if necessary
def main():
cryptos = ["bitcoin", "ethereum", "dogecoin", "shiba-inu"]
quantities = {
"bitcoin": 5.6789,
"ethereum": 1.2345,
"dogecoin": 34567,
"shiba-inu": 123456789
}
crypto_data = get_crypto_data(cryptos)
if crypto_data:
total_current_value = 0
total_initial_value = 0
total_percent_change = 0
total_value_change = 0
output = ""
for crypto in cryptos:
price = crypto_data[crypto]['usd']
percent_change = crypto_data[crypto]['usd_24h_change']
current_value = price * quantities[crypto]
initial_value = current_value / (1 + percent_change / 100)
value_change = current_value - initial_value
total_current_value += current_value
total_initial_value += initial_value
total_percent_change += percent_change
total_value_change += value_change
formatted_price = format_price(crypto, price)
#change the formatting however you see fit
output += f"> *{crypto.capitalize()}:* {percent_change:.2f}% {formatted_price} | T: ${current_value:,.2f} C: ${value_change:,.2f}\n"
overall_percent_change = ((total_current_value - total_initial_value) / total_initial_value) * 100
output += f"> *Total: {overall_percent_change:.2f}% T: ${total_current_value:,.2f} C: ${total_value_change:,.2f}*"
send_message_to_slack("🪙 *Crypto Bot* 💱\n" + output)
else:
print("Failed to retrieve data.")
if __name__ == "__main__":
main()