Building A Bitcoin Price Watcher With Alerts In Java

You will be automatically alerted of Bitcoin price changes.

Sylvain Saurel
Dec 6, 2019 · 9 min read

As a developer, you probably have an interest in everything related to technology. So, you must have already heard of Bitcoin. Better yet, I imagine you’ve already taken an interest in how it works and more specifically in Blockchain technology. If you have ever been interested in Bitcoin, you may have noticed that its price tended to be very volatile.

The volatility of Bitcoin is largely related to the youth of its market. If you decided to buy Bitcoins, you probably spent some time watching its price on exchanges platforms. This can quickly become extremely time-consuming.

Instead of wasting your time watching the price of Bitcoin for many hours, I will teach you how to build a Java program to watch the price of Bitcoin and receive alerts directly on your desktop when the price reaches levels you have defined.


Specifications Of The Bitcoin Price Watcher

The Bitcoin Price Watcher program that we will develop during this article will have the following features:

  • Getting Bitcoin price using the Bitcoin Price Index from the CoinDesk site.
  • Watching of the price of Bitcoin every minute.
  • Definition of Bitcoin prices to watch in an interactive way.
  • Listing of all watched prices.
  • Displaying notifications directly on the user’s desktop.

By reading these features, you have understood that our program will be launched on the end user’s computer. It will be launched on the command line in a terminal by the user who will be able to add new prices to watch by entering a command like that:

WATCH;7450

Here, the user requests to be alerted when the Bitcoin reaches the price of $7,450.


Creating The Java Project

The first step will be to create a Java project that will use Maven as a dependency manager. Since we will have to call the CoinDesk Web Service, we will add the OkHttp code library as a dependency to our project.

OkHttp is a very efficient HTTP client that will be perfect for our project.

As the CoinDesk Bitcoin Price Index Web Service returns its data in JSON format, we will have to add in dependence a code library to parse the data thus obtained.

For this, I will use the org.json code library which is very lightweight and easy to use. All this gives us the following POM file for our project:


Getting Bitcoin Price

Once the project is created and the dependencies added, we will move on to get the Bitcoin price. The CoinDesk Bitcoin Price Index Web Service is available at the following address:

https://api.coindesk.com/v1/bpi/currentprice.json

A first call to this API in a Web browser allows us to see the look of its rendering:

JSON returned by the BPI Web Service

At the level of the main class of our program, we create a client property of type OkHttpClient. This object is the entry point of the OkHttp API and will then allow us to launch our request to the Web Service.

The request is represented by a Request object to which we enter the endpoint of the CoinDesk Bitcoin Price Index. The latter is stored in a static variable BITCOIN_PRICE_ENDPOINT.

To execute this request with the previously created OkHttpClient instance, we use its newCall method to which we pass the Request object we just built as an input. It then remains to call the enqueue method which takes as input an object of type Callback. The use of this interface allows us to decouple the processing of the result of the request from the actual call.

All this gives the following code within a loadBitcoinPrice method:

private void loadBitcoinPrice(Callback callback) {
Request request = new Request.Builder().url(BITCOIN_PRICE_ENDPOINT).build();
client.newCall(request).enqueue(callback);
}

As our program must continuously watch the price of Bitcoin, it is necessary that this call to the Bitcoin Price Index Web Service be made at regular intervals.

To implement this operation, Java offers the Timer API. I will therefore define a TimerTask object within which I will make the call to the loadBitcoinPrice method. The execution of this TimerTask is scheduled every minute following the call to the schedule method of the Timer instantiated for the occasion.

So we have the following code:


Parsing Of The JSON Data Obtained

In the previous code, you must have noticed the presence of a parseBitcoinPrice method taking as input the result of the call to the Bitcoin Price Index Web Service. This method will be in charge of parsing the JSON data obtained following the call to the Web Service in order to get the current price of the Bitcoin.

Within this method, I start by creating a JSONObject instance from the content passed as input. I will then make two calls chained to the getJSONObject method with respectively in parameter “bpi” then “USD”, before finally calling the getFloat method with in input “rate_float”.

This gives me the current price of Bitcoin in USD.

I display in the console the date and time as well as the price of the Bitcoin that has just been obtained. The last known price of Bitcoin is also stored in the currentPrice property of our main class.

At this point, the parseBitcoinPrice method looks like this:

private void parseBitcoinPrice(String str) {
JSONObject jsonObject = new JSONObject(str);
currentPrice = jsonObject.getJSONObject("bpi").getJSONObject("USD").getFloat("rate_float");
System.out.println(LocalDateTime.now() + " | Current price = " + currentPrice + "\n");

// ...
}

I specify well at this point because once this price has been got, it will be necessary to compare this price with the watched prices defined by the user.


Modeling A Price To Watch

Before I can compare the current price of Bitcoin obtained with the watched prices defined by the user, I will have to model a price to watch.

A price to watch is modeled within a Price class and has the following two properties:

  • A target property of float type representing the price to watch.
  • A type property which is a Type enum representing the watching type performed.

