Skip to content

Instantly share code, notes, and snippets.

@siongui
Created November 28, 2013 13:59
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 siongui/7692278 to your computer and use it in GitHub Desktop.
Save siongui/7692278 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import httplib
import json
import time
import urllib2
def urlopen(url):
response = None
request = urllib2.Request(url=url)
try:
response = urllib2.urlopen(request).read()
except urllib2.HTTPError as err:
print "HTTPError: {} ({})".format(url, err.code)
except urllib2.URLError as err:
print "URLError: {} ({})".format(url, err.reason)
except httplib.BadStatusLine as err:
print "BadStatusLine: {}".format(url)
return response
def get_exchange_rate(from_currency="CNY", to_currency="USD"):
url = "https://finance.yahoo.com/d/quotes.csv?f=sl1&s=%s%s=X" % (
from_currency, to_currency)
data = urlopen(url)
if "%s%s" % (from_currency, to_currency) in data:
return float(data.strip().split(",")[1])
return None
urls = {
'bitstamp': "https://www.bitstamp.net/api/ticker/",
'btcchina': "https://data.btcchina.com/data/ticker",
'btce': "https://btc-e.com/api/2/btc_usd/ticker",
'coinjar': "https://coinjar-data.herokuapp.com/fair_rate.json",
'mtgox': "https://data.mtgox.com/api/1/BTCUSD/ticker",
}
stat = {}
while True:
for exchange, url in urls.iteritems():
json_data = urlopen(url)
if json_data:
try:
data = json.loads(json_data)
except ValueError as err:
print "ValueError: {} ({})".format(url, err)
continue
if exchange == 'bitstamp':
last = data['last']
elif exchange == 'btcchina':
exchange_rate = get_exchange_rate(from_currency="CNY",
to_currency="USD")
last = float(data['ticker']['last']) * exchange_rate
elif exchange == 'btce':
last = data['ticker']['last']
elif exchange == 'coinjar':
last = data['spot']['USD']
elif exchange == 'mtgox':
last = data['return']['last']['value']
last = float(last)
trend = ""
if stat.has_key(exchange):
if last > stat[exchange]['prev']:
trend = "\033[32m" + "up" + "\033[0m"
elif last < stat[exchange]['prev']:
trend = "\033[31m" + "down" + "\033[0m"
elif last == stat[exchange]['prev']:
trend = "\033[33m" + "unch" + "\033[0m"
else:
stat[exchange] = {}
print "\033[37m[%s]\033[0m" % datetime.datetime.now(), "\033[35m%8s\033[0m" % exchange, "%4.08f" % last, trend
stat[exchange]['prev'] = last
print "--"
time.sleep(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment