Hi everyone.

We are starting a new series of guides with awesome ways to use our new API.

The first installment in the series is going to cover building a script for tracking your Bitcoin profits (or losses 😉

We often find ourselves checking the bitcoin price multiple times a day, waiting for the next peak or valley. We all want to make some profit.
Often times this becomes distracting and time consuming, but not anymore.
We will be building a script which automatically checks the price at your favorite exchange and notifies you of the profit you’ve made.

Quick Start Guide/TL;DR:

If you just want to run the script without digging into it you can find the github link at the end with the full code.
So just copy and paste the code into a file and run it via terminal:

$ python bitcoin-profits.py

The script will prompt you to enter some data.

  1. Your exchange – the exchange you want to check at, this is the exchange where you plan to sell the bitcoin eventually, or just your favorite one.
  2. Bitcoin starting price – The price at which you bought your coins.
  3. Bitcoin amount – The amount of bitcoin you bought.
  4. Your currency (default USD) – The fiat currency in which you are buying/selling.
  5. Check every (seconds) – The script performs the calculation in an infinite loop, so this parameter tells it how much to wait between executions.
  6. Choose to be notified when a certain limit is reached 1) Percent limit: 2) Amount limit. Here you specify when you want to be notified of the change in price in Bitcoin.
    If you choose 1 (percent), then you will be asked to enter the amount of percent. Say you enter 10, this means that when the price of Bitcoin changes 10% from your starting price, you will receive a notification.
    The second option allows you to specify the exact amount, here if you enter 10 you will be notified when the Bitcoin price deviates 10 US dollars from the starting price (if you’ve chosen dollars for your currency).

Step 1: Generating the BitcoinAverage API key pair

To be able to generate a key pair you must have an account at BitcoinAverage. Choose one here.
After you create and verify your account you can generate the API key pair at the Api keys page..
Now you need to copy the public key and the secret key into the starting code snippet for our script below.

import hmac
import time
from hashlib import sha256
import subprocess
import requests

secret_key = '<your secret key here>' or input('Enter your secret key: ')
public_key = '<your public key here>' or input('Enter your public key: ')

Step 2: Function for generating the Authentication signature for the Bitcoin Average API.

This function will use your secret and public key to generate a signature that will be sent with each HTTP request that you make later on.

def create_signature():
    ts = str(int(time.time()))
    sig = str(ts + "." + public_key).encode()
    sign = hmac.new(secret_key.encode(), sig, digestmod=sha256).hexdigest()

    signature = "{0}.{1}.{2}".format(ts, public_key, sign)
    return signature

The algorithm for signature creation is very simple. First we concatenate the current timestamp (in UTC) with the public key with a “.” (dot) between them.
Then we encrypt the resulting string with our secret key and the SHA256 algorithm which is already implemented in almost all programming languages.
Finally we get the encrypted value and concatenate it, again with a “.” (dot) to the previous plain string (the one that contained the timestamp and the public key).
For example the final signature would look something like this:

1493816419 .YjBjZDFlNWMxZDk1NDNlZThlYWY5ZDlhODA4MjhlN2Q.92b28898b6081e65b2735de57aae28d23b7332c26cbe5d87ef1ad1bfad393cf1

Step 3: Making the HTTP API call to the Bitcoin Average API.

def main(exchange, starting_price, amount, currency, limit_type, limit):
    :param exchange: The exchange where bitcoin was bought
    :param starting_price: The price at which bitcoin was bought
    :param amount: The amount of bitcoin
    :param currency: The currency bitcoin was bought in
    :param limit_type: The type of threshold, percent or amount
    :param limit: The value of the threshold
    :return: Current profit made

    API_ROOT = "https://apiv2.bitcoinaverage.com"

    response = requests.get("{api}/exchanges/{exchange}".format(api=API_ROOT, exchange=exchange), headers={'X-Signature': create_signature()})
    symbol = 'BTC'+currency
    latest_bid = response.json()['symbols'][symbol]['bid']
    result = calculate_profits(currency, latest_bid, starting_price, amount, limit_type, limit)
    return result

