Automatic checkup of bitcoin status

Using Python and BTC-e

Published on January 7, 2016

Together with a couple of friends we each exchanged around 72 $ (500 kr) into bitcoins in the early 2014. We used it for trading online bitcoin mining power which we would later sell again for a profit (the site does no longer offer mining since it has become unprofitable). At our highest we had doubled our initial bitcoin after which we split it equally among us.

I decided to move mine to an online bitcoin exchange service, called BTC-e. Here, it is possible to place future orders. Say for example that you have 0.1 BTC and you would like to exchange that to dollars when the rate hits 500 $ pr. BTC. The system then enables you to place the order, waiting there until the rate hits the desired value and the order is fulfilled.
However, no one wants to check in routinely to see if their orders have been completed or not so I decided to give the site's API a try.

Using the BTC-e API

To use the API we need the BTC API key and secret found after logging in to BTC-e. Furthermore we need something called a cryptographic nonce which is basically a certain one time number that we need to send along with our request which needs to match the number BTC-e expects to receive. After that, we send the request, get the response and act accordingly: if the order has been completed then send an email to notify the user, else do nothing. 

We start by preparing the encrypted message we need to send to BTC-e using the sha512 hashing algorithm.

# Method name and nonce go into the POST parameters
params = {"method": "getInfo",
              "nonce": nonce}
params = urllib.urlencode(params)

# Hash the params string to produce the Sign header value
H = hmac.new(BTC_api_secret, digestmod=hashlib.sha512)
H.update(params)
sign = H.hexdigest()

headers = {"Content-type": "application/x-www-form-urlencoded",
               "Key": BTC_api_key,
               "Sign": sign}

We can now establish our connection with BTC-e.

# Connect to BTC-e and get response
conn = httplib.HTTPSConnection("btc-e.com")
conn.request("POST", "/tapi", params, headers)
response = json.load(conn.getresponse())

# Check if connection to BTC-e and if nonce was succesfull
if 'error' in response:
    if 'invalid nonce parameter;' in response['error']:
        open_orders = -1

         # Get the proper nonce
         l = []
         for t in str(response['error']).replace(":", " ").split():
             try:
                 l.append(float(t))
             except ValueError:
                 pass
    else:
        open_orders = response['return']['open_orders']
        l = [-1]

conn.close()

Here we notice the checking of the nonce, mentioned earlier. If we provide the wrong nonce the response will contain something like this "Expected nonce: 11, got 10". We then easily extract the expected nonce and use that next time the loop runs. 

Now we only need to be able to send an email, so we write a small script which does this. For this to work we need at least two email addresses, one sending and one receiving as well as having SMTP access to the sending address's mail server. In my case I used the one provided by my web hosting service. 

# Sender and receiver
s = 'Sender email'
s_pass = 'Sender email password'
r = 'Receiver email address'

# Email server and port
mail = smtplib.SMTP('email server', 'port')
mail.ehlo()
mail.starttls()
mail.login(s, s_pass)

# Header needed
header = 'To:' + r + '\n' + 'From: ' + s + '\n' + 'Subject:BTC-e order \n'
content = header + '\n ' + message + ' \n\n'
mail.sendmail(s, r, content)
mail.close()<br />

We now finally have all we need and our main script simply looks like this.

# Replace these with your own API key data
BTC_api_key = "Your api key"
BTC_api_secret = "Your api secret"

nonce = 0
check = 1
while check == 1:
    # Check status of btc-e
    open_orders, nonce = contact_btce(BTC_api_key, BTC_api_secret, nonce)
    sleep(1)

    if open_orders == 0 and nonce == -1:
        # print 'No open orders, time to send an email'
        send_mail('No open orders, login and check status: https://btc-e.com/')
        break

    elif open_orders > 0 and nonce == -1:
        # print 'Order still going, do nothing'
        # send_mail('Order still active: https://btc-e.com/')
        break

I then put the script into my crontab (on my Raspberry Pi) such that the script will run two times a day, at 9 am and 9 pm. Simply issue

crontab -e

and added

0 9,21 * * * python /home/pi/fBTCE/btce.py

And that's it ! 

Full code can be found at Github.