Skip to content

Instantly share code, notes, and snippets.

@mariowhowrites
Created February 27, 2018 20:37
Show Gist options
  • Save mariowhowrites/74fe62d4af04d42534891f47501a8227 to your computer and use it in GitHub Desktop.
Save mariowhowrites/74fe62d4af04d42534891f47501a8227 to your computer and use it in GitHub Desktop.

Building a Crypto Price Bot with Telegram and Laravel: Part 1

Wherein I describe my approach and defend the creation of yet another price bot.

Why Does The World Need Another Crypto Bot?

Like many I've talked to in recent months, I wish I had taken Bitcoin seriously when I first encountered it. I distinctly remember the window in 2013 where, after careful research and consideration, I declared Bitcoin "interesting" before doing nothing and forgetting cryptocurrencies for four years. While I suspect, for many Americans at least, memories of the late 2010s will be hued primarily in various shades of tangerine, reluctance to recognize cryptocurrency's staying power will likely register as another common regret.

We see this today in the embrace of FOMO, or fear of missing out, wherein satoshi-laden speculators comb the distant reaches of the Internet in search of cryptographic treasure. Though I might pretend to rationality in my business endeavors, I am today one of FOMO's chief adherents. For proof, I will confess to my status a Crypto Decembrist — one of those wide-eyed (read: foolish) investors who jumped into the blockchain revolution near its December 2017 peak, only to watch my by market forces I hadn't begun to understand.

Yet that hasn't stopped me from researching, sharing, and debating the merits of various cryptocurrencies with my similarly-obsessed friends. Each of us fiercely devoted to our altcoins, none of us willing to concede the vast likelihood of failure, we cheer on our chosen cryptocurrencies not unlike triremes in a digital naumachia, where teamwork is everything and only the strongest blockchains survive.

Yet, for all the thrill of cryptocurrency trading, the actual act of checking prices was, at least for me, both solitary and throughly uninspiring. I'd open CoinMarketCap, lament the sterile Bootstrap styling, then, one-by-one, search the coins I was interested in for any sign of movement. If cryptocurrency trading is a gladiatorial showdown, it lacks a Colosseum where winners can bask in the tears and satoshis of vanquished opponents.

The product of two weekends of code and inspired by the incredible talks at this year's Laracon Online, Artemis is a cryptocurrency bot that represents my attempt to add a fun, social element to the market's unparalleled volatility.

I've fielded a handful of questions about how I built Artemis in the two weeks since it's been live. The truth is that I didn't write a whole lot of custom code to get it done — I've relied on the open-sourced work of much smarter developers than myself to flesh out Artemis's core functionality. Because I believe this process could be easily replicated, I'm dedicating my first Ceiba Web tutorial series to explaining how Artemis is built, how I plan to expand it in the future, and how you can employ the same approach to make your ideas into reality with code.

Designing Artemis — Defining the Scope

Artemis is a cryptocurrency price bot that bundles coins into "coin lists" and tracks their performance against each other in a social setting.

Using the trusty satoshi as its primary denomination, Artemis will let you know how your coins are doing relative to the other coins on the list — ie. those coins your friends (mistakenly, of course) believe will outperform your own.

On a frequent interval, Artemis fetches price information from CryptoCompare on every "active" coin — in other words, every coin added to a coin list by a Telegram user. If it finds a coin's satoshi value has increased by a specific threshold, currently 10%, Artemis sends a "moon alert" to the subscribers of that list, letting them know one of their tracked coins is outperforming Bitcoin.

Additionally, Artemis produces "top 10" rankings on command, showing which coins in a given list have gained or lost the most satoshis over the last 24 hours.

Its primary distinction from other cryptocurrency bots is its social functionality. It is NOT an investment advisor. The market information it fetches from is not exclusive, nor does it determine when to buy or sell a given coin. There are plenty of price bots for those looking to automate their investment decisions — Artemis is not one of them. Primarily, I built Artemis because:

  1. I want to know how the coins I'm interested in are doing without yet another trip to CoinMarketCap.
  2. I want to know what coins my friends are following, so I can ask questions and research coins I haven't previously heard of.
  3. I want to taste sweet victory and dance on the corpses of my enemies.

How I Built A Crypto Price Bot — Project Overview

First off, for those curious, the source code is here. While I plan on dedicating a few posts to covering my development process in more depth, I'll run through a top-level overview now, so that anybody who's considering building something similar has a framework to work with.

