def test_get_sells(self): client = Client(api_key, api_secret) sells = client.get_sells('foo') self.assertIsInstance(sells, APIObject) self.assertEqual(sells.data, mock_collection) for sell in sells.data: self.assertIsInstance(sell, Sell)
def fetch_from_cb(what_to_fetch: str, cb_client: Client, cb_account_id: str) -> []: """Fetch the specified data from Coinbase buys and sells: Merchant buyouts like FIAT -> BTC etc. transfers: Coin transfers from Coinbase to a wallet address Arguments: what_to_fetch {str} -- either "buys", "sells" or "transfers" cb_client {Client} -- coinbase client object cb_account_id {str} -- coinbase account id to use Returns: [] -- a list with the APIObjects from Coinbase """ the_list = [] data = dict() next_uri = "" while next_uri != None: if what_to_fetch == "buys": ret = cb_client.get_buys(cb_account_id, **data) elif what_to_fetch == "sells": ret = cb_client.get_sells(cb_account_id, **data) elif what_to_fetch == "transfers": ret = cb_client.get_transactions(cb_account_id, **data) the_list.extend(ret["data"]) next_uri = ret.pagination["next_uri"] if next_uri != None: data["starting_after"] = ret["data"][-1]["id"] return the_list
def update_from_remote(): from coinbase.wallet.client import Client import yaml keys = yaml.load(open(XDG_CONFIG_HOME + "/mistbat/secrets.yaml"))["coinbase"] client = Client(keys["api_key"], keys["secret_key"]) accounts = [ { "id": account.id, "currency": account.balance.currency, "amount": account.balance.amount, } for account in client.get_accounts().data ] cb_resources = {"buys": {}, "sells": {}, "transactions_filtered": {}} for account in accounts: # Coinbase Buys buys = json.loads(str(client.get_buys(account["id"])))["data"] cb_resources["buys"][account["currency"]] = list( filter(lambda buy: buy["status"] != "canceled", buys) ) # Coinbase Sells sells = json.loads(str(client.get_sells(account["id"])))["data"] cb_resources["sells"][account["currency"]] = list( filter(lambda sell: sell["status"] != "canceled", sells) ) # Coinbase Transactions (Other) # Need to filter buys and sells out of transactions since transactions # includes those in addition to the other transactions transactions = json.loads(str(client.get_transactions(account["id"])))["data"] cb_resources["transactions_filtered"][account["currency"]] = list( filter( lambda tx: tx["type"] != "buy" and tx["type"] != "sell" and tx["status"] != "canceled", transactions, ) ) with open(XDG_DATA_HOME + "/mistbat/coinbase.json", "w") as f: f.write(json.dumps(cb_resources, indent=2))
page = 2 while pagination != None and pagination['next_uri'] != None: print("--- Getting buys via API (page %d)" % page) starting_after_guid = re.search( 'starting_after=([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})', pagination.next_uri, re.I).group(1) next_page = coinbase_client.get_buys( account['id'], starting_after=starting_after_guid) coinbase_accounts['data'][i]['buys'][ 'data'] = coinbase_accounts['data'][i]['buys'][ 'data'] + next_page['data'] pagination = next_page.pagination page = page + 1 print("--- Getting sells via API") coinbase_accounts['data'][i]['sells'] = coinbase_client.get_sells( account['id']) pagination = coinbase_accounts['data'][i]['sells'].pagination page = 2 while pagination != None and pagination['next_uri'] != None: print("--- Getting sells via API (page %d)" % page) starting_after_guid = re.search( 'starting_after=([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})', pagination.next_uri, re.I).group(1) next_page = coinbase_client.get_sells( account['id'], starting_after=starting_after_guid) coinbase_accounts['data'][i]['sells'][ 'data'] = coinbase_accounts['data'][i]['sells'][ 'data'] + next_page['data'] pagination = next_page.pagination page = page + 1
class CoinBaseClient: def __init__(self): self.client = None self.user = None self.accounts = None self.buyList = [] self.sellList = [] self.transactionList = [] # self.Connect() self.InitialiseData() def Connect(self): self.client = Client(API_KEY, API_SECRET) def InitialiseData(self): with open(BUYLIST_DATA_JSON_PATH_, 'r+') as bP: self.buyList = Serializer.deserialize(bP.read()) # self.getBuys() # self.getTransactions() # self.getCurrentUser() def getCurrentUser(self): if self.user is None: self.user = self.client.get_current_user() return self.user def getBuys(self): with open(BUYLIST_DATA_JSON_PATH_, 'rb') as bP: self.buyList.__dict__ = Serializer.deserialize(bP.read()) if self.buyList is None or len(self.buyList) == 0: for account in self.getAccounts(): buys = self.client.get_buys(account.id)['data'] crypto = CryptoBuyInfo() for buy in buys: tx = Transaction(str(buy.id), float(buy.subtotal.amount), float(buy.amount.amount), parser.parse(buy.payout_at), buy.amount.currency, float(buy.fees[0].amount.amount), self.getPrice(buy.amount.currency, 'AUD')) crypto.append(tx) self.buyList.append(crypto) json_str = Serializer.serialize(self.buyList) with open(BUYLIST_DATA_JSON_PATH_, 'wb') as b: b.write(json_str) def getTransactions(self): if len(self.transactionList) == 0: for account in self.getAccounts(): self.transactionList.append( self.client.get_transactions(account.id)['data']) # return self.transactionList def getSells(self): return self.client.get_sells(self.user.id) def getAccounts(self): if self.accounts is None: self.accounts = self.client.get_accounts()['data'] return self.accounts def getPrice(self, currency, nativeCurrency): currencyPair = str(currency + '-' + nativeCurrency) response = requests.get('https://api.coinbase.com/v2/prices/' + currencyPair + '/sell') return float( json.loads(response.content.decode("utf-8"))['data']['amount'])
starting_after_guid = re.search( 'starting_after=([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})', pagination.next_uri, re.I).group(1) next_page = coinbase_client.get_buys( account['id'], order='asc', limit=100, starting_after=starting_after_guid) coinbase_accounts['data'][i]['buys'][ 'data'] = coinbase_accounts['data'][i]['buys'][ 'data'] + next_page['data'] pagination = next_page.pagination page = page + 1 print("--- Getting sells via API") coinbase_accounts['data'][i]['sells'] = coinbase_client.get_sells( account['id'], order='asc', limit=100) pagination = coinbase_accounts['data'][i]['sells'].pagination page = 2 while pagination != None and pagination['next_uri'] != None: print("--- Getting sells via API (page %d)" % page) starting_after_guid = re.search( 'starting_after=([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})', pagination.next_uri, re.I).group(1) next_page = coinbase_client.get_sells( account['id'], order='asc', limit=100, starting_after=starting_after_guid) coinbase_accounts['data'][i]['sells'][ 'data'] = coinbase_accounts['data'][i]['sells'][ 'data'] + next_page['data']
class Coinbase(Exchange): client = None def __init__(self, config): """ Initialize the client :param config: dictionary containing keys `key` and `secret` """ try: self.client = Client(config['key'], config['secret']) print('Connected to Coinbase.') except: print('Could not connect to Coinbase.') def get_price(self, order_time, product='BTC-USD'): """Gets price for a specific day. Unfortunately, it does not allow date and time answers. :return: """ return self.client.get_spot_price(date=order_time, currency_pair=product) def parse_order(self, order, buysell): """ :param order: :param buysell: :return: """ order_time = date_parser.parse(order['payout_at']) product = order['amount']['currency'] exchange_currency = order['total']['currency'] currency_pair = '-'.join([order['amount']['currency'], order['total']['currency']]) cost = float(order['total']['amount']) amount = float(order['amount']['amount']) cost_per_coin = cost / amount return { 'order_time': order_time, 'product': product, 'currency': exchange_currency, 'currency_pair': currency_pair, 'buysell': buysell, 'cost': cost, 'amount': amount, 'cost_per_coin': cost_per_coin, } # get the buys and sells for an account def get_account_transactions(self, account): """ :param account: :return: """ buys = [] sells = [] buys_complex = self.client.get_buys(account['id']) sells_complex = self.client.get_sells(account['id']) for order in buys_complex['data']: buys.append(self.parse_order(order, 'buy')) for order in sells_complex['data']: sells.append(self.parse_order(order, 'sell')) return buys, sells def get_buys_sells(self): """ :return: """ # Get the Coinbase accounts accounts = self.client.get_accounts() buys = [] sells = [] for account in accounts['data']: # Only use the USD and BTC accounts since they will contain all transaction ids if account['currency'] != 'USD': buys_dummy, sells_dummy = self.get_account_transactions(account) buys += buys_dummy sells += sells_dummy return buys, sells
client = Client(api_key, api_secret, api_version='2017-05-19') accounts = client.get_accounts() for account in accounts['data']: running_buy = 0 running_sell = 0 initial_total =0 # Generate the total amount of cash that is currently invested account_id = account['id'] deposits = client.get_buys(account_id) withdrawls = client.get_sells(account_id) for deposit in deposits['data']: if deposit['status'] == "completed": running_buy = running_buy + float(deposit['subtotal']['amount']) for withdrawl in withdrawls['data']: if deposit['status'] == "completed": running_sell = running_sell + float(withdrawl['subtotal']['amount']) initial_total = running_buy - running_sell # Calculate how much of each currency currently have currency = account['balance']['currency'] vc_balance = account['balance']['amount'] print "Total of cash investments " + str(initial_total)