This is the function that accepts all of the parameters entered by the user and forwards them to the calculate_profits function which we’ll write next.
But before we start coding make sure you have the awesome requests http library installed.
Get it with:
pip install requests
The response from the requests will be in the following format:

    "name": "bitstamp",
    "display_name": "Bitstamp",
    "url": "https://bitstamp.net/",
    "timestamp": 1493816831,
    "data_source": "api",
    "symbols": {
        "XRPEUR": {
            "last": 0.0513,
            "volume": 5706005.4795,
            "ask": 0.0513,
            "bid": 0.0511
        "BTCUSD": {
            "last": 1474.74,
            "volume": 9207.05,
            "ask": 1474.70,
            "bid": 1471.81
        "BTCEUR": {
            "last": 1345.10,
            "volume": 1032.09,
            "ask": 1347.59,
            "bid": 1345.10
        "XRPUSD": {
            "last": 0.0560,
            "volume": 12515723.6935,
            "ask": 0.0560,
            "bid": 0.0557

As you see from this response you can discover all the available trading pairs at your exchange and you might want to extend this script and perform the profits check calculation on more than one trading pair.
For now we will only use the BTCUSD values from this response.
But first let’s cover what these values mean, ask, bid, last and volume.
Last: the last price by which Bitcoin was sold or bought
Bid: the best (highest) bid. The highest price at which someone is willing to buy Bitcoin.
Ask: the best (lowest) ask. The lowest price at which someone is willing to sell Bitcoin.
Volume: The total number of Bitcoin bought and sold at this exchange in the last 24 hours.
From these values we are only interested in the “bid” value because if we were to sell our coins right now, that is the price we would get for them.
So after we extract the bid, we just pass all the values to the calculate_profits function.

Step 4: Algorithm for checking our profits

def calc_percent_diff(now, base):
    difference = now - base
    return difference * 100 / base

def calculate_profits(cc, latest_bid, starting_price, amount, limit_type, limit):
    difference = abs((latest_bid - starting_price) * amount)
    single_diff = latest_bid - starting_price
    if limit_type == 'percent':
        percent_difference = calc_percent_diff(latest_bid, starting_price)
        if percent_difference >= limit:
            return "The bitcoin price has increased by {:.2f} %, you have a profit of {:.2f} {}n That is {:.2f} {} per coin.".format(percent_difference, difference, cc, abs(single_diff), cc)
        elif percent_difference <= -1 * limit:
            return "The bitcoin price has decreased by {:.2f} %, you have a loss of {:.2f} {}n That is {:.2f} {} per coin.".format(abs(percent_difference), difference, cc, abs(single_diff), cc)
        if single_diff >= limit:
            return "The bitcoin price has increased by {:.2f} {}, you have a profit of {:.2f} {}n That is {:.2f} {} per coin.".format(single_diff, cc, difference, cc, abs(single_diff), cc)
        elif single_diff <= -1 * limit:
            return "The bitcoin price has decreased by {:.2f} {}, you have a loss of {:.2f} {}n That is {:.2f} {} per coin.".format(single_diff, cc, abs(difference), cc, abs(single_diff), cc)

What we’re doing here is comparing the starting price with the latest bid price we got from the API.
If the script is setup to check in percent, we’re doing that, otherwise we’re checking for the absolute difference in dollars between the two prices.
If the latest price has deviated from the starting price more than a certain amount then we are constructing a helpful message that we will present to the end user.

Step 5: Running the script in an infinite loop and displaying desktop notifications on Linux and Mac

if __name__ == '__main__':
    my_exchange = input("Your exchange:")
    starting_price = input("Bitcoin starting price:")
    amount = input("Bitcoin amount:")
    currency = input("Your currency (default USD):")
    check_every = input("Check every (seconds):")
    threshold = input("Choose to be notified when a certain limit is reachedn1) Percent limit: n2) Amount limit: n ")
    limit_type = None
    limit = 0
    if threshold == '1':
        limit_type = 'percent'
        limit = input("Percent:")
    elif threshold == '2':
        limit_type = 'amount'
        limit = input("Amount:")
    if not currency:
        currency = 'USD'
    notifications = input("Choose desktop notifications: n0) Non1) Macn2) Linuxn")
    while True:
        result = main(my_exchange, float(starting_price), float(amount), currency, limit_type, float(limit))
        if result:
            if notifications == '1':
                content = 'display notification "{result}" with title "Bitcoin Profits" '.format(result=result)
                subprocess.run(['/usr/bin/osascript', '-e', content])
            elif notifications == '2':
                subprocess.run(['notify-send', 'Bitcoin Profits', result])

First we’re getting all the data we need from the user and then using infinite looping (while True:) we are executing the main function from before.
If this function happens to return us some answer, that means there is something to show to the user.
Depending on his choosing either Linux or Mac desktop notification will be generated. If he hasn’t chosen notifications, or is a Windows user, the message will be printed in the terminal.

Linux desktop notifications

I have only tried this on Ubuntu Linux, so these might not work on other Linux distros.
The library for generating notifications is called notify-send and it’s very simple to use.
In our example above I am running it like this.

notify-send 'Bitcoin Profits' result

This will show the result as the body of the notification and “Bitcoin Profits” as the title.

Mac desktop notifications

For Mac we’re using the osascript command which lets us run AppleScript commands from inside the terminal.
The command for showing a notification is as follows:

osascript -e 'display notification "You have made 10% of profits" with title "Bitcoin profits" '

Full code

The full code can be found here: https://gist.github.com/KolevDarko/e4e57825871c89adfaf0bf09eded3b45

We hope you enjoyed the first guide in this series and found it usefull.

Leave a Reply

Your email address will not be published. Required fields are marked *