Automated Crypto-Currency Text Alerts with Python and Twilio

Daniel Warren
Feb 22 · 9 min read

Send yourself text alerts so you don’t have to constantly monitor Robinhood.

Part 1: Introduction

I don’t know about y’all, but the volatile price movement of cryptocurrencies has given me a few minor panic attacks over the past few weeks. Whether it be initiated by a tweet from Musk or a Winklevoss twin or something else all together, these digital assets have jumped multiple percentage points over the span of just a few seconds, forcing me to constantly monitor (and at times all together reconsider) my “safe investment against inflation of the USD.”

For hours on end, I’ve found myself unable to peel my eyes away from the $DOGE homescreen on Robinhood in fear of a missed opportunity to cut my losses or maximize my gains. I’ve looked all across the web for an alternative to this manual monitoring/nail biting, but the best solution I could find was the Yahoo Finance app. Unfortunately, the Yahoo Finance app has extremely laggy crypto prices and it requires users to manually input upper/lower limits for push notifications; this “automation” quickly becomes a very manual process, all without the capabilities of monitoring percentage changes.

So the solution I came up with involves sending push notifications to my cell phone anytime my crypto of interest passes a percentage change threshold over a given time interval. Since I’m convinced $DOGE will go to the moon, $DOGE is said crypto of interest (this is not financial advice). When $DOGE jumps by 0.5% over a 15 second period, I get an automated text saying: “DOGE TO THE MOON! Up X%”. And when $DOGE drops by more than 0.5% over a 15 second period, I get an automated text saying: “DOGE AWAY FROM THE MOON! Down X%.”

Image for post
Image for post

Now I can sit through meetings at work without wondering whether or not I’ve lost half of my portfolio, because in the event that I do lose all of my savings in the span of 30 minutes, at least I’ll get a million notifications on my Apple Watch in the meantime as my account value plummets. Alright, let’s jump into the code, shall we?

Part 2: Automated Texts with Twilio

The first thing you’re going to want to do is create a python script that can send an automated text to your personal phone number. I decided to use Twilio because it works seamlessly with python and it allows users to send up to $14.50 worth of credits with a free trial (no credit card info needed!). It’s a little bit confusing how the credits work within Twilio, but I’ve already sent myself well over 100 texts and I’m still sitting at around $14 in remaining credits. Feel free to check out how Twilio credits work on their website.

Twilio provides a concise guide on how to send programmable messages with python. You’ll first need to set up an account on their website, and once completed you’ll be provided with an [account_sid] and an [auth_token] which will be utilized in your python code to hit their API.

Let’s test out whether this whole Twilio automated text thing works before we get too far into this. Below is the code I’ve borrowed from Twilio to hit their API using my [account_sid] and [auth_token]:

Code to test if Twilio automated texting works

Don’t put your [account_sid] and [auth_token] values directly into your python script. Instead, you’ll want to head over to your terminal and set those environment variables manually within the terminal. Your specific values can be found at the following link. That may sound complicated, but in Mac OSX all you have to do enter the following two lines in your terminal:

Image for post
Image for post
Setting environment variables in terminal

In Windows, just use the word ‘set’ instead of ‘export’ and you should be good to go. As far as dependencies are concerned, only ‘os’ and ‘twilio’ should be required for this next step. But now is probably as good of a time as ever to make sure all of the following dependencies are installed for the entirety of this project:

Pip install the following dependencies:

  • twilio (automated texts)
  • robin_stocks (access live crypto prices — requires Robinhood account)
  • math (to round values to 2 sig figs)
  • subprocess (to help with handling exceptions caused by hitting Robinhood API too many times in a certain amount of time)
  • rematch (to help retrieve list of python files within current directory)

Alright alright alright. Now it’s time to test if your code works up until this point. Try executing your code and see if you receive a verification message from Twilio asking you to enter a 6 digit code. If you receive this message, enter that code where it prompts you to do so in your terminal and you should receive your message shortly. If your iPhone vibrates, feel free to head on over to part 3. If you don’t receive that message, I recommend going back to the top of this article and starting from the beginning.

Side note: if you want to have a little bit of fun, you can change the name of the number from which you receive that Twilio text from. I decided to give it the following name:

Image for post
Image for post
Change the name of the Twilio number in your contacts

Part 3: Accessing Robinhood Crypto Data

I’d like to personally thank Joshua Fernandes for creating the robin_stocks python library to connect to and interact with Robinhood programatically. We’ll only be using a little bit of this library’s functionality in this project, but be sure to check out all the other capabilities this library has to offer if you’re interested.

