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 CoinbaseHelper(): def __init__(self, api_key, api_secret): self.client = Client(api_key, api_secret) def get_price(self, seconds): price = self.client.get_spot_price(currency_pair='ETH-USD') dollar_per_second = 0.00025 ether_per_dollar = 1 / float(price['amount']) ether_price_per_second = ether_per_dollar * dollar_per_second final_price = ether_price_per_second * seconds if final_price < 0.000001: print("SENDING 0.000001") return 0.000001 print(f"SENDING {final_price}") return final_price def send_ether(self, email, seconds): account = self.client.get_account("ETH") amount_to_send = self.get_price(seconds) tx = account.send_money(to=email, amount=amount_to_send, currency='ETH') print(tx)
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)
class CoinbaseManager(object): """Manager for the coinbase API""" def __init__(self): super(CoinbaseManager, self).__init__() self.api_key = os.environ.get('COINBASE_API_KEY') self.api_secret = os.environ.get('COINBASE_API_SECRET') self.client = Client(self.api_key, self.api_secret) def get_curreny_pair(self, crypto_currency, exchange_currency): """Return the currency pair to get the price from API""" currency_pair = '%s-%s' % (crypto_currency, exchange_currency) return currency_pair def get_spot_price(self, crypto_currency, exchange_currency): """Get the spot price from API""" currency_pair = self.get_curreny_pair(crypto_currency, exchange_currency) price = self.client.get_spot_price(currency_pair=currency_pair) return price.amount def get_buy_price(self, crypto_currency, exchange_currency): """Get the buy price from API""" currency_pair = self.get_curreny_pair(crypto_currency, exchange_currency) price = self.client.get_buy_price(currency_pair=currency_pair) return price.amount def get_sell_price(self, crypto_currency, exchange_currency): """Get the sell price from API""" currency_pair = self.get_curreny_pair(crypto_currency, exchange_currency) price = self.client.get_sell_price(currency_pair=currency_pair) return price.amount
def actual(self): client = Client('https://api.coinbase.com/v2/currencies', '0') Result0 = client.get_buy_price() Result1 = client.get_sell_price() Result2 = client.get_spot_price() self._compra.setText(Result0.get('amount')) self._venta.setText(Result1.get('amount')) self._spot.setText(Result2.get('amount'))
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()
class SpotPriceRetriever(): def __init__(self): config_reader = ConfigReader() key = config_reader.value(ConfigTypes.Coinbase, 'api_key') secret = config_reader.value(ConfigTypes.Coinbase, 'api_secret') self.client = Client(key, secret) def get_price(self): try: spot_price = self.client.get_spot_price(current_pair='BTC-USD') except requests.HttpError as exception: print(exception) return round(float(spot_price['amount']), 8)
def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) client = Client("YOUR_INFO", "YOUR_INFO", api_version="2018-09-15") currency_code = "USD" item_price = client.get_spot_price(currency=currency_code) print("Last price was {}".format(item_price.amount)) context["price"] = item_price.amount # URL sandbox content url = "https://api-public.sandbox.pro.coinbase.com/products/BTC-USD/candles?granularity=300" r = requests.get(url) context["json_stuff"] = r.json() return context
def handle(self, *args, **options): api_client = Client(api_key=COINBASE_CONFIG['API_KEY'], api_secret=COINBASE_CONFIG['API_SECRET'], api_version=COINBASE_CONFIG['API_VERSION']) rate = api_client.get_spot_price( currency_pair=('%s-%s' % (self.base_currency, self.currencuy))) if rate.base == self.base_currency and rate.currency == self.currencuy: exchange_rate = ExchangeRate.objects.create( base_currency=ExchangeRate.C_CURRENCY_ETH, currency=ExchangeRate.CURRENCY_USD, rate=float(rate.amount)) exchange_rate.save()
def Etc(): key = "97dc0590e82deff43786f4ae989efcba" secret = "gamgVpze2B1Ea6EbhFRAdIqze5hEc3nDVUXV3WHJjRjQiMJECW5GnSklT6+ZjWI5Xsh/2GcFOh4yud86YAQc3Q==" client = Client(key, secret, api_version='YYYY-MM-DD') rates = client.get_spot_price(currency_pair='ETC-EUR') etc_name = rates['base'] etc_price = rates['amount'] pricelabel.config(bg="#44BE24") etc = float(etc_price) output = round(etc, 2) pricevar.set(output) curenttime = datetime.now().strftime("%H:%M:%S") a.set(curenttime) Prices.matplotCanvas(curenttime, output) tree.insert('', '0', text=etc_name, values=(curenttime, output))
def coinBase(): client = Client(config.coinbase_auth, config.coinbase_api, api_version='2017-12-03') currency_code = 'USD' # can also use EUR, CAD, etc. # Make the request price = client.get_spot_price(currency=currency_code) if float(price.amount) <= 10000: return ('Current bitcoin price in %s: %s - You should buy now' % (currency_code, price.amount)) else: return ('Current bitcoin price in %s: %s' % (currency_code, price.amount))
class Coinbase(): def __init__(self, config): self.client = Client(config['DEFAULT']['api_key'], config['DEFAULT']['api_secret']) self.current_btc_amount = 0 self.last_price = 0 def set_current_btc_amount(self, current_btc_amount): self.current_btc_amount = current_btc_amount def get_current_price(self, currency_code, prices): price = self.client.get_spot_price(currency=currency_code) if self.last_price != float(price.amount): self.last_price = float(price.amount) prices.add_new_price_defaulted_time(price.amount) temp_prices = prices.get_last_prices(len(prices.price_list)) return price
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_prices_from_acct_bal(acct_bal: pd.DataFrame) -> pd.Series: """ Iterate through the "Asset" column and generate simple API calls to get the spot price for each asset in USD """ # simple price checks don't require API creds client = Client( "intentionally_blank", "intentionally_blank", api_version="YYYY-MM-DD" ) price_dict = dict() for asset in acct_bal["Asset"]: pair = asset + "-USD" price_dict[asset] = client.get_spot_price(currency_pair=pair).get("amount") current_prices = pd.Series(price_dict, name="current_price_per_coin").astype(float) return current_prices
class Coinbase(): def __init__(self): self.client = Client(os.environ['COINBASE_API_KEY'], os.environ['COINBASE_API_SECRET'], api_version='2020-12-08') self.payment_methods = self.client.get_payment_methods() self.account = self.client.get_primary_account() self.payment_method = self.client.get_payment_methods()[0] def get_price(self, date, currency): return self.client.get_spot_price(currency_pair=f'{currency}-EUR', date=date) def get_portfolio(self): pass def buy(self, amount): pass def sell(self, amount): pass
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) ethereumPrice = client.get_spot_price(currency_pair='XTZ-USD') print '%s XTZ %s %s' % (color_purple, currency_code, ethereumPrice.amount)
class Command(BaseCommand): comparison_currency = 'USD' coin_list_url = 'https://api.coinbase.com/v2/currencies' api_version = '2018-02-14' xchange = Xchange.objects.get(pk=XCHANGE['COINBASE']) def handle(self, *args, **options): # instance variable unique to each instance try: self.client = Client(self.xchange.api_key, self.xchange.api_secret, api_version='2018-01-14') except ObjectDoesNotExist as error: logging.debug('Client does not exist:{0}'.format(error)) xchange_coins = self.client.get_currencies() for xchange_coin in xchange_coins['data']: if xchange_coin is None: continue coins = Coins.Coins(xchange_coin['id']) try: currency = Currency.objects.get(symbol=xchange_coin['id']) logger.info("{0} exists".format(xchange_coin['id'])) except ObjectDoesNotExist as error: logger.info( "{0} does not exist in our currency list..Adding".format( xchange_coin['id'], error)) coins.createClass() now = datetime.now() start_date = now.replace(second=0, minute=0, hour=0) end_date = start_date - timedelta(days=10) while end_date < start_date: start_date_ts = calendar.timegm(start_date.timetuple()) prices = self.getPrice(xchange_coin['id'], date=start_date.strftime('%Y-%m-%d')) if len(prices) != 0: if prices is None: break coin = coins.getRecord(time=start_date_ts, xchange=self.xchange) coin.time = int(calendar.timegm(start_date.timetuple())) coin.close = float(prices['amount']) coin.xchange = self.xchange coin.currency = currency coin.save() start_date = start_date - timedelta(days=1) def getCoins(self): headers = { 'content-type': 'application/json', 'user-agent': 'your-own-user-agent/0.0.1' } params = {} currencies = requests.get(self.coin_list_url, params=params, headers=headers) return currencies.text def getPrice(self, currency_symbol, date): try: res = self.client.get_spot_price(currency_pair=currency_symbol + '-USD', date=date) except Exception as error: logger.error('{0}'.format(error)) res = {} return res
#-*-coding:utf-8-*- ''' @author:HANDSOME_JERRY @time:'18-8-2上午10:38' ''' import json import requests, time import urllib import pandas as pd dates = pd.date_range('2018-06-30', '2018-08-01', freq='D') dates = dates.values from coinbase.wallet.client import Client client = Client('M0110UJ8G2pteyAW', ' wi5cAfH41hG06sVyiYmZ5TQ3EpCKAxN0') import re symbol = 'BTC-USD' for i in dates: i = i.tolist() date = re.findall('\d{10}', str(i))[0] date = time.localtime(int(date)) date = time.strftime('%Y-%m-%d', date) q = client.get_spot_price(date=date, currency_pair=symbol) print("%s Done %s %s" % (date, symbol, q)) #https://api-public.sandbox.pro.coinbase.com//products/BTC-USD/candles
parser = argparse.ArgumentParser() parser.add_argument( "budget_file", help='JSON file in the form [{"name":"Budget Item 1", "amount_usd":5.50}]') parser.add_argument("bitcoin_paid_price", help='The price you paid for the coins') parser.add_argument("coinbase_api_key", help='Get this from coinbase.com') parser.add_argument("coinbase_api_secret", help='Get this from coinbase.com') args = parser.parse_args() with open(args.budget_file) as data_file: budget_accounts = json.load(data_file) client = Client(args.coinbase_api_key, args.coinbase_api_secret) primary_account = client.get_primary_account() bitcoin_spot_price_in_usd = client.get_spot_price( currency_pair='BTC-USD')["amount"] bitcoin_paid_price_in_usd = args.bitcoin_paid_price accounts_obj = client.get_accounts(limit="100") assert (accounts_obj.pagination is None) or isinstance(accounts_obj.pagination, dict) accounts = accounts_obj[::] total_usd = 0 for budget_account in budget_accounts: total_usd += budget_account["amount_usd"] total_btc = 0 for budget_account in budget_accounts: budget_account_name = budget_account["name"] budget_account_id = find_account(accounts, budget_account_name).id budget_account_amount_usd = budget_account["amount_usd"]
# Helper method for getting the price difference change ratio def get_price_difference(prev, curr): return curr / prev - 1 if __name__ == "__main__": print "=*====================CryptoG====================*=" print "CryptoG is up and running." print "You'll get an update every " + str( update_period) + " seconds if the price of BTC changes by " + str( change_threshold * 100) + " percent." print "=*===============================================*=" last_btc_price = float( coinbase_client.get_spot_price(currency_pair='BTC-USD').amount) # Update loop while True: curr_btc_price = float( coinbase_client.get_spot_price(currency_pair='BTC-USD').amount) diff = get_price_difference(last_btc_price, curr_btc_price) if diff > change_threshold: trend = 'DOWN' if curr_btc_price > last_btc_price: trend = 'UP' # Send a message if the difference is above our change threshold msg_body = 'BTC has gone ' + trend + ' by ' + str(
def test_get_spot_price(self): client = Client(api_key, api_secret) spot_price = client.get_spot_price() self.assertIsInstance(spot_price, APIObject) self.assertEqual(spot_price, mock_item)
class Coinbase: def __init__(self, config): # TODO command-line parameters? # https://docs.python.org/3/library/argparse.html account = input("Account: ") if account == "Kevin" or "kevin" or "k": api_key = config["coinbase_api_kevin"]["key"] api_secret = config["coinbase_api_kevin"]["secret"] elif account == "Liang" or "liang" or "l": api_key = config["coinbase_api_liang"]["key"] api_secret = config["coinbase_api_liang"]["secret"] else: print("Account not found. Please add API keys to config.json") exit(1) self.client = Client(api_key, api_secret) # Initialize all calculated numbers self.accumulated_profit_btc = 0 self.accumulated_profit_eth = 0 self.total_btc_paid_fees = 0 self.total_eth_paid_fees = 0 self.total_btc_received = 0 self.total_eth_received = 0 def set_eth_price(self, price): self.current_eth_price = price # TODO automatically update ETH price def get_exchange_rate(self, coin="BTC", currency="USD"): """ Get BTC - USD exchange rate Bug for ETH-USD: https://community.coinbase.com/t/python-3-5-get-spot-price-for-eth-eur-returns-btc-usd/14273/9 Modify source library code: https://stackoverflow.com/a/23075617/3751589 """ param = "{}-{}".format(coin, currency) return self.client.get_spot_price(currency_pair=param) def calculate_profit_loss(self): self.current_btc_price = float( self.get_exchange_rate("BTC", "USD").amount) # self.current_eth_price = float(self.get_exchange_rate("ETH", "USD").amount) # Ask user for balance outside of Coinbase BTC_external_balance = float(input('BTC external balance: ')) ETH_external_balance = float(input('ETH external balance: ')) # # Print transactions? # print_transactions = input("Print transactions? ") # if print_transactions == "Y" or "y" or "yes" or "Yes" or "si" or "si patron": # # do everything inside for then print the following # print("\tBuy transaction: -{}".format(amount_paid_fees)) # print("\t{} transaction: {}".format(transaction.type.title(), amount_received)) # elif print_transactions == "N" or "n" or "no" or "No" or "fk off boi": # # do everything inside for loop # else: # print("Answer the question dumbass. Yes or No") # Get all accounts listing accounts = self._get_accounts() print("Accounts retrieved: {}\n".format(len(accounts.data))) # Read each account for account in accounts.data: currency = account.balance.currency if currency in ( "USD", "LTC" ) or account.name == "My Vault": # Ignore these accounts # TODO add USD wallet continue print(currency) print("Calculating currency: {}".format(currency)) print("{}: {} {}".format(account.name, account.balance.amount, currency)) # Get all transactions transactions = account.get_transactions( start_after="1805ae5b-f65b-5825-b780-9c6cecdec1cf", limit=100) """ Documentation for argument syntax in get_transactions https://github.com/coinbase/coinbase-python/blob/f9ed2249865c2012e3b86106dad5f8c6068366ed/coinbase/wallet/model.py#L168 """ # TODO regex or some way to find everyones start_after # https://stackoverflow.com/questions/44351034/pagination-on-coinbase-python-api for transaction in transactions.data: if transaction.status != "completed": print("\tIncomplete transaction...") continue # Calculate for each transaction type # Calculate all BUYS if transaction.type == "buy": transaction_id = transaction.buy.id transaction_detail = self._get_buy_transaction( account.id, transaction_id) # Calculate price point during purchase amount_paid = float(transaction_detail.subtotal.amount ) # USD paid before fees coins_bought = float( transaction_detail.amount.amount ) # Total coins received from purchase purchase_price = amount_paid / coins_bought # Price of BTC/ETH at time of buying amount_paid_fees = float( transaction.native_amount.amount ) # USD paid after fees (total paid) # Calculate profit-loss if currency == "BTC": self.accumulated_profit_btc -= amount_paid_fees self.total_btc_paid_fees += amount_paid_fees #TODO prompt user if they want to print all transactions #print("\tBuy transaction: -{}".format(amount_paid_fees)) elif currency == "ETH": self.accumulated_profit_eth -= amount_paid_fees self.total_eth_paid_fees += amount_paid_fees #TODO prompt user if they want to print all transactions #print("\tBuy transaction: -{}".format(amount_paid_fees) # Calculate all SELLS elif transaction.type in ("sell"): # Amount received after fees amount_received = float(transaction.native_amount.amount) amount_received = amount_received * -1 # Accumulate profit-loss if currency == "BTC": self.accumulated_profit_btc += amount_received self.total_btc_received += amount_received elif currency == "ETH": self.accumulated_profit_eth += amount_received self.total_eth_received += amount_received #TODO prompt user if they want to print all transactions #print("\t{} transaction: {}".format(transaction.type.title(), amount_received)) # Add current Coinbase balance + current external balance to profit/Loss if currency == "BTC": # BTC_external_value = BTC_external_balance * self.btc_current_price account.balance.amount = float(account.balance.amount) self.accumulated_profit_btc += ( BTC_external_balance + account.balance.amount) * self.current_btc_price self.percent_profit_btc = self.accumulated_profit_btc / self.total_btc_paid_fees self.total_btc_balance = ( BTC_external_balance + account.balance.amount) * self.current_btc_price elif currency == "ETH": # ETH_external_value = ETH_external_balance * self.eth_current_price account.balance.amount = float(account.balance.amount) self.accumulated_profit_eth += ( ETH_external_balance + account.balance.amount) * self.current_eth_price self.percent_profit_eth = self.accumulated_profit_eth / self.total_eth_paid_fees self.total_eth_balance = ( ETH_external_balance + account.balance.amount) * self.current_eth_price # Print accumulated profit/loss if currency == "BTC": print("\nProfit/Loss ({}): ${:.2f} or {:.2f}%".format( currency, self.accumulated_profit_btc, (self.percent_profit_btc * 100))) elif currency == "ETH": print("\nProfit/Loss ({}): ${:.2f} or {:.2f}%\n".format( currency, self.accumulated_profit_eth, (self.percent_profit_eth * 100))) # Print balance start --> balance now self.total_accumulated_profit = self.accumulated_profit_btc + self.accumulated_profit_eth self.total_paid_fees = self.total_btc_paid_fees + self.total_eth_paid_fees self.total_acc_balance = self.total_btc_balance + self.total_eth_balance + self.total_eth_received + self.total_btc_received print("\nTotal USD Value (ALL): ${:.2f} --> ${:.2f}".format( self.total_paid_fees, self.total_acc_balance)) # Print total account (BTC + ETH) profit/loss self.percent_profit_total = ( self.accumulated_profit_btc + self.accumulated_profit_eth) / ( self.total_eth_paid_fees + self.total_btc_paid_fees) * 100 print("Profit/Loss (ALL): ${:.2f} or {:.2f}%\n".format( self.accumulated_profit_btc + self.accumulated_profit_eth, self.percent_profit_total)) def _get_accounts(self): return self.client.get_accounts() def _get_buy_transaction(self, account_id, transaction_id): return self.client.get_buy(account_id, transaction_id)
'dol': start_val, currency: 0, 'net': 0, 'fees': 0, 'spent': 0, 'gains': 0, 'profit': 0 } last = 0 fee_pc = 0.00 day = dt.datetime.now() prices = [] # initial purchase res = client.get_spot_price(currency_pair=currency_pair) data = json.loads(str(res)) spot_price = float(data['amount']) prices.append(spot_price) coin_num = unit * 5 order_amount = spot_price * coin_num fee = order_amount * fee_pc order_tot = order_amount + fee act['dol'] -= order_tot act[currency] += coin_num act['net'] = act['dol'] + act[currency] * spot_price act['fees'] += fee act['spent'] += order_amount file = open(log_file, "w+") file.write(
:rtype: int, int, int """ maximum = 0 buy_day = 0 sell_day = 0 for i in range(len(prices) - 1): sell_price = max(prices[i + 1:]) buy_price = min(prices[:i + 1]) profit = sell_price - buy_price transaction_cost = buy_price * .03 + sell_price * .03 if profit > transaction_cost: maximum = max(maximum, profit) return maximum, buy_day, sell_day client = Client(api_key='', api_secret='') historic_prices = client.get_historic_prices() price_list = [float(day['price']) for day in historic_prices['prices']] print(price_list) max_profit = maxProfit(price_list) print("Max profit: $" + str(max_profit)) for i in range(10): time.sleep(10) print("Buy price " + str(client.get_buy_price(currency_pair='BTC-USD'))) print("Sell price " + str(client.get_sell_price(currency_pair='BTC-USD'))) print("Spot price " + str(client.get_spot_price(currency_pair='BTC-USD')))
# Connect to Coinbase print('###################################') print(' .(-._. ~Coinbase Failsafe~ ._.-). ') print('###################################') print('') sleep(1) print('[*] Wait time is set to %s seconds.' % (time_delay)) print('[*] Acceptable relative loss from maximum is set to %s %%.' % (margin)) print('[*] The currency code chosen is %s.' % (currency_code)) print('[*] Connecting to Coinbase..') # Connects to Coinbase client = Client(api_key, api_secret, api_version=version) # Gets primary account account = client.get_primary_account() price = client.get_spot_price(currency=currency_code) print('[*] Connected. You currently have %s. Starting..' % (account.balance)) print('') # Defines starting maximum value max_price = float(price.amount) # Defines starting acceptable loss margin_value = (1 - float(margin) / 100) * max_price sleep(5) # Main code while True: try: account = client.get_primary_account() # Updates data
# Get prices every minute btc_prices = [] btc_max = 0.0 while True: # Repeat every 30 seconds (coinbase price update time) sleep(30) # Refresh holdings btc_account.refresh() # For debugging #print("btc_prices:",btc_prices) #print("btc_max:",btc_max) # Get price btc_price = float(client.get_spot_price(currency_pair='BTC-USD').amount) print("Bitcoin currently trading at ${}".format(btc_price)) btc_prices.append(btc_price) # Purge list if len(btc_prices) > BTC_BURST_MINUTES * 2: btc_prices.pop(0) # Set max price btc_new_max = max(btc_prices) if btc_new_max > btc_max: btc_max = btc_new_max print("New maximum BTC price: ${}!".format(btc_max)) # Check for bubble burst if btc_price < btc_max - BTC_BURST_AMOUNT:
em casa e por algum motivo tome erro de autenticação. ''' from coinbase.wallet.client import Client from coinbase.wallet.model import APIObject api_key = 'R6NS3FRYnJXKJmI7' api_secret = '2b4Pdpji2iYZrdBMalPEKerWKs8FCFh6' #Fazer autenticação client = Client(api_key, api_secret) #Pegar preço de mercado - Argumento date opcional #pode ser utilizada para pegar o preço em um dia específico #o argumento é no formato date = 'YYYY-MM-DD' price = client.get_spot_price(currency_pair='BTC-USD', date='2018-01-01T07:10:40') print(price) #Pegar o histórico de preços - Esta função pega o histórico de preços. #O único parâmetro dela é o period que pode ter os seguintes valores: #hour - Pega o histórico da última hora (361 pontos) #day - Pega o histórico das últimas 24h (360 pontos) #week - Pega o histórico da última semana (316 pontos) #month - Pega o histórico do último mês (360 pontos) #year - Pega o histórico do último ano (365 pontos) #all - Pegar o histórico do último ano(não entendi, mas pega mais pontos) historic = client.get_historic_prices(currency_pair='BTC-USD', period='hour') print(historic) print(len(historic["prices"]))
def test_get_spot_price(self): client = Client(api_key, api_secret) spot_price = client.get_spot_price() self.assertIsInstance(spot_price, APIObject) self.assertEqual(spot_price, mock_item)
level=logging.INFO) except Exception as e: logging.basicConfig(filename='coinb.log', format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO) logging.info('container started') # initialise coinbase client c = Client('1', '2') # mongo client mongo_host = os.environ['mongosvc'].rstrip() db_connection = MongoClient(mongo_host) db = db_connection.cryptocurrency collection = db.bitcoinprice while True: spot_price = c.get_spot_price(currency_pair='BTC-EUR') buy_price = c.get_buy_price(currency_pair='BTC-EUR') sell_price = c.get_sell_price(currency_pair='BTC-EUR') #logging.debug('BTC price at %s: %s' %(time.time(),a['amount'])) post = { 'BTC-EUR spot price': int(float(spot_price['amount'])), 'BTC-EUR buy price': int(float(buy_price['amount'])), 'BTC-EUR sell price': int(float(sell_price['amount'])), 'date': time.time() } collection.insert_one(post) logging.debug('loop complete') time.sleep(60)
df_this_year["balance_gbp"] = 0 if "delta_gbp" not in df_this_year: df_this_year["delta_gbp"] = 0 df_this_year.to_csv(f'csvs/annual/{today.year}.csv') except FileNotFoundError as e: df_this_year = pd.DataFrame(columns=[ "timestamp", "datetime_utc", "validator", "epoch", "effective_balance_eth", "balance_eth", "delta_eth", "balance_usd", "delta_usd", "balance_gbp", "delta_gbp" ]) df_this_year.to_csv(f'csvs/annual/{today.year}.csv') try: # get ETH_USD eth_usd_price = float( coinbase_client.get_spot_price(currency_pair='ETH-USD').amount ) # only check this once for the whole loop through validators eth_gbp_price = float( coinbase_client.get_spot_price(currency_pair='ETH-GBP').amount ) # only check this once for the whole loop through validators coinbase_timeout = 15 except requests.ConnectionError as e: print( f"Unable to connect to Coinbase API, retrying in for {coinbase_timeout} seconds." ) time.sleep(coinbase_timeout) coinbase_timeout += 15 continue for v in validators: print(f"Updating balance sheet for validator: {v}")
class Command(BaseCommand): comparison_currency = 'USD' coin_list_url = 'https://api.coinbase.com/v2/currencies' api_version = '2018-02-14' xchange = Xchange.objects.get(pk=XCHANGE['COINBASE']) def handle(self, *args, **options): # instance variable unique to each instance try: self.client = Client(self.xchange.api_key, self.xchange.api_secret, api_version='2018-01-14') except ObjectDoesNotExist as error: logging.debug('Client does not exist:{0}'.format( error)) xchange_coins = json.loads(self.getCoins()) for xchange_coin in xchange_coins['data']: try: currency = Currency.objects.get(symbol=xchange_coin['id']) print(xchange_coin['id'] + " exists") except ObjectDoesNotExist as error: print(xchange_coin['id'] + " does not exist in our currency list..adding") currency = Currency() symbol = SymbolName.SymbolName(xchange_coin['id']) currency.symbol = symbol.parse_symbol() try: currency.save() print("added") except: print("failed adding {0}".format(xchange_coin['id'])) continue now = datetime.now() start_date = now.replace(second=0, minute=0, hour=0) end_date = start_date - timedelta(days=10) while end_date < start_date: prices = self.getPrice(xchange_coin['id'], date=start_date.strftime('%Y-%m-%d')) coins = Coins.Coins() if len(prices) != 0: coin = coins.get_coin_type(symbol=currency.symbol, time=int(calendar.timegm(start_date.timetuple())), exchange=self.xchange) coin.time = int(calendar.timegm(start_date.timetuple())) coin.close = float(prices.amount) coin.xchange = self.xchange coin.currency = currency coin.save() start_date = start_date - timedelta(days=1) def getCoins(self): headers = {'content-type': 'application/json', 'user-agent': 'your-own-user-agent/0.0.1'} params = {} currencies = requests.get(self.coin_list_url, params=params, headers=headers) return currencies.text def getPrice(self, currency_symbol, date): try: res = self.client.get_spot_price(currency_pair=currency_symbol + '-USD', date=date) except: res = {} return res