DEV Community

Cover image for The easiest way to track your Bitcoin profits
Darko
Darko

Posted on • Originally published at Medium

The easiest way to track your Bitcoin profits

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 from the market volatility.

Often times this becomes distracting and time consuming, but not anymore. Let's build a script which automatically checks the price at your favorite exchange, compares it to your starting price and notifies you of the profit you are making.

Quick Start Guide

If you just want to run the script without digging into it you can get the final code from here. Then just copy and paste it into a file with “.py” extension 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 at that price.

  4. Your currency (default USD): The fiat currency in which you are trading.

  5. Check every (seconds): The script performs the calculation in an infinite loop, so this parameter specifies how much to wait between subsequent executions. You can choose from 4 options for our API.

  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 the first option (1), 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 form the starting price (assuming US dollars is your currency).

Full Developer guide

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 here.

We have a complicated authentication method and a simple one.
Let's use the simpler one here. Just copy the public key and put it in a header in your request.
Header

x-ba-key: <your public key here>

Step 2: Making the Http API call to the BitcoinAverage 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-ba-key': <your public key here>})
    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 main 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.

Let’s checkout the response we get from our API real quick.


{
    "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 can extend this script to perform the profits check calculation on more than one trading pair.

For now we will only use the BTCUSD values from the response.
Let’s cover what these values mean: ask, bid, last and volume.

Last: the last price at which Bitcoin was sold or bought
Bid: the best (highest) bid. The highest price someone is willing to buy Bitcoin at your exchange right now.
Ask: the best (lowest) ask. The lowest price someone is willing to sell Bitcoin at your exchange right now.
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 3: 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)
    else:
        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 are 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 are doing that, otherwise we are 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 4: 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 reached\n1) 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) No\n1) Mac\n2) Linux\n")
    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])
            else:
                print(result)
            break
        time.sleep(int(check_every))

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 distributions. 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

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

Full code

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

If you have any questions about extending this script or doing something similar feel free to ask in the comments.

Top comments (1)

Collapse
 
koriroro profile image
koriroro

The cryptocurrency is one of the hottest topics nowadays. I'm just thinking about investing money in bitcoin or altcoin. Before investing I decided to learn a little bit more about it. Have you heard about the bitcoin bot? I have read that it helps to delegate some tasks like monitoring and trading when the course changes. Why I'm interested in it because it allows to earn money even when you sleep or haven't got time to monitor the market situation