The reason we are using this specific python library is because it allows us to do the following:

  • Log into our own Robinhood portfolio via python
  • Access various crypto currencies of interest
  • Gather live price data including max/min/mark

To make sure that we can log into our own Robinhood accounts and access this information, let’s test out the following python script:

Code to test if Robinhood connection works

If this python script returns the live price of $DOGE, then you are all good to move onto part 5. If not, take a look at pg. 60 in the linked document to learn more about getting crypto information from Robinhood.

Part 5a: Putting It All Together

Now that we have the two main pieces of the puzzle sorted out(automated texting and connecting to Robinhood), we can start putting it all together. My current code that I am running on my computer requires just two python scripts. Bear in mind I am by no means a python wizard, and I am 120% positive there is a more efficient and/or elegant way to write this code. That being said, I’ll start by laying out my entire first script and going over it in detail so you can understand how it works and what was going on inside my head:

Main python script to send texts at various thresholds

The bulk of this first script (which I called takes place within the ‘while’ loop. Since the first line in the ‘while’ loop (n+=0) does not increase the value of ‘n,’ this loop will run forever. But that is intentional — I want this loop to always be running in the background on my computer. However, if you don’t want to run this script for eternity, feel free to increase the value of ’n’ with every pass through the loop.

The first real action this loop sees is when the price_0 variable is assigned to the current value of $DOGE. A 15 second timer then begins, and at the end of the 15 seconds, our second price variable, price_f, is assigned to the current value of $DOGE at that time. With both of those values saved as local variables, the percentage change is then calculated between those two points which takes us to the fun part: the conditionals.

If the percentage change is above 0.5% within those 15 seconds, the first ‘if’ statement returns True, and you will receive a text notifying you that $DOGE is on the way to the moon. If the percentage change is below -0.5% within those 15 seconds, the second ‘if’ statement returns True, and you will receive a text notifying you $DOGE has backtracked away from the moon. If neither of those two criteria are met, you will be passed back to the beginning of the ‘while’ loop where the next local price_0 will be assigned to the then current value of $DOGE and the cycle starts again.

The 0.5%, -0.5%, and 15 values may seem like they were picked arbitrarily, but at least for the case with $DOGE, these values are the result of a lot of trial and error. If your percentage threshold is too low, your iPhone might get mistaken for a Theragun massage device. But if your threshold is too high, you may never receive notifications about travels to/from the moon. For cryptocurrencies that are less volatile than $DOGE, I recommend either decreasing the percentage threshold or increasing the time interval or both.

Part 5b: Bump In The Road

After I finished this first script, I thought I was done. It was working all dandy until all of a sudden my code stopped working and it threw up an error. I honestly cannot remember the exact error it threw up, but after doing extensive research (copy/pasting the error into google and looking through stack overflow), I determined the error was due to hitting the Robinhood API too many times in a short period of time. I tried rerunning the code from the beginning, and voila — the error went away. So this random error that I ran into brings us to my second python script, which I’ll describe in detail:

Python script to run and rerun indefinitely

When saving this python script, you’re going to want to make sure that it is saved in the same directory as since the first ‘for’ loop in this script creates a list of all the python files in the current directory. This is important because you need the exact name and location of the saved as a variable so in the event an error is thrown, we can automatically rerun that script.

My file was the second file in my list of files, so I saved it to the variable ‘filename.’ For your own personal case, your file may be in a different location so please do ensure the variable ‘filename’ is pointing to the first main script you wrote.

At the end of this new python script we get to the real meat and potatoes: the ‘while’ loop that keeps us free of errors and/or exceptions. We first jump into the ‘while’ loop, where our file is initiated and so long as no errors are thrown and no exceptions encountered, we continue running forever. However, in the event an error does occur, we are returned to the beginning of the ‘while’ loop where we attempt to rerun the and hope our error has resolved itself.

And that’s all she wrote: we now have two scripts that will keep us up to date anytime $DOGE or any crypto currency within Robinhood takes a big step towards or away from the moon. Even if you’re not invested in these digital assets, getting texts like the following screenshot are sure to give you a mid-day smile.

Image for post
Image for post
$DOGE updates I’m currently receiving

Part 6: Next Steps

Thanks for taking the time to read my first medium post. I’d love to hear any feedback or comments y’all may have. The github repo can be found at the following link:

As for now, I plan to include the following as time permits.

  • Add functionality for additional crypto currencies
  • Initiate trades in Robinhood account based on price movement criteria
  • Send memes when various percentage thresholds are met
  • Add voice notifications from computer when given threshold is crossed

Daniel Warren

Python hobbyist and stack overflow enthusiast

The Startup

Medium's largest active publication, followed by +771K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store