In order to setup the bitcoin trade advice alert, go through the following steps:
- First, start by importing the bitcoin price API, called exchanges:
#!/usr/bin/python
# import modules
# Make sure to copy the exchanges from https://github.com/dursk/bitcoin-price-api
# to the same location as this script
from exchanges.bitfinex import Bitfinex
- Also import smtplib, which we will use for triggering the bitcoin price alert. Here, we define a function called trigger_email. We then set the server user and email details:
import smtplib
# Function to send email
def trigger_email(msg):
# Change these to your email details
email_user = "[email protected]"
email_password = "bitcoin1"
smtp_server = 'smtp.gmail.com'
smtp_port = 587
email_from = "[email protected]"
email_to = "[email protected]"
- Using smtplib, send the sendmail function to send the price alert email, as shown in the following code:
# login to the email server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(email_user, email_password)
# send email
server.sendmail(email_from, email_to, msg)
server.quit()
- Next, define the buy and sell price thresholds for bitcoin. Use these thresholds to make decisions on whether to sell or buy bitcoin:
# define buy and sell thresholds for Bitcoin. These values you have to change according to the current price of the bitcoin.
buy_thresh = 6500
sell_thresh = 6500
- Next, we get the current bitcoin price and the current asking price for bitcoin from Bitfinex bitcoin exchange using the exchanges module that we imported in the bitcoin_trade.py script. We can also use some other exchanges, such as CoinDesk, but for the moment, we will use Bitfinex. We will get these prices in btc_sell_price and btc_buy_price.
# get Bitcoin prices
btc_sell_price = Bitfinex().get_current_bid()
btc_buy_price = Bitfinex().get_current_ask()
- Once we have the current prices, we can compare them with the threshold prices we have set before.
- If the buy price is lower than the sell threshold, we call the trigger_email function to send a buy trigger email alarm:
# Trigger Buy email if buy price is lower than threshold
if btc_buy_price < buy_thresh:
email_msg = """
Bitcoin Buy Price is %s which is lower than
threshold price of %s.
Good time to buy!""" % (btc_buy_price, buy_thresh)
trigger_email(email_msg)
- If the sell price is greater than the sell threshold, we call the trigger_email function to send the sell trigger email alert:
# Trigger sell email if sell price is higher than threshold
if btc_sell_price > sell_thresh:
email_msg = """
Bitcoin sell Price is %s which is higher than
threshold price of %s.
Good time to sell!""" % (btc_sell_price, sell_thresh)
trigger_email(email_msg)