Skip to content

Instantly share code, notes, and snippets.

@anthonybaldwin
Last active June 10, 2019 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonybaldwin/c1cdaa3a528c13cff35054586d5eb7d5 to your computer and use it in GitHub Desktop.
Save anthonybaldwin/c1cdaa3a528c13cff35054586d5eb7d5 to your computer and use it in GitHub Desktop.
Save crypto prices to a text file
import requests
import time, datetime
import sys
# find a home for these
directory = 'C://Users//antho//Downloads//Assets//' # include trailing slash, e.g., 'C://Users//antho//Downloads//Assets//'
# get latest price of desired coin from coinmarketcap.com
def get_latest_price(coin):
response = None
while response is None:
try:
response = requests.get('https://api.coinmarketcap.com/v1/ticker/' + coin)
except:
pass
# i know a guy named json
response_json = response.json()
# return rounded float as string
return str(round(float(response_json[0]['price_usd']),2))
# write price of coin to local file in directory
def write_price_file(coin):
# get price of coin
price = "$" + get_latest_price(coin)
# cmd line output
print(str(datetime.datetime.now()) + ": " + coin + " price is now " + price + "...")
# write price to file
file = open(directory + coin + "-price.txt","w")
file.write(price)
file.close()
# announce that we're starting
print("Starting... Press CTRL+C to exit.")
# system clock at start
start = time.time()
# forever, every 60 seconds, until exit
try:
while True:
# update price files
write_price_file('Bitcoin')
write_price_file('Ethereum')
write_price_file('Litecoin')
# etc...
# now it works
sys.stdout.flush()
# sleep tied to system clock for accuracy https://stackoverflow.com/a/25251804
time.sleep(60.0 - ((time.time() - start) % 60.0))
except KeyboardInterrupt:
# announce that we're stopping
print("Stopping...")
except Exception as e:
# announce any errors
print("ERROR:", e, file=sys.stderr)
input("There was an error... Press Enter to exit.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment