avatarViviana Márquez

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3091

Abstract

2: Save results in a table</h2><p id="098e">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.</p><p id="6c24">For this, we will need to save the history of the last sent text message in a table.</p><div id="73d0"><pre><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd <span class="hljs-title">from</span> datetime <span class="hljs-keyword">import</span> datetime</pre></div><div id="b34d"><pre>current_time = datetime.now().strftime(<span class="hljs-string">"%m/%d/%Y, %H:%M:%S"</span>) df = pd.DataFrame([(current_time, price)], columns = [<span class="hljs-string">"time"</span>, <span class="hljs-string">"price"</span>]) df.to_csv(<span class="hljs-string">"coreto_price_history.csv"</span>, <span class="hljs-keyword">index</span>=False)</pre></div><p id="5719">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.</p><h2 id="3e83">Step 3: Send a text message using Twilio</h2><p id="3361">Once we have our price change information</p><div id="c557"><pre><span class="hljs-attr">price_difference</span> = price - df.price.values[-<span class="hljs-number">1</span>] <span class="hljs-attr">abs_price_difference</span> = abs(price_difference) <span class="hljs-attr">sgn</span> = <span class="hljs-string">"🔺"</span> if price_difference <<span class="hljs-number">0</span> else <span class="hljs-string">"🔻"</span></pre></div><p id="3bad">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.</p><div id="7445"><pre><span class="hljs-comment"># Excecute code if difference is higher than USD0.001</span> <span class="hljs-attribute">flag</span> = round(diff,<span class="hljs-number">3</span>)&gt;=<span class="hljs-number">0</span>.<span class="hljs-number">001</span></pre></div><p id="8022">Go to your <a href="https://www.twilio.com/console">Twilio console</a>, and obtain your<code>ACCOUNT SID</code>and <code>AUTH TOKEN</code>. Then get a <a href="https://www.twilio.com/console/phone-numbers/search">Twilio phone number</a> 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).</p><div id="9757"><pre><span class="hljs-attr">account_sid</span> = <span class="hljs-string">"XXXXXXXXXXXXXXXX"</span> <span class="hljs-attr">auth_token</span> = <span class="hljs-string">"XXXXXXXXXXXXXXXXX"</span> <span class="hljs-attr">twi

Options

lio_phone</span> = <span class="hljs-string">"+1........"</span> <span class="hljs-attr">target_number</span> = <span class="hljs-string">"+1......."</span> <span class="hljs-comment"># Phone number that receives the alerts</span></pre></div><p id="d196">Now, we authenticate and send the text message</p><div id="a7cb"><pre><span class="hljs-attr">client</span> = Client(account_sid, auth_token)</pre></div><div id="2234"><pre>def send_msg(<span class="hljs-keyword">text</span>, <span class="hljs-built_in">number</span>, sender):
message = client.messages.<span class="hljs-built_in">create</span>(body=<span class="hljs-keyword">text</span>, from_=sender, <span class="hljs-built_in">to</span>=<span class="hljs-built_in">number</span>)</pre></div><div id="e882"><pre><span class="hljs-attribute">msg</span> <span class="hljs-operator">=</span> f<span class="hljs-string">"Coreto's price is {price}. Scraped @ {current_time}"</span></pre></div><div id="a2c1"><pre><span class="hljs-function"><span class="hljs-title">send_msg</span><span class="hljs-params">(msg, target_number, twilio_phone)</span></span></pre></div><p id="25a3">Et voilà!</p><p id="6127">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.</p><h1 id="256c">☁️ A code that runs 24/7</h1><p id="c836">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.</p><p id="2954">To add a cronjob on an ec2 instance, simply type <code>crontab -e</code>. Then you will be in a <a href="https://www.tutorialspoint.com/unix/unix-vi-editor.htm">vi environment</a>. The commands you will need to accomplish your mission are <code>i</code> to insert your cronjob and then hit the <code>esc</code> key, followed by <code>:wq</code> and enter to save changes.</p><p id="af92">My cronjob looks like this:</p><div id="8680"><pre>*/<span class="hljs-number">2</span> * * * * <span class="hljs-keyword">python</span> coreto.<span class="hljs-keyword">py</span> >> <span class="hljs-built_in">log</span>.txt</pre></div><p id="0a70">The <a href="https://crontab.guru/every-2-minutes">stars</a> mean the script will run every two minutes and I decided to save any log output generated into <code>log.txt</code>.</p><h1 id="d45d">✨ That is it! Have fun buying Coreto or your favorite crypto! 🤑🌈</h1><p id="f598">Full code is available on my <a href="https://github.com/vivianamarquez/Coreto/blob/main/coreto.py">GitHub</a>.</p><p id="5af0">Follow me on <a href="https://twitter.com/vivmarquez">Twitter</a> or <a href="https://www.instagram.com/vivianamarquez/">Instagram</a> or <a href="https://www.youtube.com/user/vivmarquez">YouTube</a> :)</p><p id="a5e5">If you liked this article, send me some Coreto 😜</p></article></body>

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 bs
link = "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").text

Keep 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 datetime
current_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.001

Go 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 alerts

Now, 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.txt

The 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 😜

Coreto
Cryptocurrency
Python
Scraping
Twilio
Recommended from ReadMedium