A script to fetch price data from coinmarketcap.com

The Code
import urllib.request
import json
def getCoins():
coin = open("coins.txt", "r").read()
coins = coin.split("\n")
for c in coins:
if(c != ""):
print(c + ": " + getRate(c))
def getRate(coin):
r = urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/" + coin)
d = json.load(r)
data = d[0]
return(data['price_usd'])
getCoins()
Explaining the above a little more
import urllib.request
import json
So this is just importing stuff that will be needed for the rest of the program
just note that urllib.request is specific to python3, so this probably will not work so
well with python2.
def getCoins():
coin = open("coins.txt", "r").read()
coins = coin.split("\n")
for c in coins:
if(c != ""):
print(c + ": " + getRate(c))
Okay here we have a block that reads a file on disk for names on coins, it has to be formed as
the name is formed in the url on coinmarketcap, so if you want to know about harvest, you have to write
harvest-masternode-coin in the config file/coins.txt file.
the if statement is needed since the split leaves a blank string in the list, so this just weeds that out.
def getRate(coin):
r = urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/" + coin)
d = json.load(r)
data = d[0]
return(data['price_usd'])
This one is the piece of the code that does the most important part
namely the fetching from coinmarketcap.com, and then display the useful information.
Your code doesn't work for me, you may be missing part where you store data into the text file?
Btw, you probably know already, but can't hurt mentioning for someone else, coinmarketcap does also have an API and it is quite simple to use it:
These upper 3 lines gives you price for Steem. Of course, coinmarketcap needs to be installed first with: "pip install coinmarketcap"
Yeah the reason the code does not work would be the lack of coins.txt
I wrote this on a machine that was not so happy about libraries so I couldn't really use stuff that was not preinstalled in python, else I would have used requests for the http stuff.
Apis are good, but I think this is simple enough to not need that.