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 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)
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"]
def collect_coinbase(): # ------------------------------ # collect data from Coinbase API # ------------------------------ # Before implementation, set environmental variables with the names API_KEY_COINBASE and API_SECRET_COINBASE # API_KEY_COINBASE = '7wFz0CndMuduPhaO' # API_SECRET_COINBASE = 'SwN2NPlrak3t6gVrNpQmxphTSC40lRNH' client = Client(API_KEY_COINBASE, API_SECRET_COINBASE) #api_version='YYYY-MM-DD' currency_code = 'USD' # can also use EUR, CAD, etc. # currency=currency_code # Make the request price = client.get_spot_price(currency=currency_code, date='2017-04-11') currencies = client.get_currencies() rates = client.get_exchange_rates(currency='BTC') time = client.get_time() # print ('Current bitcoin price in %s: %s %s' % (currencies, price,rates)) def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) start_date = date(2013, 1, 1) end_date = date(2018, 1, 13) coinbase_d_cur_his = [] for single_date in daterange(start_date, end_date): pre_date = single_date.strftime("%Y-%m-%d") pre_price = client.get_spot_price(currency=currency_code, date=pre_date) # sell_price = client.get_sell_price(currency=currency_code, date=pre_date) # buy_price = client.get_buy_price(currency=currency_code, date=pre_date) print([ pre_date, pre_price['base'], pre_price['currency'], pre_price['amount'], single_date.day, single_date.month, single_date.year ]) # print(pre_price['amount'], sell_price['amount'], buy_price['amount']) coinbase_d_cur_his.append([ pre_date, pre_price['base'], pre_price['currency'], pre_price['amount'], single_date.day, single_date.month, single_date.year ])
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 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 Send2Address(exchange, wallet, amount, address): print "SENDING %s %s FROM %s TO %s" % (amount, wallet["Symbol"], exchange, address) if exchange.upper() == "CB" or exchange.upper() == "COINBASE": print "Account ID:", wallet["AccountId"] print "Address:", address print "Amount:", amount print "Currency:", wallet["Symbol"] print "idem:", time.time() client = CB_Client(CB_API_KEY, CB_API_SECRET, api_version="2017-05-19") exchange_rates = client.get_exchange_rates() if wallet["Symbol"] == "BCH": fee = 0.0043 * float(exchange_rates["rates"]["BCH"]) if wallet["Symbol"] == "BTC": fee = 5.2975 * float(exchange_rates["rates"]["BTC"]) if wallet["Symbol"] == "ETH": fee = 1.05 * float(exchange_rates["rates"]["ETH"]) if wallet["Symbol"] == "LTC": fee = 0.042 * float(exchange_rates["rates"]["LTC"]) print str(float(amount) - fee) tx = client.send_money(wallet["AccountId"], amount=str(float(amount) - fee), currency=wallet["Symbol"], to=address, type="send") print tx if exchange.upper() == "NZ" or exchange.upper() == "CRYPTOPIA": tx = json.loads( Cryptopia_API_Query("SubmitWithdraw", { "Address": address, "Amount": amount, "Currency": wallet["Symbol"] })) print tx if exchange.upper() == "KC" or exchange.upper() == "KUCOIN": client = KC_Client(KC_API_KEY, KC_API_SECRET) client.create_withdrawal(wallet["Symbol"], amount, address)
def calculate_premium(self): # get coinbase price coinbase_monitor = Client(api_key='admin', api_secret='admin') coinbase_price = float(coinbase_monitor.get_buy_price()['amount']) print('BTC price in Coinbase: %.2f USD' % coinbase_price) # get huobi price huobi_monitor = huobi_main_monitor.Huobi_Main_Monitor() huobi_price = float(huobi_monitor.get_btccny_bid_price()) print('BTC price in Huobi: %.2f CNY' % huobi_price) # get exchange rate exchange_rate = float( coinbase_monitor.get_exchange_rates()['rates']['CNY']) print('Exchange rate is now: %.2f CNY/USD' % exchange_rate) # cal premium (huobi -> coinbase) premium = huobi_price / exchange_rate - coinbase_price premium_rate = premium / coinbase_price print('Premium: %.2f USD\nPremium Rate: %.1f %%' % (premium, premium_rate * 100)) return premium_rate
def get_dollar_value(eth_balance, btc_balance): cl = Client(settings.API_KEY, settings.API_SECRET) currencies = cl.get_exchange_rates(currency='USD') #btc_rate=int(currencies['BTC']) #eth_rate=int(currencies['ETH']) pdb.set_trace()
api_secret = 'REPLACE' currency_code = 'USD' color_red = '\033[1;31;40m' color_green = '\033[1;32;40m' color_yellow = '\033[1;33;40m' color_dark_gray = '\033[1;30;40m' color_purple = '\033[1;35;40m' color_blue = '\033[1;34;40m' color_cyan = '\033[1;36;40m' # don't change below that line # ---------------------------------------------------------- from coinbase.wallet.client import Client client = Client(api_key, api_secret) client.get_exchange_rates() # clear LCD from os import system system('clear') import datetime d = datetime.datetime.today() dateTimeNow = d.strftime("%d-%B-%Y %H:%M:%S") print '%s %s' % (color_red, '{}'.format(dateTimeNow)) bitcoinPrice = client.get_spot_price(currency=currency_code) print '%s BTC %s %s' % (color_green, currency_code, bitcoinPrice.amount) ethereumPrice = client.get_spot_price(currency_pair='ETH-USD') print '%s ETH %s %s' % (color_dark_gray, currency_code, ethereumPrice.amount)
def test_get_exchange_rates(self): client = Client(api_key, api_secret) exchange_rates = client.get_exchange_rates() self.assertIsInstance(exchange_rates, APIObject) self.assertEqual(exchange_rates.data, mock_collection)
from coinbase.wallet.client import Client import time from elasticsearch import Elasticsearch from datetime import datetime # GitPython # python-dateutil # https://elasticsearch-py.readthedocs.io/en/master/ # https://docs.objectrocket.com/elastic_python_examples.html INDEX = 'coinbase' DOC_TYPE = 'rates' client = Client("zhtXa1PEK0J6tzZ2", "pS9sqBNMAWVLfJWGXk36wLuCb1OMQnIF") rates = client.get_exchange_rates(currency='BTC') rates['time'] = time.time() print(rates) es = Elasticsearch( ['192.168.1.7'], scheme="http", port=9200 ) res = es.index(index=INDEX, doc_type=DOC_TYPE, body=rates) print(res)
def test_get_exchange_rates(self): client = Client(api_key, api_secret) exchange_rates = client.get_exchange_rates() self.assertIsInstance(exchange_rates, APIObject) self.assertEqual(exchange_rates.data, mock_collection)
- Reference: https://github.com/coinbase/coinbase-python # Signup Coinbase account to get API key & Secret-> https://www.coinbase.com/ - Install Coinbase Python Module in CMD or Terminal. >>> pip install coinbase --upgrade ''' from coinbase.wallet.client import Client print("\n *** CoinBase Using Python *** \n") api_key = input(' Enter API Key : ') api_secret = input(' Enter API Secret : ') client = Client(api_key, api_secret) print('\n Current User information : {}'.format(client.get_current_user())) print('\n Coinbase Accounts Information : {}'.format(client.get_accounts())) print('\n Coinbase Primary Account Information : {}'.format(client.get_primary_account())) print('\n Get supported native currencies : {}'.format(client.get_currencies())) print('\n Get exchange rates : {}'.format(client.get_exchange_rates())) print('\n Buy Prices : {}'.format(client.get_buy_price(currency_pair = 'BTC-USD'))) print('\n Sell Price : {}'.format(client.get_sell_price(currency_pair = 'BTC-USD'))) print('\n Spot Price : {}'.format(client.get_spot_price(currency_pair = 'BTC-USD'))) print('\n Current Server Time : {}'.format(client.get_time())) print('\n Get Authorization Information: {}'.format(client.get_auth_info())) print('\n Get Transaction : {}'.format(account.get_transactions())) print('\n Get Reports : {}'.format(client.get_reports())) print('\n Get Buys : {}'.format(account.get_buys())) print('\n Get Sells : {}'.format(account.get_sells())) print('\n Get Sells: {}'.format(account.get_deposits())) print('\n Get Withdrawls : {}'.format(account.get_withdrawals())) print('\n Get Orders : {}'.format(client.get_orders())) print('\n Get Checkouts : {}'.format(client.get_checkouts()))
class Client: def __init__(self): self.coinbase_client = CoinbaseClient( 'kjbqArvnGOKiVsCL', '1EtHiISTUavVa5CxqUpKIxi2bmEddW2N') self.currency_code = 'USD' # can also use EUR, CAD, etc. self.sp_api_client = SpreadsheetsApi() self.auth_api_client = AuthenticationApi() self._set_token() self.wb = '067474f68bcc4fada0da5b85fe9b6b62' self.tb = 'a47eddaf73b64709a2db2d893e3dfddd' def _set_token(self): Configuration().access_token = self.auth_api_client.oauth2_token_post( client_id='04fffc2536fa4978808ac680dbbecacc', x_api_key='', client_secret='4e8ecf9b8d20504352b7539dc0a664095ed52a80ff8517a0', grant_type='client_credentials').access_token # Renew token every minute t = threading.Timer(60.0, self._set_token) t.daemon = True t.start() def set_price_in_sheet(self): # Make the request btc_price = self.coinbase_client.get_spot_price( currency_pair='BTC-USD') self.coinbase_client.get_historic_prices() resp = requests.get( url='https://api.coinbase.com/v2/prices/ETH-USD/spot', headers={ 'Authorization': 'Bearer ' + Configuration().access_token }) eth = json.loads(resp.text) eth_price = eth['data']['amount'] # Update the Spreadsheet resp = self.sp_api_client.spreadsheets_spreadsheet_id_sheets_sheet_id_data_put( '067474f68bcc4fada0da5b85fe9b6b62', 'a47eddaf73b64709a2db2d893e3dfddd', { "values": [["Bitcoin price (in dollars)", btc_price.amount], ["ETH price (in dollars)", eth_price]] }, 'fakekey', region='A1:B2', ) def set_exchange_rates_in_sheet(self): while True: raw_input("Press 'Enter' to refresh exchange rates") rates = self.coinbase_client.get_exchange_rates(currency="BTC") values = [["BTC Exchange Rates", ""]] for k, v in rates["rates"].iteritems(): values.append([k, v]) # Update the Spreadsheet resp = self.sp_api_client.spreadsheets_spreadsheet_id_sheets_sheet_id_data_put( '067474f68bcc4fada0da5b85fe9b6b62', 'a47eddaf73b64709a2db2d893e3dfddd', {"values": values}, 'fakekey', region='A4:B', )