My open-source weapon of choice, both for Artemis and in my day job as a freelance web developer, is Laravel. This is partly due to circumstance: as a self-taught programmer who started programming by building custom WordPress sites, Laravel represented a logical next step in my professional growth. Though both WordPress and Laravel are built on the same underlying language — PHP — the ways in which the two applications enable developers to customize and extend their frameworks could not be more different.

As I continue to work more with Laravel, however, I've consistently been amazed at how fluidly it allows me to map my digital ideas into concrete realities. The prototype for Artemis, for example, was completed over the course of two days, and two more days gave it the full functionality it has today. Using the Telegram Bot SDK package, connecting my bot to Telegram and sending Artemis' first message happened within an hour of starting the project.

I'm also using CryptoCompare as my central data source for cryptocurrency markets. In an ideal world, I'd hook Artemis up to each exchange's data API individually — but until then, CryptoCompare offers a robust data API with generous access at the free level.

When planning development projects, I like to think of project objectives in terms of how data should move through the application. What inputs will this program take, and what outputs will it produce in return?

For Artemis, this broke down into these main inputs:

  1. Given a list of coins, the bot should fetch price information from CryptoCompare and create regular price snapshots for each coin.
  2. Given text input from Telegram users:
  3. If the input alters a coin list, make the requested alterations and output confirmation (send "Done!" message to Telegram)
  4. If the input requests information on one or more coins on the list, compile the requested information and return it.

Very quickly, I'll run through how Artemis handles each of these data flows:

Text Input

  1. A user sends a valid command to Artemis through Telegram.

  2. Telegram receives the command and sends the information as a POST request to a webhook set up on Artemis's website.

https://gist.github.com/11aece630dd46bf076087d68abd56b2d

  1. Once Artemis receives the webhook, the Telegram SDK package checks the commands registered in the telegram.php config file to determine how it should handle the user's request. It does this by matching the $name property of the registered command with the name of the command sent by the user. If the user sends a remove command, for example, Artemis will find the command whose $name property is remove.

https://gist.github.com/a6164b4195386c5d9aa030f824a89447

  1. The command checks the input for validity and outputs the requested information to Telegram if everything checks out. All commands eventually end by sending a message through the replyWithMessage function, which is included with the SDK and automatically replies to the proper message thread based on who sent the command.

For example, here's the command that runs when a coin is removed from the list: https://gist.github.com/a98e597ece59e2e233dd5cd26b02432e

Fetching Prices

  1. Every minute, Artemis uses Laravel's schedule functionality to call a FetchPrices command. This ensures that prices are updated frequently, and that the update schedule can be changed easily if need be.

https://gist.github.com/ebf03d80d4783f1b1043ed0caa18249e

  1. Within the FetchPrices command, the handle() command is responsible for fetching prices. It takes every coin in the database and fetches prices from CryptoCompare to make a price snapshot of each one.

https://gist.github.com/eb19dc19a2cb0479d1a69d9e71539183

  1. At this point, the application has everything it needs to respond to a user's request. However, it also needs to check each PriceSnapshot to see whether moon alerts should be sent out.

To accomplish this, I'm taking advantage of Laravel's event system to trigger an action each time a PriceSnapshot is created. In my EventServiceProvider, Artemis triggers the CheckForMooning action whenever a PriceSnapshot is saved:

https://gist.github.com/87c0bf9175c81cc668f1d30ec6f09d87

  1. The CheckForMooning event is very simple — if the PriceSnapshot qualifies the Coin as "mooning", an alert is sent out to the relevant parties.

https://gist.github.com/5269065daa669b4c88a9324026d9dbf7

Conclusion: Next Steps, Next Tutorials

Artemis is far from finished. In fact, it can hardly be called alpha right now, as it's only current capable of maintaining one list — the list I've built with my friends.

However, when time permits, my goal is to abstract the concept of coin lists, coin list subscribers, and chatrooms, so that anybody can use Artemis to make their own coin list for their own chatrooms.

Additionally, I've got plans to add a "fantasy crypto" setting to Artemis. At the beginning of each week, Artemis will ask each coin list subscriber which coin they believe will perform best over the week. At week's end, Artemis will declare a victor and post a happy GIF to celebrate your (hopeful) success.

Of course, I'm open to suggestions as well — both in what I should add to Artemis and what I should write about in these tutorials. Just leave a comment or tweet me @CeibaWeb with your suggestions.

That's it for now! May the mooning be ever in your favor!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment