How to obtain text message alerts for a cryptocurrency's price changes using Python

Hi all, in this post, you will learn how to get a text message alert every time your favorite crypto has a price change by creating a surprisingly very easy Python script.
⚒️ Tools you will need:
- Python
- A Twilio account (to get a number to send a text message from)
- An AWS ec2-instance (or some other cloud machine)
🤔 The problem
My latest obsession is Coreto, a relatively new cryptocurrency that aims to disrupt the market by being the “Facebook” of the crypto world. The problem is that being a new coin, it is still not available in centralized exchange platforms like Coinbase or Binance, and most decentralized exchange platforms, like Uniswap, don’t offer limit orders.
By not being able to buy and sell orders at predetermined prices you could potentially lose a lot of money for failing to complete a buy order at the dip or a sell order at the pump. With the Python script that you’ll be able to create after reading this post, you’ll get your own custom price changes alerts in the form of text messages, even while sleeping.
🐍 Let’s code!
Step 1: Scrape Coreto’s price from Coin Market Cap
For this, we will use Beautiful Soup, a Python library for pulling data out of webpages.
import bs4 as bslink = "https://coinmarketcap.com/currencies/coreto/"request = urllib.request.Request(link) webpage = urllib.request.urlopen(request)
source = webpage.read()
webpage.close() soup = bs.BeautifulSoup(source, 'html.parser')Once we have the whole web page in the soup variable, we need to find the price.
price = soup.find(class_="price").textKeep in mind that if you’re planning on scraping the price frequently, you should and a random pause to avoid being detected as a bot and getting your IP address blacklisted from Coin Market Cap.
Step 2: Save results in a table
There are two ways to approach the problem at hand. One, we could send text alerts every time the crypto coin reaches a predetermined value, or two, we could send a text message every time the crypto coin drops/goes up a certain value. In this post we will do the later, but feel free to do the former if it makes more sense to you and your strategy.
For this, we will need to save the history of the last sent text message in a table.
import pandas as pd
from datetime import datetimecurrent_time = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
df = pd.DataFrame([(current_time, price)],
columns = ["time", "price"])
df.to_csv("coreto_price_history.csv", index=False)You should read this table every time you scrape the price, and update only if the price difference between the current price and the last price in the table is greater than the threshold. If so, we may continue to the next step of our script.
Step 3: Send a text message using Twilio
Once we have our price change information
price_difference = price - df.price.values[-1]
abs_price_difference = abs(price_difference)
sgn = "🔺" if price_difference <0 else "🔻"We create a flag variable to avoid using Twilio’s API unless we actually want to text an update, in order to avoid incurring charges.
# Excecute code if difference is higher than USD$0.001
flag = round(diff,3)>=0.001Go to your Twilio console, and obtain yourACCOUNT SIDand AUTH TOKEN. Then get a Twilio phone number that is capable of sending text messages. Twilio offers $15 dollars of trial money, however, if you’re on a trial account, you will be able to send text messages only to verified numbers on Twilio (which should be enough if you’re sending the price alert only to yourself).
account_sid = "XXXXXXXXXXXXXXXX"
auth_token = "XXXXXXXXXXXXXXXXX"
twilio_phone = "+1........"
target_number = "+1......." # Phone number that receives the alertsNow, we authenticate and send the text message
client = Client(account_sid, auth_token)def send_msg(text, number, sender):
message = client.messages.create(body=text,
from_=sender,
to=number)msg = f"Coreto's price is {price}. Scraped @ {current_time}"send_msg(msg, target_number, twilio_phone)Et voilà!
Well… not really. We are done with the script but now we want to run it even if our computer is off while we are sleeping.
☁️ A code that runs 24/7
You can schedule your script to run as often as you want with a cronjob, however, I recommend doing this in a cloud machine, so your computer doesn’t have to be on and connected to the internet all the time. I used the smallest (a.k.a cheapest) AWS ec2-instance I could find since our code is pretty simple.
To add a cronjob on an ec2 instance, simply type crontab -e. Then you will be in a vi environment. The commands you will need to accomplish your mission are i to insert your cronjob and then hit the esc key, followed by :wq and enter to save changes.
My cronjob looks like this:
*/2 * * * * python coreto.py >> log.txtThe stars mean the script will run every two minutes and I decided to save any log output generated into log.txt.
✨ That is it! Have fun buying Coreto or your favorite crypto! 🤑🌈
Full code is available on my GitHub.
Follow me on Twitter or Instagram or YouTube :)
If you liked this article, send me some Coreto 😜
