Created
May 22, 2013 14:40
-
-
Save xsleonard/5628039 to your computer and use it in GitHub Desktop.
mtgox exchange rate calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
''' | |
USAGE: | |
./rate.py <amount:float> <bid|ask> | |
''' | |
import sys | |
import requests | |
ORDER_DEPTH_URI = 'http://data.mtgox.com/api/1/BTCUSD/depth/fetch' | |
def get_data(type): | |
return requests.get(ORDER_DEPTH_URI).json()['return']['{0}s'.format(type)] | |
def get_rate(amount, type): | |
if not amount: | |
raise SystemExit('Enter a value') | |
data = get_data(type) | |
data.sort(key=lambda a: a['price'], reverse=(type == 'bid')) | |
remaining_amount = amount | |
prices = [] | |
amounts = [] | |
for b in data: | |
if remaining_amount < b['amount']: | |
prices.append(b['price']) | |
amounts.append(remaining_amount) | |
break | |
prices.append(b['price']) | |
amounts.append(b['amount']) | |
remaining_amount -= b['amount'] | |
offers = [b[0] * b[1] for b in zip(prices, amounts)] | |
total = sum(offers) | |
return total / sum(amounts) | |
def get_bid_rate(amount): | |
return get_rate(amount, 'bid') | |
def get_ask_rate(amount): | |
return get_rate(amount, 'ask') | |
if __name__ == '__main__': | |
if len(sys.argv) > 2 and sys.argv[2] == 'bid': | |
print get_bid_rate(float(sys.argv[1])) | |
else: | |
print get_ask_rate(float(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment