Create a bitcoin price watcher
codesharedot
Posted on September 3, 2019
You can create your own cryptocurrency price ticket. This is an excellent exercise for learning how to use APIs from Python.
A free API is the coinmarketcap API. You can request price information directly from a script. To make the request we use the requests module.
#!/usr/bin/python3
import requests
bitcoin_api_url = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/'
response = requests.get(bitcoin_api_url)
response_json = response.json()
print(response_json)
That outputs the current price and more information to your terminal if you run the script.
[{'id': 'bitcoin', 'name': 'Bitcoin', 'symbol': 'BTC', 'rank': '1', 'price_usd': '10681.1782936', 'price_btc': '1.0', '24h_volume_usd': '21114044526.6', 'market_cap_usd': '191336753303', 'available_supply': '17913450.0', 'total_supply': '17913450.0', 'max_supply': '21000000.0', 'percent_change_1h': '0.11', 'percent_change_24h': '7.82', 'percent_change_7d': '5.02', 'last_updated': '1567522779'}]
You can get the current price like this:
for coin in response.json():
print(coin.get("price_usd", "U$S Price not provided"))
That outputs $10616.5048903 which needs rounding. This is a string, but you can convert it like this:
btc_price = float(("{0:.2f}").format(float(price)))
print("$ " + str(btc_price))
There's probably a nicer way to do this, but this does the job.
Conversion
Big chance you use another currency if you don't live in the US. You can use the module forex_python to convert the rate.
Load the module:
from forex_python.converter import CurrencyRates
Then you can get the conversion rate of USD to another currency like this:
c = CurrencyRates()
rate = c.get_rate('USD', 'EUR')
print(rate)
Then convert the btc price to euro:
btc_price_eur = float(("{0:.2f}").format(float(price)*rate))
print("\u20ac " + str(btc_price_eur))
What is this "\u20ac " you ask? This is how you can print the euro symbol. It's the unicode font code.
You can find a list of unicode currency symbols here:
unicode currency symbols.
Notifications
If you are trading, you want to get notifications instead of watching the price 24/7. You can use the os module with notify-send app (Linux) to get notifications.
if btc_price_eur > 9000:
os.system("notify-send trade btc")
You can do this on your phone too, or email. To keep watching the price, you can put the whole code in a loop and keep it running in the background. Happy coding! :)
Read more:
Posted on September 3, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.