Skip to content

Instantly share code, notes, and snippets.

@badmofo
Last active June 27, 2017 15:30
Show Gist options
  • Save badmofo/ab5f5d9c71168233c07e18aee9d740b5 to your computer and use it in GitHub Desktop.
Save badmofo/ab5f5d9c71168233c07e18aee9d740b5 to your computer and use it in GitHub Desktop.
bitstamp.py
import hmac
import hashlib
import requests
import time
import json
import re
import arrow
from decimal import Decimal
def to_bytes(s):
return s if isinstance(s, bytes) else str(s).encode('utf-8')
class BitstampClient(object):
def __init__(self, customer_id, api_key, api_secret):
self.customer_id = str(customer_id)
self.api_key = api_key
self.api_secret = api_secret
def auth(self):
nonce = int(time.time() * 1e6)
message = str(nonce) + self.customer_id + self.api_key
signature = hmac.new(
to_bytes(self.api_secret),
msg=to_bytes(message),
digestmod=hashlib.sha256
).hexdigest().upper()
return {'key': self.api_key, 'nonce': str(nonce), 'signature': signature}
def balances(self):
url = 'https://www.bitstamp.net/api/v2/balance/'
params = self.auth()
r = requests.post(url, data=params)
result = r.json()
balances = {}
for k,v in result.items():
m = re.match(r'^(.*)_balance$', k)
if m:
balances[m.group(1).upper()] = Decimal(v) or Decimal('0')
return balances
def user_transactions(self, offset=0, limit=100, sort='desc'):
url = 'https://www.bitstamp.net/api/v2/user_transactions/'
params = self.auth()
params.update({'offset': str(offset), 'limit': str(limit), 'sort': sort})
r = requests.post(url, data=params)
txs = r.json()
for t in txs:
t['type'] = int(t['type'])
t['btc'] = Decimal(t['btc'])
t['usd'] = Decimal(t['usd'])
t['fee'] = Decimal(t['fee'])
t['time_t'] = arrow.get(t['datetime']).timestamp
return txs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment