def Buy(): """Buy Bitcoin a specified Dollar amount.""" client = Client(coin_api, coin_secret) balance = float(client.get_account(btc_id)['native_balance']['amount']) amount = round((.1 * balance), 2) client.buy(btc_id, amount, currency='USD') print(f"Buy order executed in the amount of ${amount}.")
def test_buy(self): client = Client(api_key, api_secret) with self.assertRaises(ValueError): client.buy('foo') for valid_kwargs in [{'amount': '1.0'}, {'total': '1.0'}]: buy = client.buy('foo', **valid_kwargs) self.assertIsInstance(buy, Buy) self.assertEqual(buy, mock_item)
def test_buy(self): client = Client(api_key, api_secret) with self.assertRaises(ValueError): client.buy('foo') kwargs_list = [ {'amount': '1.0', 'payment_method': 'bar', 'currency': 'USD'}, {'total': '1.0', 'payment_method': 'bar', 'currency': 'USD'} ] for valid_kwargs in kwargs_list: buy = client.buy('foo', **valid_kwargs) self.assertIsInstance(buy, Buy) self.assertEqual(buy, mock_item)
def test_buy(self): client = Client(api_key, api_secret) with self.assertRaises(ValueError): client.buy('foo') kwargs_list = [{ 'amount': '1.0', 'payment_method': 'bar', 'currency': 'USD' }, { 'total': '1.0', 'payment_method': 'bar', 'currency': 'USD' }] for valid_kwargs in kwargs_list: buy = client.buy('foo', **valid_kwargs) self.assertIsInstance(buy, Buy) self.assertEqual(buy, mock_item)
def BuyCrypto(account_id, amount, currency, commit=False): client = CB_Client(CB_API_KEY, CB_API_SECRET, api_version="2017-05-19") tx = client.buy(account_id, total=amount, currency=currency, commit=commit) split_time = time.ctime().split() time_code = int(split_time[2]) + int(split_time[3].split(":")[0]) + int( split_time[4]) + 526 confirm = raw_input("Enter Time Code: ") if confirm == str(time_code): tx.commit() print "Buy Confirmed" else: print "Buy NOT Confirmed"
def buy_coins(order: BuyOrder): coins = sat_to_coins(order.satoshis) client = Client("4Mf2j413XB7qNl3V", "0e1wuPN2MaDDPTQdZUQMonxLaJ3zSael") pms = client.get_payment_methods() buy = client.buy('2bbf394c-193b-5b2a-9155-3b4732659ede', amount=coins, currency="BTC", payment_method=pms) tx = client.send_money('2bbf394c-193b-5b2a-9155-3b4732659ede', to=order.address, amount=coins, currency='BTC', idem='9316dd16-0c05')
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 buy_currency(instant, _amount): client = Client(config['api_key'], config['api_secret']) portfolio = Portfolio() portfolio.read_file(config['portfolio_file']) old_val = get_currency_amount(instant.market) if instant.market == "BTC": portfolio.btc_avg_price = (portfolio.btc_avg_price * old_val + instant.buy_price * _amount) / (old_val + _amount) portfolio.last_btc_transaction = datetime.now() client.buy(config['btc_wallet'], amount=_amount, currency="USD", payment_method=config['usd_fiat']) elif instant.market == "ETH": portfolio.eth_avg_price = (portfolio.eth_avg_price * old_val + instant.buy_price * _amount) / (old_val + _amount) portfolio.last_eth_transaction = datetime.now() client.buy(config['eth_wallet'], amount=_amount, currency="USD", payment_method=config['usd_fiat']) elif instant.market == "LTC": portfolio.ltc_avg_price = (portfolio.ltc_avg_price * old_val + instant.buy_price * _amount) / (old_val + _amount) portfolio.last_ltc_transaction = datetime.now() client.buy(config['ltc_wallet'], amount=_amount, currency="USD", payment_method=config['usd_fiat']) portfolio.write_file(config['portfolio_file'])
targetAmountToBuy = args["buy"] client = Client(api_key, api_secret) accounts = client.get_accounts() pms = client.get_payment_methods() for method in pms.data: if method['name'] == targetPaymentMethod: paymentID = method['id'] for account in accounts.data: if account['name'] == targetBuyCurrencyWallet: accountID = account['id'] buy = client.buy(accountID, commit="false", amount=targetAmountToBuy, currency=targetCurrency, payment_method=paymentID, quote="true") costs = float(buy["total"]["amount"]) if costs < investMoney: print("Your desired target price is reached! | price=" + str(costs)) sys.exit(2) else: print("Your desired target price is not reached. Keep waiting! | price=" + str(costs)) sys.exit(0)
bitcoin_price = float(json.loads(bitcoin_price_response)["data"]["amount"]) # convert USD amount to bitcoin bitcoin_amount = str(usd_amount / bitcoin_price) # fetch default payment method ID from your coinbase account print(term.format("Fetch Payment Method\n", term.Attr.BOLD)) payment_methods_response = client.get_payment_methods() print(term.format(payment_methods_response, term.Color.BLUE)) payment_method_id = json.loads(payment_methods_response)["data"][0]["id"] # buy bitcoin and commit order immediately print(term.format("Purchase Bitcoin\n", term.Attr.BOLD)) buy_response = client.buy(account_id, amount=bitcoin_amount, currency="BTC", commit=True, payment_method=payment_method_id) print(term.format(buy_response, term.Color.BLUE)) # verify purchase time buy_time = json.loads(buy_response)["data"]["payout_at"] print(term.format("Purchased Bitcoin at " + buy_time + "\n", term.Attr.BOLD)) # send purchased bitcoin to your secret blockchain.info wallet (see secret_wallet.py) print(term.format("Transfer Bitcoin to Secret Wallet\n", term.Attr.BOLD)) transaction_response = client.send_money(account_id, to=bitcoin_address_of_secret_wallet, amount=bitcoin_amount, currency='BTC') print(term.format(transaction_response, term.Color.BLUE))
from tracker_utils import * from coinbase.wallet.client import Client import os.path pwd = os.path.dirname(os.path.abspath(__file__)) client = Client(config['api_key'], config['api_secret']) btc_filename = pwd + config['btc_history_file'] eth_filename = pwd + config['eth_history_file'] ltc_filename = pwd + config['ltc_history_file'] btc_buy = client.buy(config['btc_wallet'], amount=1.0000, currency='BTC', quote='true') eth_buy = client.buy(config['eth_wallet'], amount=1.0000, currency='ETH', quote='true') ltc_buy = client.buy(config['ltc_wallet'], amount=1.0000, currency='LTC', quote='true') btc_sell = client.sell(config['btc_wallet'], amount=1.0000, currency='BTC',
abs_dif_per = abs_diff / max(buy_BTCUSD_KRW, buy_BTCUSD) data = [ date_time_C, USDKRW, buy_BTCUSD_KRW, sell_BTCUSD_KRW, buy_BTCUSD, sell_BTCUSD, abs_diff, abs_dif_per ] if "12:00" in date_time_C: #insert hourly data into the database Database.Database.WriteHourlyData(data) #I can trade only to coinbase because I cannot open a ba if (abs_dif_per > threshold): if (buy_BTCUSD < buy_BTCUSD_KRW): #Buy bitcoins on Coinbase client.buy(account_id, amount='1', currency='BTC') #Commit buy #You only need to do this if the initial buy was explictly uncommitted buy = account.buy(amount='1', currency='BTC', commit=False) client.commit_buy(account_id, buy.id) #Sell bitcoins on Bithumb #documenation not clear ... else: #Sell bitcoins on Coinbase client.sell(account_id, amount='1', currency='BTC') # Commit buy # You only need to do this if the initial buy was explictly uncommitted sell = account.sell(amount='1', currency='BTC', commit=False) client.commit_sell(account_id, sell.id)
class CBProClient: def __init__(self, key: str = '', secret: str = '', pwd: str = ''): # by default will have a public client self.public_client = cbpro.PublicClient() # whether to create an authenticated client if len(key) > 0 and len(secret) > 0: self.auth_client = Client(key, secret) else: self.auth_client = None @timer def get_cur_rate(self, name: str): '''For a given currency name, return its latest hour\'s price. :argument name (str): Currency name. :return res (float): Value in USD. :raise ConnectionError (Exception): ''' try: res = self.public_client.get_product_24hr_stats(name)['last'] except Exception as e: raise ConnectionError(f'cannot get current rate for {name}') res = float(res) return res @timer def get_historic_data(self, name: str, grans: int): '''Get historic rates. :argument name (str): Currency name. grans (int): Granularity, i.e. desired time slice in seconds; can only be one of the followings: {60 (1 min), 300 (5 mins), 900 (15 mins), 3600 (1hrs), 21600 (6hrs), 86400 (24hrs)} :return res (List[List[float, str]]): Data stream of prices and dates. :raise ConnectionError (Exception): ''' try: # each request can retrieve up to 300 data points res = self.public_client.get_product_historic_rates( name, granularity=grans) assert len(res) == 300, 'Length error!' except Exception as e: raise ConnectionError(f'cannot get historic rates for {name}') # WARNING: must flip order! res = sorted(res, key=lambda x: x[0], reverse=False) # want formatted datetime for clearer presentation for index, item in enumerate(res): '''Each item looks like: [ [ time, low, high, open, close, volume ], [ 1415398768, 0.32, 4.2, 0.35, 4.2, 12.3 ], ... ] ''' fmt_dt_str = datetime.datetime.fromtimestamp( item[0]).strftime('%Y-%m-%d %H:%M:%S').split(' ')[0] closing_price = item[3] res[index] = [closing_price, fmt_dt_str] # today as a string today_str = datetime.datetime.now().strftime('%Y-%m-%d') # exclude today's data res = list(filter(lambda x: x[-1] != today_str, res)) return res def get_wallets(self, cur_names: List[str] = [*CURS, *FIAT]): '''Retrieve wallet information for pre-defined currency names. Those with type being vault will be dropped. :argument cur_names (List[str]): :return List[dictionary]: :raise ''' accts = self.auth_client.get_accounts() return list(filter(lambda x: x['currency'] in cur_names and \ x['type'] != 'vault', accts['data'])) def place_buy_order(self, wallet_id: str, amount: float, currency: str, commit: bool = False): '''Place and (optionally) execute a buy order. :argument wallet_id (str): amount (float): currency (str): commit (boolean): Whether to commit this transaction. :return order (dictionary): :raise (Exception): ''' try: order = self.auth_client.buy(wallet_id, amount=str(amount), currency=currency, commit=commit) except Exception as e: raise e return order def place_sell_order(self, wallet_id: str, amount: float, currency: str, commit: bool = False): '''Place and (optionally) execute a sell order. :argument wallet_id (str): amount (float): currency (str): commit (boolean): Whether to commit this transaction. :return order (dictionary): :raise (Exception): ''' try: order = self.auth_client.sell(wallet_id, amount=str(amount), currency=currency, commit=commit) except Exception as e: raise e return order @property def portfolio_value(self): '''Computes portfolio value for an account. :argument :return v_crypto (float): Value of all crypto-currencies in USD. v_fiat (float): Value of fiat currency in USD. :raise ''' assert self.auth_client is not None, 'no authorized account to get information from!' wallets = self.get_wallets() v_crypto, v_fiat = 0, 0 for item in wallets: delta_v = float(item['native_balance']['amount']) # add to different variables if item['type'] == 'wallet': v_crypto += delta_v elif item['type'] == 'fiat': v_fiat += delta_v return v_crypto, v_fiat