Retrieve and Send Live Bitcoin Rates Every Day Using CEX.io, Twilio SMS, and PHP

October 15, 2020
Written by
Precious Opusunju
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by
Paul Kamp
Twilion

Retrieve and Send Live Bitcoin Rates Every Day Using CEX.io, Twilio SMS, and PHP.png

 

Ever wondered how platforms like Binance set price watchlists for different Bitcoin price alerts? If so, imagine getting a daily SMS alert whenever the price of Bitcoin changes.

This tutorial will teach you how to use Twilio Programmable SMS to send out live Bitcoin rates every day using your Laravel app. After we’re finished, you will be able to automatically send an SMS containing the conversion rate of Bitcoin to USD to your phone number, daily.

Installation Requirements

We will begin with a new Laravel project. Additionally, the following modules are required for proper functionality. These modules are:

Having installed Laravel on your machine, proceed to create a new project using the Laravel CLI:

$ laravel new bitcoin_watcher

Or using the Composer create-project command:

$ composer create-project --prefer-dist laravel/laravel bitcoin_watcher

Next, install Twilio’s PHP SDK to interact with Twilio’s APIs as needed. To make this happen, use Composer to install the dependency with the following commands:

$ cd bitcoin_watcher
$ composer require Twilio/sdk

After the installation is done, add your Twilio API credentials in the .env file, as that will be used to authenticate the API requests.

TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXX
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_FROM=13365555555

Once the configuration above is completed, create a controller which will contain the functions to retrieve the current price of bitcoin and send them at different intervals.

$ php artisan make:controller BitcoinPriceController

Next, import Guzzle and the Twilio PHP SDK into the controller (found in ./app/Http/Controllers) by declaring the namespace at the top of the controller file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Exception;
use Twilio\Rest\Client;
use GuzzleHttp\Client as GuzzleClient;

class BitcoinPriceController extends Controller
{
  //
}

Initialize the Constructor

Next, create a constructor to initialize the Twilio client, so that the appropriate APIs can be used. This is done to avoid repeating a block of code across all controller methods following the KISS principle.

The code for the constructor is as follows:

public $twilio;
protected $sid;
public $token;
     
public function __construct() {
    // Your Account SID and Auth Token from twilio.com/console
    $this->sid = env('TWILIO_ACCOUNT_SID');
    $this->token = env('TWILIO_AUTH_TOKEN');
    /** Initialize the Twilio client */
    $this->twilio = new Client($this->sid, $this->token);
}

Call the CEX.io API

Next, create a function that calls the CEX.io API using Guzzle.

protected function bitcoinRate() {

    $headers = array('Accept' => 'application/json');

    $client = new GuzzleClient([
       'headers' => $headers,
    ]); //GuzzleHttp\Client

    $result = $client->post('https://cex.io/api/last_price/BTC/USD', []);
    $response = json_decode($result->getBody()->getContents(), true);
    $responseCode = $result->getStatusCode();

    return "$".number_format($response['lprice']);
}

Next, create a function that sends out the current rate when needed.

public function sendRate() {
    $to = ''; // Phone Number To Send Rates To
    $bitcoinRate = $this->bitcoinRate();
    $message = "Bitcoin Rate For Today: $bitcoinRate";

    $this->twilio->messages->create($to,
        ['from' => env( 'TWILIO_FROM' ), 'body' => $message]
    );

    return true;
}

NOTE: Don’t forget to add your phone number in the $to variable.

Create the Command

Next, we create a command that will eventually run every 24 hours. The following command will generate a file within the app/Console/Commands folder.

$ php artisan make:command BitcoinPriceWatcher

Next, we call the BitcoinPriceController in the command’s __construct() and initialize it.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\BitcoinPriceController;

Next, overwrite the commands signature and description.

 

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'bitcoin:watch';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Listen for the latest price of Bitcoin every day';

Next, we initialize the BitcoinPriceController in the command’s construct:

/**
 * Create a new command instance.
 *
 * @return void
 */
protected $bitcoinPriceController;

public function __construct()
{
  parent::__construct();
  $this->bitcoinPriceController = new BitcoinPriceController();
}

Now we can call the sendRate() function in the controller.

/**
 * Execute the console command.
 *
 * @return string
 */
public function handle()
   {
       $executeSendRate = $this->bitcoinPriceController->sendRate();

       if($executeSendRate === true) {
           $this->info('Bitcoin Price For Today Sent!');
       } else {
           $this->error('An error occurred, check the log!');
       }  
   }

Now we are done with the commands. Next we’ll work on scheduling the function.

Schedule the BitcoinPriceWatcher Command

Finally, let’s set up the scheduler in the Kernel.php file inside the App/Console folder.

First step, add the newly created command to the list of commands.

/**
 * The Artisan commands provided by your application.
 *
 * @var array
 */
protected $commands = [
   BitcoinPriceWatcher::class
];

Second step, define the schedule for our command.

/**
 * Define the application's command schedule.
 *
 * @param \Illuminate\Console\Scheduling\Schedule $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
      $schedule->command('bitcoin:watch')->daily(); // also can do: dailyAt('12:00');
}

Test the Bitcoin Price Watcher

At this point, you have all of the code you need to get daily price alerts for Bitcoin’s market rate. All that’s left is to test your code. Run the command by calling:

$ php artisan bitcoin:watch 

Then an SMS will be sent out with the current rate of Bitcoin.

Example SMS message

Set up a cron job

Now, you should create a cron job to run the command automatically, every 24 hours. You can use the crontab command below to set this up.

To edit or create your crontab file, type the following command at the UNIX / Linux shell prompt:

crontab -e

For the cron job to run at 3 am every day, add the following line:

0 3 * * * php /path/to/bitcoin_watcher artisan schedule:run

Checking Bitcoin’s Daily Price with a Bitcoin API and Twilio

Now that you have set up a Bitcoin Rate monitoring app you can see how straightforward it was to automate this process. Using CEX.io and Twilio’s Programmable Messaging, you’ll always know the price of Bitcoin, whether you have internet access or not!

If you would like to extend this tutorial, you should check out CEX.io's API for more tools and API endpoints to personalize your Bitcoin SMS delivery.

You can find the code repository for this tutorial here.

 

Precious Opusunju is a backend software engineer and technical content creator. He can be reached via:

Email: masterpreshy1@gmail.com
Github: https://github.com/Preshy