class CoinbaseData: """Get the latest data and update the states.""" def __init__(self, api_key, api_secret): """Init the coinbase data object.""" self.client = Client(api_key, api_secret) self.update() @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from coinbase.""" try: response = self.client.get_accounts() accounts = response["data"] # Most of Coinbase's API seems paginated now (25 items per page, but first page has 24). # This API gives a 'next_starting_after' property to send back as a 'starting_after' param. # Their API documentation is not up to date when writing these lines (2021-05-20) next_starting_after = response.pagination.next_starting_after while next_starting_after: response = self.client.get_accounts( starting_after=next_starting_after) accounts = accounts + response["data"] next_starting_after = response.pagination.next_starting_after self.accounts = accounts self.exchange_rates = self.client.get_exchange_rates() except AuthenticationError as coinbase_error: _LOGGER.error("Authentication error connecting to coinbase: %s", coinbase_error)
def create_coinbase_client(key, scrt): print("1. Connecting to Coinbase...") try: client = Client(key, scrt) client.get_accounts() return client except: raise Exception("Failed to connect to client. Please make sure key"\ " and secret are correct.")
class Coinbase(Client): def __init__(self, api_key, secret_key): self.api_key = api_key self.secret_key = secret_key self.client = Client( api_key, secret_key) def __call__(self): return self.client.get_accounts() def accounts(self): return self.client.get_accounts()
def test_check_Coinbase_valid_credentials(self): error_raised = False api_key = os.getenv('Coinbase_API_Key') api_secret = os.getenv('Coinbase_API_Secret') try: client = ClientCoinbase(api_key, api_secret) client.get_accounts() except: error_raised = True self.assertFalse(error_raised, "Invalid Coinbase credentials")
def _get_balance(self): """ method to get coinbase balances Returns: wallet: list of dict e.g. [{"balance": { "amount": "0.00058000", "currency": "BTC" }, "created_at": "2017-07-11T13:27:36Z", "currency": "BTC", "id": "3abaaa8a-d9e4-58d5-9143-df3ca8a3b67f", "name": "BTC Wallet", "native_balance": { "amount": "12.81", "currency": "SGD" }, "primary": true, "resource": "account", "resource_path": "/v2/accounts/3abaaa8a-d9e4-58d5-9143-df3ca8a3b67f", "type": "wallet", "updated_at": "2017-12-13T09:31:31Z"}] """ logger = logging.getLogger(__name__) logger.debug("Retrieving Coinbase account balances...") client = Client(self._key, self._secret) resp = client.get_accounts().data return resp
def fetch(config: Config) -> List[Raw]: client = Client(config.api_key, config.api_secret) accounts = client.get_accounts().data return list( Fetch.buys(accounts) + Fetch.sells(accounts) + Fetch.deposits(accounts) + Fetch.withdrawals(accounts))
class CoinbaseApi(object): client = None _api_version = '2018-07-15' def __init__(self, api_key, api_secret): self._api_key = api_key self._api_secret = api_secret self.authenticate() def authenticate(self): try: self.client = Client(self._api_key, self._api_secret, api_version=self._api_version) except Exception as e: raise e def get_accounts(self): accounts = self.client.get_accounts() if accounts: return accounts.data def get_account_value(self, account): price_response = self.client.get_spot_price( currency_pair=f'{account.balance.currency}-USD') price = price_response.get('amount') if price_response.get( 'amount') else 0 return float(price) * float(account.balance.amount)
def setData_Coinbase(self, coinbase_api_key, coinbase_api_secret, s, threaded=True): while (not self.stop_all): start = time.time() try: API_KEY = coinbase_api_key API_SECRET = coinbase_api_secret client = Client(API_KEY, API_SECRET) accounts = client.get_accounts() i = 0 for currency in accounts["data"]: if float(currency["balance"]["amount"]) > 0: self.names_coinbase_currencies[i] = currency[ "balance"]["currency"] self.balance_coinbase_currencies[i] = float( currency["balance"]["amount"]) self.values_coinbase_currencies[i] = float( currency["native_balance"]["amount"]) i += 1 if not threaded: break except: pass end = time.time() elapsed = (end - start) if (elapsed < s): time.sleep(s - elapsed)
class Coinbase: def __init__(self, key, secret): self.logger = Logger(__name__) try: self.client = Client(key, secret) except Exception as e: self.logger.log(e) raise ExchangeException(self.__class__.__name__, e) def getBalances(self): try: result = self.client.get_accounts() balances = {} for currency in result["data"]: name = currency["balance"]["currency"].upper() value = float(currency["balance"]["amount"]) if value >= Config.BALANCE_ZERO: balances[name] = value return balances except Exception as e: self.logger.log(e) raise ExchangeException(self.__class__.__name__, e)
def CoinBaseBalance(): print "Connecting To CoinBase..." client = CB_Client(CB_API_KEY, CB_API_SECRET, api_version="2017-05-19") accounts = client.get_accounts() wallets = {} for account in accounts.data: address_data = client.get_addresses(account.id).data x = int(random.random() * len(address_data)) #; x = 0 wallet_address = address_data[x].address print "\tRetrieving %s Wallet Data" % account.currency.name wallets.update({ account.balance.currency: { "AccountId": account.id, "Address": wallet_address, "Available": account.balance.amount, "Name": account.currency.name, "NativeBalance": account.native_balance.amount, "NativeCurrency": account.native_balance.currency, "Symbol": account.balance.currency, "TotalAmount": account.balance.amount } }) wallets.update({"ExchangeName": "CoinBase.com"}) print return wallets
class Coinbase(object): def __init__(self, name, wallet): self.name = name self.wallet = wallet self.c = Client(getenv("COINBASE_API_KEY"), getenv("COINBASE_API_SECRET")) def balance(self, market): accounts = self.c.get_accounts() for account in accounts["data"]: if account["currency"] == "USD": rate = 1.0 else: rate = market[account["currency"]] self.wallet.put(account["currency"], rate * float(account["balance"]["amount"])) def market(self): market = dict() symbols = ['BTC', 'ETH', 'LTC'] for symbol in symbols: resp = requests.get( "https://api.coinbase.com/v2/prices/{}-USD/buy".format(symbol)) result = resp.json() market[symbol] = float(result['data']['amount']) return market
def test_get_accounts(self): client = Client(api_key, api_secret) accounts = client.get_accounts() self.assertIsInstance(accounts, APIObject) self.assertEqual(accounts.data, mock_collection) for account in accounts.data: self.assertIsInstance(account, Account)
class CoinbaseExchange(): def __init__(self): self.CLIENT = Client(os.environ["Coinbase_API_Key"], os.environ["Coinbase_API_Secret"]) def get_balances(self): balances = [] info = self.CLIENT.get_accounts() for asset in info['data']: if float(asset['balance']['amount']) != 0: balance = { "amount": float(asset['balance']['amount']), "currency": asset['balance']['currency'] } balances.append(balance) return balances def get_Price(self, asset, currency): try: price_info = self.CLIENT.get_buy_price( currency_pair=f"{asset}-{currency}") except Exception as e: raise e else: price = float(price_info['amount']) return price
def test_get_accounts(self): client = Client(api_key, api_secret) accounts = client.get_accounts() self.assertIsInstance(accounts, APIObject) self.assertEqual(accounts.data, mock_collection) for account in accounts.data: self.assertIsInstance(account, Account)
def bitcoin_wallet(text): text = text.translate(None, string.punctuation) text = text.lower() text = text.split(" ") output = '' #check the amount of bitcoins in your wallet client = Client('QMxY1zh5et9LBH7X', '6yOdOFPvWAnc4qcElxHTHSJRqglgHNf3', api_version='2017-08-07') currency_code = 'AUD' accounts = client.get_accounts() for account in accounts.data: balance = account.balance exchange_rates = client.get_exchange_rates(currency=balance.currency) print(exchange_rates) price = decimal.Decimal( exchange_rates['rates']['AUD']) * decimal.Decimal(balance.amount) if (balance.currency == 'BTC'): currency_name = 'bitcoins' elif (balance.currency == 'ETH'): currency_name = 'ethereum' else: currency_name = 'litecoins' if (balance.amount == 0): balance.amount = 0 output += account.name + ' has ' + balance.amount + ' ' + currency_name + ', valued at ' + str( round(decimal.Decimal(price), 2)) + ' ' + currency_code + '. ' return output
class Trader(threading.Thread): def __init__(self, api_key, api_secret, alpha=0.5): assert 0 < alpha <= 1.0 # smoothing factor for the exponential moving avg function super(threading.Thread, self).__init__() self.alpha = alpha self.client = Client(api_key, api_secret) self.user = self.client.get_current_user() self.buys = [] self.sells = [] print 'Trading As: %s (%s)' % (self.user['name'], self.user['email']) print 'Starting Balance: $%s (%s BTC @ $%s/BTC)' % (self.balance['USD'], self.balance['BTC'], self.get_price()) @property def account(self): return [acct for acct in self.client.get_accounts()['data'] if acct['balance']['currency'] == 'BTC'][0] @property def balance(self): return { self.account['balance']['currency']: float(self.account['balance']['amount']), self.account['native_balance']['currency']: float(self.account['native_balance']['amount']), } def get_price(self): return float(self.client.get_spot_price()['amount']) def buy(self, amount): buy_obj = self.account.buy(amount, 'USD') self.buys.append(buy_obj) def sell(self, amount): sell_obj = self.account.sell(amount, 'USD') self.sells.append(sell_obj) def analyze(self): for idx, buy in enumerate(self.buys): if self.get_price() > buy['price'] + market_fees + min_profit_margin: self.buys.pop(idx) self.sell(buy['amount']) # if price rises above buy price + market fees by a certain amount, sell early and reap the tiny profits elif self.get_price() < buy['price']: self.buys.pop(idx) self.sell(buy['amount']) # if price drops below the price it was bought at, sell immediately to minimize losses else: pass # do nothing until the price fluctuates enough to make more of a difference for idx, sell in enumerate(self.sells): if self.get_price() > sell['price']: self.sells.pop(idx) self.buy(sell['amount']) # if price starts to rise above the amount we sold it for, rebuy the same amount else: # if market trends downwards we'll lose (number of transactions * (market fee per transaction + min profit margin)) pass # price is below the amount we sold for, don't do anything until it's passing break-even again def run(self): self.keep_running = True while self.keep_running: self.analyze()
def get_coinbase(key, secret): """Get balance from coinbase exchange API.""" client = Client(key, secret) accounts = client.get_accounts() df = pd.DataFrame([row.balance for row in accounts.data]) df['source'] = 'coinbase' df.columns = ['balance', 'coin', 'source'] data.append(df)
def set_coinbase_currencies(self): API_KEY = self.coinbase_api_key API_SECRET = self.coinbase_api_secret client = Client(API_KEY, API_SECRET) accounts = client.get_accounts() for currency in accounts["data"]: if float(currency["balance"]["amount"]) > 0: self.coinbase_currencies.append( currency["balance"]["currency"]) self.num_coinbase_currencies += 1
def get(self, request): api_key = "GUODYAv11MXO2HFm" api_secret = "iV0vbIyIJUspnRsjg1aYLIanzHfdoaG8" from coinbase.wallet.client import Client client = Client(api_key, api_secret) accounts = client.get_accounts() assert isinstance(accounts.data, list) assert accounts[0] is accounts.data[0] assert len(accounts[::]) == len(accounts.data) wallet_id = accounts.data[11]['id'] transactions = client.get_transactions(wallet_id) return HttpResponse(json.dumps(client.get_transactions(wallet_id)), content_type='application/json')
def getTransactionsInAllAccounts(api_key, api_secret): client = Client( api_key=api_key, api_secret=api_secret, api_version='2017-12-07') accounts = client.get_accounts() transactions = [] for account in accounts.data: transactions.append(account.get_transactions()) return transactions
def coinbaseBalance(cbKey, cbSecret): '''usage from coinbase.wallet.client import Client coinbaseBalance(KEY, SECRET) it returns balance in wallet currency as float''' api_key = cbKey api_secret = cbSecret client = Client(api_key, api_secret) accInfo = client.get_accounts() balance = accInfo['data'][0]['native_balance']['amount'] ts = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') coinBalance = ['coinbase', 'income', float(balance), ts] coinBalance = [str(ele) for ele in coinBalance] return ','.join(coinBalance)
def main(): current_datetime = datetime.datetime.now() print "[+] Current Datetime: %s" %(current_datetime) client = Client(creds.api_key, creds.api_secret) data = client.get_accounts() total_euro_value = 0.00 for x in range(0,4): currency_type = data[x]["balance"]["currency"] currency_amount = data[x]["balance"]["amount"] euros_amount = data[x]["native_balance"]["amount"] print "[+] You have %s %s valued at %s euros" %(currency_amount, currency_type, euros_amount) total_euro_value = total_euro_value + float(euros_amount) print "[+] Total euro worth is: %f " %(float(total_euro_value)) logger(current_datetime, total_euro_value)
def CoinBasePull(BankInfo): from coinbase.wallet.client import Client client = Client(BankInfo["APIKey"], BankInfo["APISecret"]) accounts = client.get_accounts() for account in accounts.data: balance = account.balance print("%s: %s %s" % (account.name, balance.amount, balance.currency)) print(account.get_transactions()) PData = { "cash": balance, }
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))
class CoinbaseData(object): """Get the latest data and update the states.""" def __init__(self, api_key, api_secret): """Init the coinbase data object.""" from coinbase.wallet.client import Client self.client = Client(api_key, api_secret) self.update() @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from coinbase.""" from coinbase.wallet.error import AuthenticationError try: self.accounts = self.client.get_accounts() self.exchange_rates = self.client.get_exchange_rates() except AuthenticationError as coinbase_error: _LOGGER.error("Authentication error connecting" " to coinbase: %s", coinbase_error)
class CoinbaseAccount(): client = None accounts = None def __init__(self, key_directory, perms=None): api_key_file = key_directory + 'api_key' api_secret_file = key_directory + 'api_secret_key' try: try: api_key_fp = open(api_key_file, 'r') api_key = api_key_fp.readline() if (api_key == ''): raise ValueError ('Error: API Key File: ' + api_key_file + ' is empty.') api_key_fp.close() except: raise ValueError('Error opening the API Key File: ' + api_key_file) try: api_secret_fp = open(api_secret_file, 'r') api_secret = api_secret_fp.readline() if (api_secret == ''): raise ValueError ('Error: Secret Key File: ' + api_secret_file + ' is empty.') api_secret_fp.close() except: raise ValueError('Error opening the API Key File: ' + api_secret_file) except ValueError as err: print(err.args) quit() # end program on bad key reads self.client = Client(api_key, api_secret) self.accounts = self.client.get_accounts() try: assert (self.accounts.warnings is None) or isinstance(self.accounts.warnings, list) except AssertionError as err: print(err.args) quit() def get_current_price(self, symbol): table = self.client.get_exchange_rates() return 1.0 / table["rates"][symbol] def get_exchange_cur(self): table = self.client.get_exchange_rates() return table["rates"]
class CoinbaseClient(): def __init__(self, filename='etc/.api'): try: with open(filename, 'r') as infile: lines = [line for line in infile] key = str(lines[0]).strip() secret = str(lines[1]).strip() except FileNotFoundError: print('Please create a file with coinbase api information at {}'. format(filename)) key = None secret = None self.client = Client(key, secret, api_version='2017-10-09') self.accountDict = dict() self.update() def update(self): accounts = self.client.get_accounts() for account in accounts.data: self.accountDict[account.name] = account def last(self, pair): return float(self.client.get_spot_price(currency_pair=pair)['amount']) def get_sell_price(self, pair): return float(self.client.get_sell_price(currency_pair=pair)['amount']) def get_buy_price(self, pair): return float(self.client.get_pair_price(currency_pair=pair)['amount']) def sell(self, currency, amount): wallet = '{} Wallet'.format(currency) sell = self.client.sell(self.accountDict[wallet].id, amount=self.accountDict[wallet].balance.amount, currency=currency) return sell def buy(self, currency, amount): wallet = '{} Wallet'.format(currency) buy = self.client.buy(self.accountDict[wallet].id, amount=str(amount), currency=currency)
def get_current_gains(user): api_key, api_secret = os.environ.get( f'API_KEY_{user.upper()}'), os.environ.get( f'API_SECRET_{user.upper()}') client = Client(api_key, api_secret) nat_curr = os.environ.get('NAT_CURRENCY', 'EUR') accounts = client.get_accounts() gains = [] for acc in accounts.data: # Getting general info id, curr, name = acc.id, acc.balance.currency, acc.name # Getting coin balance coin_balance = float(acc.balance.amount) # Getting market price if curr == 'EUR' or coin_balance == 0.0: continue sell_price = float( client._make_api_object( client._get('v2', 'prices', f'{curr.upper()}-{nat_curr}', 'sell'), APIObject).amount) buy_price = float( client._make_api_object( client._get('v2', 'prices', f'{curr.upper()}-{nat_curr}', 'buy'), APIObject).amount) # Getting fiat payments and balance fiat_balance = coin_balance * sell_price * (1 - SELL_FEE) fiat_buys = sum([ float(b['total']['amount']) for b in client.get_buys(id).data if b['status'] == 'completed' ]) gains.append({ 'currency': curr, 'name': name, 'fiat_buys': fiat_buys, 'fiat_balance': fiat_balance, 'coin_balance': coin_balance, 'buy_price': buy_price, 'sell_price': sell_price, }) return gains
class CoinbaseData: """Get the latest data and update the states.""" def __init__(self, api_key, api_secret): """Init the coinbase data object.""" from coinbase.wallet.client import Client self.client = Client(api_key, api_secret) self.update() @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from coinbase.""" from coinbase.wallet.error import AuthenticationError try: self.accounts = self.client.get_accounts() self.exchange_rates = self.client.get_exchange_rates() except AuthenticationError as coinbase_error: _LOGGER.error("Authentication error connecting" " to coinbase: %s", coinbase_error)
def get_account_assets(): client = Client(os.environ["coinbase_key"], os.environ["coinbase_secret"]) accounts = client.get_accounts() assets = [] for balance in accounts["data"]: symbol = balance["currency"] amount = float(balance["balance"]["amount"]) exchange = "coinbase" asset = Asset(symbol=symbol, amount=amount, exchange=exchange) if int(amount * 1e18) > 0: assets.append(asset) return assets
class CoinBase(ExchangeInterface): def __init__(self): self._client = Client(os.getenv('coinbase_api_key'), os.getenv('coinbase_api_secret')) def get_coins(self): accounts = self._client.get_accounts() assert isinstance(accounts.data, list) assert accounts[0] is accounts.data[0] assert len(accounts[::]) == len(accounts.data) for account in accounts.get('data'): if float(account['balance']['amount']) != 0.0: coin = {} coin.update({'name': account['currency']}) coin.update({'type': account['currency']}) coin.update({ 'amount': format(float(account['balance']['amount']), '.8f') }) yield coin
class Coinbase: def __init__(self, key, secret): self.client = Client(key, secret) self.logger = Logger(__name__) def getBalances(self): try: result = self.client.get_accounts() balances = {} for currency in result["data"]: name = currency["balance"]["currency"].encode('utf-8').upper() value = float(currency["balance"]["amount"].encode('utf-8')) if value > 0.0: balances[name] = value return balances except Exception as e: self.logger.log(e) raise ExchangeException(self.__class__.__name__, e.message)
class CoinbaseClient(CryptoClient): def __init__(self, key, secret): self.client = Client(key, secret) self.accounts = self.client.get_accounts()["data"] for account in self.accounts: if account["balance"]["currency"] == PRIMARY_ACCOUNT_CURRENCY: self.account = account break def get_product_values(self): values = {} for account in self.accounts: currency = account["balance"]["currency"] values[currency] = float(account["native_balance"]["amount"]) return values def get_current_value(self): values = {} for account in self.accounts: currency = account["balance"]["currency"] values[currency] = float(account["native_balance"]["amount"]) return sum(v for k, v in values.items()) def get_account_total(self, account): transactions = account.get_transactions()["data"] total = 0 for transaction in transactions: transaction_type = transaction["type"] if transaction_type in ["exchange_deposit", "exchange_withdrawl"]: continue total += float(transaction["native_amount"]["amount"]) return total def get_amount_invested(self): return sum( self.get_account_total(account) for account in self.accounts)
from coinbase.wallet.client import Client api_key = 'of71uB7fEysCzQMp' api_secret = 'k2cvJr3UuUhXc2pKPE2I6IV5cxQ7wVV0' SANDBOX_URL = 'https://api.sandbox.coinbase.com' import pdb; pdb.set_trace() client = Client( api_key, api_secret, base_api_uri=SANDBOX_URL) accounts = client.get_accounts() print('accounts:', accounts) for account in accounts.data: balance = account.balance print("%s: %s %s" % (account.name, balance.amount, balance.currency)) print(account.get_transactions()) account = client.create_account(name="New Wallet") balance = account.balance print("%s: %s %s" % (account.name, balance.amount, balance.currency)) primary_account = client.get_primary_account() address = account.create_address() primary_account.send_money( to=address.address,
#General libs import json, hmac, hashlib, time, requests from requests.auth import AuthBase #Coinbase libs from coinbase.wallet.client import Client #Whale extras import whaleCREDS user = Client(whaleCREDS.API_KEY, whaleCREDS.API_SECRET, base_api_uri=whaleCREDS.API_URL) print(user) accounts = user.get_accounts() for account in accounts.data: balance = account.balance print ("%s: %s %s" % (account.name, balance.amount, balance.currency)) # print(type(json.loads(str(account.get_transactions())))) for transaction in json.loads(str(account.get_transactions()))["data"]: # print ("TRANSACT: %s %s - %s" % (transaction.amount.amount, transaction.amount.currency, transaction.description)) print(transaction["type"]+" "+transaction["amount"]["amount"]+" "+transaction["amount"]["currency"]+" ("+transaction["status"]+", "+transaction["network"]["status"]+")") print(" Description: "+str(transaction["description"])) print("\n")
def generate_bitcoin_address(): client = Client(API_KEY, API_SECRET) accounts = client.get_accounts() r = client.create_address(accounts["data"][0]["id"]) return r["address"]