Skip to content

Instantly share code, notes, and snippets.

@mcohen01
Last active June 8, 2017 19:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcohen01/d5b2319432abad9c8ea8d9726e8123d4 to your computer and use it in GitHub Desktop.
Save mcohen01/d5b2319432abad9c8ea8d9726e8123d4 to your computer and use it in GitHub Desktop.
import hmac, hashlib, locale, math, time, requests, base64
from requests.auth import AuthBase
class CoinbaseExchangeAuth(AuthBase):
def __init__(self, api_key, secret_key, passphrase):
self.api_key = api_key
self.secret_key = secret_key
self.passphrase = passphrase
def __call__(self, request):
timestamp = str(time.time())
message = timestamp + request.method + request.path_url + (request.body or '')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'CB-ACCESS-PASSPHRASE': self.passphrase,
'Content-Type': 'application/json'
})
return request
api_url = 'https://api.gdax.com/'
read_only = CoinbaseExchangeAuth('apiKey',
'secret',
'passphrase')
write = CoinbaseExchangeAuth('apiKey',
'secret',
'passphrase')
def server_time():
return requests.get(api_url + 'time', auth=read_only).json()
def round(decimal):
try:
return format(math.ceil(float(decimal) * 100) / 100, '.2f')
except:
# import traceback
# print(decimal)
# traceback.print_exc()
return decimal
def position():
x = requests.get(api_url + 'position', auth=read_only).json()
total = 0
for y in x['accounts'].iteritems():
balance = float(y[1]['balance'])
if balance > 0:
if y[0] != 'USD':
url = api_url + 'products/' + y[0] + '-USD/ticker'
price = requests.get(url, auth=read_only).json()['price']
amount = round(balance * float(price))
total += float(amount)
price = round(float(price))
print(y[0] + ': $' + str(amount) + ' ( ' +
str(balance) + ' @ ' + str(price)) + ' )'
else:
total += balance
print('USD: ' + str(balance))
print('Total: $' + str(total))
def get_order(id, delete=False):
if delete:
return pretty(requests.delete(api_url + 'orders/' + id, auth=write).json())
else:
return pretty(requests.get(api_url + 'orders/' + id, auth=read_only).json())
def place_order(size,
price,
side,
product_id='LTC-USD',
time_in_force='GTT',
cancel_after='day'):
order = {
'size': size,
'price': price,
'side': side,
'product_id': product_id,
'type': 'limit',
'time_in_force': time_in_force,
'post_only': True
}
if time_in_force == 'GTT':
order['cancel_after'] = cancel_after
r = requests.post(api_url + 'orders', json=order, auth=write)
# print(r.json())
# print(r.headers)
return r.json()
def cancel_order(id):
r = requests.delete(api_url + 'orders/' + id, auth=write).json()
pretty(r)
def orders():
[pretty(x) for x in requests.get(api_url + 'orders', auth=read_only).json()]
def order_book(product_id, level=1):
url = api_url + 'products/' + product_id + '/book?level=' + str(level)
resp = requests.get(url, auth=read_only).json()
print(resp)#['sequence'])
print('asks')
with open('asks.csv', 'a') as f:
for x in reversed(resp['asks']):
price = round(x[0])
size = round(x[1])
f.write(price + ',' + size + '\n')
print('bids')
with open('bids.csv', 'a') as f:
for x in resp['bids']:
price = round(x[0])
size = round(x[1])
f.write(price + ',' + size + '\n')
def ticker(product_id):
url = api_url + 'products/' + product_id + '/ticker'
return requests.get(url, auth=read_only).json()
def prices():
locale.setlocale(locale.LC_ALL, 'en_US')
btc = ticker('BTC-USD')
eth = ticker('ETH-USD')
ltc = ticker('LTC-USD')
output = lambda x: x['bid'] + '-' + x['ask'] + ' $' + \
locale.format("%d",
float(round(float(x['volume']) * float(x['bid']))),
grouping=True)
print(output(btc))
print(output(eth))
print(output(ltc))
def pretty(obj, effects=False):
if isinstance(obj, list):
print(obj)
elif isinstance(obj, dict):
print('{')
for k in sorted(obj.keys()):
print(' "' + str(k) + '": "' + str(obj[k]) + '",')
print('}')
else:
print(str(obj))
# order_book('ETH-USD', 3)
# position()
# prices()
# orders()
# get_order('0f1e07bd-1acd-4751-b382-9e71d3ad8928')
# place_order(100, 37.97, 'sell', product_id='LTC-USD')
# place_order(50, 181.63, 'sell', product_id='ETH-USD')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment