Do you manually track crypto currencies values?
Do you want to be notified by email when your crypto currency value goes up or down by specific value?
Do want to stop going to crypto exchange websites just to see value of the coin?
If you answered with 'Yes', then, you are in the right place.
Whether you're a seasoned trader or a crypto enthusiast, staying updated with the latest prices is crucial. Thankfully, Python can help automate this process, saving you time and effort.
In this post, I’ll walk you through a simple Python script that tracks the value of any cryptocurrency on a specific exchange in real-time.
Cryptocurrency markets operate 24/7, and prices can change in seconds. By automating the tracking process, you can:
To follow along, ensure you have the following:
There are three files:
Whole code can be found in this GitHub gist.
Note: The code could be refactored for improved readability and efficiency, but the primary focus here is on functionality.
Note: In this example I used "Kraken" as crypto exchange where I follow prices.
When the value of the (for example) Polkadot coin increases by 1 EUR, you receive an email notification like this:
Import necessary libraries.
load_dotenv()
Loads variables like email credentials (PASSWORD) from a .env file for secure handling.
load_dotenv()
Purpose: Sends an HTML-formatted email notification when price thresholds are met.
Loads the email template from an external file (email_template.html).
def send_email(subject, price, currency_name, image_url, price_change): sender_email = "your_email@gmail.com" receiver_email = "your_email@gmail.com" password = os.getenv("PASSWORD") -> here you need to type your generated google account app password msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = receiver_email msg['Subject'] = subject if price_change > 0: change_emoji = "?" elif price_change < 0: change_emoji = "?" else: change_emoji = "⚖️" with open('email_template.html', 'r', encoding='utf-8') as f: html_template = f.read() html_content = html_template.format( currency_name=currency_name, price=price, image_url=image_url, change_emoji=change_emoji ) msg.attach(MIMEText(html, 'html')) try: server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(sender_email, password) server.sendmail(sender_email, receiver_email, msg.as_string()) print("E-mail sent!") except Exception as e: print(f"Error occured: {e}") finally: server.quit()
Purpose: Adds a delay to prevent excessive requests to the target website, avoiding detection as a bot.
def delay(): time.sleep(2)
Purpose: Loads cryptocurrency details (e.g., name, url, imagesrc) from a JSON file.
def load_cryptocurrencies(): with open('cryptocurrencies.json', 'r') as f: return json.load(f)
Purpose: Sets up a headless Chrome browser for scraping cryptocurrency prices.
headless: Runs Chrome without a GUI.
Custom User-Agent: Mimics real browser usage for better bot detection evasion.
chrome_options = Options() header = Headers(browser="chrome", os="win", headers=False) customUserAgent = header.generate()['User-Agent'] chrome_options.add_argument(f"user-agent={customUserAgent}") chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
cryptocurrencies = load_cryptocurrencies() for currency in cryptocurrencies: try: url = f"https://www.kraken.com/prices/{currency['url']}" driver.get(url) delay() price_element = driver.find_element(By.CLASS_NAME, "asset-price.black-color")
Parses the price text and converts it into a float for comparison and calculation
price = price_element.text.strip().replace('€', '').replace(',', '.') try: price = float(price) except ValueError: print(f"Error while conversion price for {currency['name']}: {price}") continue
Retrieves the last saved price from a text file. If it doesn’t exist, assumes no previous data.
Calculates the price change (price_change).
previous_price_file = f"previous_price_{currency['url']}.txt" try: with open(previous_price_file, 'r') as file: previous_price = float(file.read().strip()) except FileNotFoundError: previous_price = None price_change = price - previous_price
Sets thresholds for price change notifications:
Note: If you want to track coins with more digits you need to adapt it here.
if previous_price is not None: if price < 100: if abs(price - previous_price) >= 1: subject = f"New price {currency['name']}: {price}" send_email(subject, price, currency['name'], currency['imagesrc'], price_change) else: if abs(price - previous_price) >= 5: subject = f"New price {currency['name']}: {price}" send_email(subject, price, currency['name'], currency['imagesrc'], price_change)
Saves the current price to the text file for future comparisons.
with open(previous_price_file, 'w') as file: file.write(str(price))
except Exception as e: print(f"Error occured for {currency['name']}: {e}")
Closes the browser instance after all tasks are complete.
To make this in action once per hour add this:
driver.quit()
crontab -e
By following this guide, you can track cryptocurrency prices and receive real-time email notifications while you sleep!
If you found this post helpful or have ideas to improve the script, feel free to leave a comment below ?
Happy coding and successful trading!
The above is the detailed content of Automated crypto price tracking using GMAIL and Python. For more information, please follow other related articles on the PHP Chinese website!