Indeed, when a user asks to watch for a given price, we will define if this watching should be made up or down in order to make the alert message more relevant later on.

The Type enum that is created from this requirement has two values: UP and DOWN. In addition, we define two abstract methods:

  • An reached method taking as input the current price of Bitcoin and the price to watch and returning true if this price is reached.
  • An msg method taking as input the current price of Bitcoin and the price to watch and returning the message to display to the user.

The implementation of these methods is then carried out in a specific way on the two values of the Type enum. Finally, the type definition of a price to watch is done at the creation of a Price object by comparing the current value of Bitcoin with the price to watch defined by the user.

This gives the following code for the Price class:


Alerting User On Prices to Watch

Earlier, I told you that the parseBitcoinPrice method was not complete. Indeed, for the moment, it only displays the price of Bitcoin obtained from the Bitcoin Price Index Web Service.

For work of that method to be complete, it must be able to iterate on the prices watched by the user and for each of the prices reached, send a system alert message to the user. This will allow him to be alerted directly when a price he wishes to watch is reached.

In addition, once a watched price is reached, it should not be forgotten to remove it from the list of prices to watch.

To do this, I create a pricesToWatch property within the main class of my program. This property will store a list of Price objects. In order to iterate on this list and be able to delete items if necessary, I will use an Iterator object.

Then, for each price I will get its type property on which I would call the reached method by passing as input the current price of Bitcoin as well as the watched price contained within the current Price object.

If the reached method returns true, then the price watched by the user is reached.

We must then retrieve the message to display to the user by calling the msg method of the type property associated with the current Price object. Then define a displayNotification method that will be in charge of launching the system notification on the user’s host machine.

The Java Virtual Machine offers the SystemTray API for this. This supports the proper display of system notifications regardless of the operating system on which the program will run.

Finally, it remains to remove the price to be watched by calling the iterator’s remove method. This gives us the following code:


Interaction With The User

As it stands, our Bitcoin Price Watcher program allows us to get the price of Bitcoin at regular intervals and then compare it to a list of prices to watch. If prices to be watched are reached, then a system notification is displayed to the user.

The interaction with the user is still missing in order to allow him to enter the prices of the Bitcoin he wants to watch.

The user interaction part is implemented within a scanConsole method.

Our application will support the following three commands:

  • QUIT to exit the program.
  • LIST to list the prices watched by the program.
  • WATCH followed by a semicolon and a price to add a new price to watch.

We will then use the JDK Scanner class to get the commands entered by the user. If the QUIT command is entered, the program is left, taking care to close the connection to the Scanner and to cancel the execution of the Timer. Otherwise, we continue to wait for the user’s commands.

When the LIST command is entered, the listPricesToWatch method is called, which displays all the watched prices in the console, specifying each time whether it is up or down.

Finally, for the WATCH command, we will retrieve the price entered. After verifying that this price was a valid floating value, a new instance of the Price object will be created and added to the list of prices to watch.

All this gives us the following code:


Assembling The Different Parts

All we have to do now is to assemble the different parts of our Bitcoin Price Watcher program into the main method of the App class.

In concrete terms, this consists in instantiating an App object, then getting the Bitcoin price at regular intervals by calling the launchTimer method, then calling the scanConsole method in order to remain waiting for the user’s entries in the console.

We therefore have the following complete code for the App class :


Bitcoin Price Watcher In Action

Before starting our Bitcoin Price Watcher program, I took care to generate a JAR archive allowing a user to use it directly from a terminal.

The first step consists in launching the program with the following command:

java -jar BitcoinPriceWatcher.jar

Following the launch of the program, the price of Bitcoin is obtained for the first time. I add several prices to watch and then I enter the LIST command to check that the prices have been taken into account by the Bitcoin Price Watcher:

The program continues to get the Bitcoin price at regular intervals:

I can then leave the program running and resume normal activity. Indeed, the Bitcoin Price Watcher will alert me when the prices I want to watch have been reached.

After a while, I receive a system notification while I’m reading an article about cryptocurrencies on Medium :

Closer up, the system notification looks like this:

A quick glance at the terminal launched in the background shows that the program continued to run well and to watch the Bitcoin price:

The Bitcoin Price Watcher we have just developed is therefore perfectly functional.


To Go Further

This Bitcoin Price Watcher can be improved by adding the sending of emails to a given address when the price reaches the prices that the user wants to watch.

In addition, you can extend this program to other cryptocurrencies. To do this, you will need to use an API that offers the price of other cryptocurrencies in order to watch the evolution of their prices. Then, it will be necessary to take into account the code of a cryptocurrency in addition to the price to watch.

It is now up to you to code to make this more complete program if you need it.

The Startup

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

Sylvain Saurel

Written by

Entrepreneur / Developer / Blogger / Author. In Bitcoin We Trust: https://www.inbitcoinwetrust.net

The Startup

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade