def sell_bitcoin(): connection = get_connection() client = Client('fakeapikey', 'fakeapisecret') sell_info = client.get_sell_price(currency_pair='BTC-USD') sell_price = float(sell_info["amount"]) qty = request.form['qty'] cmd = connection.cursor() cmd.execute("select remain_capital from trade_user where user_id = 1") remain = cmd.fetchmany(1) remain = float(remain[0][0]) qty_float = float(qty) total_price = qty_float * sell_price cmd.execute("select sum(quantity) from trade_record where item_id=1") remain_qty = cmd.fetchmany(1) remain_qty = int(remain_qty[0][0]) if qty_float <= remain_qty: sell_price = str(sell_price) sql = 'insert into trade_record (quantity,item_id,price) values (' + qty + ',1,' + sell_price + ')' result = connection.cmd_query(sql) # insert the price to the database, the variable of price is buy_price remain = remain - total_price remain_qty = remain_qty - qty_float remain = str(remain) sql1 = 'update trade_user set remain_capital=' + remain + ' where user_id=1' result = connection.cmd_query(sql1) connection.commit() connection.close() return "Order process!" else: return "有内鬼!"
class CoinBasePrice: currency_pair = attr.ib(default='ETH-EUR') spot_price = attr.ib(init=False, default=0.0) sell_price = attr.ib(init=False, default=0.0) buy_price = attr.ib(init=False, default=0.0) client = None config = config _last_update = attr.ib(init=False, default=None) def connect(self): self.client = Client(self.config.get('CoinBase', 'API_KEY'), self.config.get('CoinBase', 'API_SECRET'), api_version=self.config.get( 'CoinBase', 'API_VERSION')) def fetch(self): if not self.client: self.connect() self.sell_price = float( self.client.get_sell_price( currency_pair=self.currency_pair).amount) * 0.985 # self.spot_price = float(self.client.get_spot_price(currency_pair=self.currency_pair).amount) # self.buy_price = float(self.client.get_buy_price(currency_pair=self.currency_pair).amount) self._last_update = arrow.now() def __str__(self): return f"{self.currency_pair} - " \ f"{self.sell_price}/{self.spot_price}/{self.buy_price} " \ f"(sell/spot/buy), {self._last_update}"
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 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)
from coinbase.wallet.client import Client client = Client('<YOUR API KEY>', '<YOUR API KEY>', api_version='2017-11-20') accounts = client.get_accounts() currency_code = 'GBP' # can also use EUR, CAD, etc. for x in range(1): #Make the request #price = client.get_spot_price(currency=currency_code) #print ('Current bitcoin price in ' + currency_code + " " + price.amount) price = client.get_buy_price(currency_pair='BTC-GBP') #print ('Current BTC BUY price in ' + currency_code + " " + price.amount) price = client.get_sell_price(currency_pair='BTC-GBP') #print ('Current BTC SELL price in ' + currency_code + " " + price.amount) accounts = client.get_accounts() for account in accounts.data: balance = account.balance #print (account.name, balance.amount, balance.currency) #print (account.get_transactions()) #**********************TESTING************************ #**********************TESTING************************ #**********************TESTING************************ #**********************TESTING************************ #for x in range(100):
def test_get_sell_price(self): client = Client(api_key, api_secret) sell_price = client.get_sell_price() self.assertIsInstance(sell_price, APIObject) self.assertEqual(sell_price, mock_item)
: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')))
def test_get_sell_price(self): client = Client(api_key, api_secret) sell_price = client.get_sell_price() self.assertIsInstance(sell_price, APIObject) self.assertEqual(sell_price, mock_item)
def get_ltc_sellprice(): client = Client('apisell', 'secretsell') sell_ltc = client.get_sell_price(currency_pair = 'LTC-USD') return sell_ltc
# print accounts exchange_rates = client.get_exchange_rates() data = pd.DataFrame( columns=['time', 'currency_pair', 'spot_price', 'buy_price', 'sell_price']) log_num = 1 while True: for entry in range(14400): for currency in currencies: currency_pair = currency + '-USD' server_time = client.get_time() buy_price = client.get_buy_price(currency_pair=currency_pair) sell_price = client.get_sell_price(currency_pair=currency_pair) spot_price = client.get_spot_price(currency_pair=currency_pair) data = data.append( { 'time': server_time['iso'], 'currency_pair': currency_pair, 'spot_price': spot_price['amount'], 'buy_price': buy_price['amount'], 'sell_price': sell_price['amount'] }, ignore_index=True) with open('logs/log_{}.csv'.format(log_num), 'a') as f: if entry == 0: data.to_csv(f, header=True)
def checkPrice(): client = Client(API, APIsecrect) data = client.get_sell_price(currency_pair='ETH-USD') return data
def get_eth_sellprice(): client = Client('apisell', 'secretsell') sell_eth = client.get_sell_price(currency_pair = 'ETH-USD') return sell_eth
#print(r.__dict__.keys()) #print(json.load(r.content)) json_data = json.loads(str(r.content, encoding='utf-8')) buy_price_B = json_data['data']['buy_price'] sell_price_B = json_data['data']['sell_price'] buy_BTCUSD_KRW = float(buy_price_B) / float(USDKRW) sell_BTCUSD_KRW = float(sell_price_B) / float(USDKRW) #coinbase data extraction api_key_C = 'place you api key for coinbase' api_secret_C = 'place your api secret for coinbase' client = Client(api_key_C, api_secret_C) buy_BTCUSD = float(client.get_buy_price(currency_pair='BTC-USD')) sell_BTCUSD = float(client.get_sell_price(currency_pair='BTC-USD')) buy_price = float(buy_price['amount']) sell_price = float(sell_price['amount']) date_time_C = client.get_time() date_time_C = date_time_C["iso"] abs_diff = abs(buy_BTCUSD_KRW, buy_BTCUSD) 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:
#for buy triggers pricelow1 = 2240 pricelow2 = 2375 #for sell triggers mySellPrice = 8000 #Gets my account balance #balance = account.balance #Gets the current buy price for Bitcoin buyPrice = client.get_buy_price().amount #Gets the current sell price for Bitcoin sellPrice = client.get_sell_price().amount #Sell Price for Litecoin sellPriceL = client.get_sell_price(currency_pair='LTC-USD').amount #Gets the current price for Bitcoin spotPrice = client.get_spot_price().amount #Gets primary account which is Bitcoin wallet #wallet = client.get_primary_account() #Tests that can be deleted whenever #print("Current buy price", buyPrice) #print("Current sell price", sellPrice) #print("Current spot price", spotPrice) #print("My account balance:",account.balance)
# - add your api key in the api_key variable # - add your api secretin the api_secret variable from coinbase.wallet.client import Client import os os.system("clear") api_key = "" # insert your api key here api_secret = "" # insert your api secret here client = Client(api_key, api_secret) time = client.get_time().iso user = client.get_current_user() balance = client.get_primary_account().balance print("+------------------------------------------------+") print("| Coinbase Bitcoin Manager v1.0 |") print("+------------------------------------------------+") print print("Server time: %s " % time) print("Name: %s " % user.name) print("Primary Wallet Balance: %s " % balance) print("--------------------------------------------------") buy = client.get_buy_price(currency_pair = 'BTC-USD') print("BTC Buy Price: %s " % buy) sale = client.get_sell_price(currency_pair = 'BTC-USD') print("BTC Sales Price: %s " % sale) print("--------------------------------------------------")
#!/usr/bin/env python3 from coinbase.wallet.client import Client import json import creds import datetime current_datetime = datetime.datetime.now() print("[+] Current Datetime: {}".format(current_datetime)) client = Client(creds.api_key, creds.api_secret) accounts = client.get_accounts() total_inr = 0.00 for account in accounts["data"]: balance = account["balance"] price = client.get_sell_price(currency_pair=balance["currency"] + '-INR') native_currency = float(str(balance["amount"])) * float( str(price["amount"])) print("[+] You have {0} {1} valued {2} INR at {3} per {1}".format( balance["amount"], balance["currency"], native_currency, price["amount"])) total_inr += native_currency print("[+] Total inr worth is: {} ".format(float(total_inr))) with open("log.csv", "a") as f: message = "{}, {}\n".format(current_datetime, total_inr) f.write(message)
from config import coinbase_api_key, coinbase_api_secret SANDBOX_URL = 'https://api.sandbox.coinbase.com' client = Client( coinbase_api_key(), coinbase_api_secret(), base_api_uri=SANDBOX_URL) payment_methods = client.get_payment_methods() account = client.get_primary_account() payment_method = client.get_payment_methods()[0] buy_price_threshold = 200 sell_price_threshold = 500 buy_price = client.get_buy_price(currency='USD') sell_price = client.get_sell_price(currency='USD') if float(sell_price.amount) <= sell_price_threshold: sell = account.sell(amount='1', currency="BTC", payment_method=payment_method.id) if float(buy_price.amount) <= buy_price_threshold: buy = account.buy(amount='1', currency="BTC", payment_method=payment_method.id)
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)
- 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 CoinbaseBot: def __init__(self, api_key, api_secret): """ Initializes an instance of the CoinbaseBot class. Initializes and sets the Coinbase API client. Args: api_key:str: API key for authenticating with the Coinbase API. api_secret:str: API secret for authenticating with the Coinbase API. client:coinbase.wallet.client.Client: Client object for authenticating using the provided api_key and api_secret. """ self.api_key = api_key self.api_secret = api_secret self.client = Client(self.api_key, self.api_secret) def live_prices(self, buy_currency_pair=None, sell_currency_pair=None): """ Fetches the current buy price and sell price for specified cryto currency pairs. Can be same currency pair, or individual. Args: buy_currency_pair:str: The currency pair for which to get the current buy price. Formatted like so "XXX-XXX". See Coinbase documentation. sell_currency_pair:str: The currency pair for which to get the current buy price. Formatted like so "XXX-XXX". See Coinbase documentation. Returns: dict: Most recent buy and sell data for the specified currency pair. Includes the "amount" or price, and two individual fields denoting the pair. """ combined_data = {} buy_data = self.live_buy_price(buy_currency_pair) sell_data = self.live_sell_price(sell_currency_pair) combined_data['buy'] = buy_data combined_data['sell'] = sell_data return combined_data def live_buy_price(self, currency_pair): """ Fetches the current buy price for a given cryto currency pair. Args: currency_pair:str: The currency pair for which to get the current buy price. Formatted like so "XXX-XXX". See Coinbase documentation. Returns: dict: Key value dictionary object. """ return self.client.get_buy_price(currency_pair=currency_pair) def live_sell_price(self, currency_pair): """ Fetches the current sell price for a given cryto currency pair. Args: currency_pair:str: The currency pair for which to get the current buy price. Formatted like so "XXX-XXX". See Coinbase documentation. Returns: dict: Key value dictionary object. """ return self.client.get_sell_price(currency_pair=currency_pair)
from coinbase.wallet.client import Client import time import os from keys import API_KEY, API_SECRET, ACCOUNT_ID 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) x = client.get_buy_price(currency_pair='BTC-CAD') y = client.get_sell_price(currency_pair='BTC-CAD') print(x["amount"]) s = time.strftime('%Y-%m-%d-%H-%M-%S') #will produce 2011-10-24-13-10 print(s) cwd = os.getcwd() f = open(cwd + "\logs\\" + s + ".txt", "w+") f.write(str(x['amount']) + '\n') f.write(str(y['amount']) + '\n') f.write(str(s) + '\n') #print(client.get_spot_price(currency_pair = 'BTC-CAD')) #print(client.get_time()) #print(client.get_primary_account()) #print(client.get_transactions(ACCOUNT_ID))
api_secret="API_SECRET", api_version="YYYY-MM-DD") # Making sure a verified payment method is associated with the Coinbase account. #payment_methods = client.get_payment_methods() # Buy and Sell bitcoins # account = client.get_primary_account() # payment_method = client.get_payment_methods()[0] buy_price_threshold = 200 sell_price_threshold = 500 buy_price = client.get_buy_price(currency='EUR') sell_price = client.get_sell_price(currency='EUR') if float(sell_price.amount) <= sell_price_threshold: sell = account.sell(amount='1', currency="BTC", payment_method=payment_method.id) if float(buy_price.amount) <= buy_price_threshold: buy = account.buy(amount='1', currency="BTC", payment_method=payment_method.id) #while 1: # Infinite loop for y in range(1): # get BTC info
client = Client(api_key="API_KEY", api_secret="API_SECRET", api_version="YYYY-MM-DD"); # Making sure a verified payment method is associated with the Coinbase account. #payment_methods = client.get_payment_methods() # Buy and Sell bitcoins # account = client.get_primary_account() # payment_method = client.get_payment_methods()[0] buy_price_threshold = 200 sell_price_threshold = 500 buy_price = client.get_buy_price(currency='EUR') sell_price = client.get_sell_price(currency='EUR') if float(sell_price.amount) <= sell_price_threshold: sell = account.sell(amount='1', currency="BTC", payment_method=payment_method.id) if float(buy_price.amount) <= buy_price_threshold: buy = account.buy(amount='1', currency="BTC", payment_method=payment_method.id) #while 1: # Infinite loop for y in range(1):