def Sell(): """Sell 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.sell(btc_id, amount, currency='USD') print(f"Sell order executed in the amount of ${amount}.")
def test_sell(self): client = Client(api_key, api_secret) with self.assertRaises(ValueError): client.sell('foo') for valid_kwargs in [{'amount': '1.0'}, {'total': '1.0'}]: sell = client.sell('foo', **valid_kwargs) self.assertIsInstance(sell, Sell) self.assertEqual(sell, mock_item)
def test_sell(self): client = Client(api_key, api_secret) with self.assertRaises(ValueError): client.sell('foo') for valid_kwargs in [{'amount': '1.0'}, {'total': '1.0'}]: sell = client.sell('foo', **valid_kwargs) self.assertIsInstance(sell, Sell) self.assertEqual(sell, mock_item)
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 sell_currency(instant, _amount): client = Client(config['api_key'], config['api_secret']) if instant.market == "BTC": client.sell(config['btc_wallet'], amount=_amount, currency="USD", payment_method=config['usd_fiat']) elif instant.market == "ETH": client.sell(config['eth_wallet'], amount=_amount, currency="USD", payment_method=config['usd_fiat']) elif instant.market == "LTC": client.sell(config['ltc_wallet'], amount=_amount, currency="USD", payment_method=config['usd_fiat'])
# 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: # SELL! print( "BURST! Price dropped from ${} to ${}! Selling all {} BTC now!". format(btc_max, btc_price, account.balance.amount)) client.sell(btc_account.id, total=btc_account.balance.amount, currency="BTC", payment_method=payout_method) break else: print("Hodling {} BTC worth ${}...".format( account.balance.amount, account.native_balance.amount))
def self_bitcoin_at_price_USD(self, sell_price_usd): client = Client(api_key, api_secret, api_version = CB_VERSION) cb_tools = Cb_tools(client) msg = "Selling all bitcoins at price:$" + str(sell_price_usd) + "\nRetype to confirmed_price:\n" confirmed_price = raw_input(msg) if int(confirmed_price) == sell_price_usd: pass else: return #f_name = 'Logs/Log file ' + start_time + '.txt' #f= open(f_name,"a+") #f_sell_price = 'Logs/Prices/sell price recorder history ' + start_time + '.txt' #f_sell = open(f_sell_price,"a+") #f_buy_price = 'Logs/Prices/buy price recorder history ' + start_time + '.txt' #f_buy = open(f_buy_price,"a+") #print cb_tools.get_blance() #print cb_tools.get_sell_price() #print cb_tools.sell_total() #usr = client.get_current_user() #print usr #account = client.get_account('') #account = client.get_accounts() #print account #rates = client.get_exchange_rates(currency = 'BTC') # buy_price = json.dumps(client.get_buy_price(currency_pair = 'BTC-USD')) # sell_price = json.dumps(client.get_sell_price(currency_pair = 'BTC-USD')) # buy_price = ast.literal_eval(buy_price) # sell_price = ast.literal_eval(sell_price) #print buy_price #print sell_price #sell_price = cb_tools.obj_to_dic(client.get_buy_price(currency_pair = 'BTC-USD')) #print sell_price['amount'] #txs = client.get_sells('') #txs = client.get_buys('') #print txs #pms = client.get_payment_methods() #print pms # sell = client.sell('', # amount="2", # currency="USD", # payment_method="") # print sell current_balance = cb_tools.sell_total() #cb_tools.slack_msg('#############################\n\tTrading bot has started\n#############################') while current_balance > 10 and not self.SOLD_OUT: msg = time.ctime(time.time()) + ': Current total BTC balance:' + str(current_balance) print '#######################' print msg #f.write("%s\r\n" % msg) #sell_price = cb_tools.obj_to_dic(client.get_sell_price(currency_pair = 'BTC-USD')) #f_sell.write("%s\r\n" % sell_price['amount']) #buy_price = cb_tools.obj_to_dic(client.get_buy_price(currency_pair = 'BTC-USD')) #f_buy.write("%s\r\n" % sell_price['amount']) #spot_price = cb_tools.obj_to_dic(client.get_spot_price(currency_pair = 'BTC-USD')) #print 'sell: ', sell_price['amount'], 'buy: ', buy_price['amount'], 'spot: ', spot_price['amount'] # if int(math.ceil(float(buy_price['amount']))) < MAX_BUY_PRICE: # buy = cb_tools.buy_with_usd(ONE_TIME_BUYING_AMOUNT) # print buy quote_price_sell = cb_tools.get_quote_sell(current_balance) print 'Quote sell price: $', quote_price_sell print 'SELL_ALL_LOW_THREAD_USD: $', SELL_ALL_LOW_THREAD_USD if SELL_ALL_LOW_THREAD_USD < quote_price_sell: try: msg = 'tying to sale all' print msg #f.write("%s\r\n" % msg) sell = client.sell(account_id, amount=str(current_balance), currency="USD", payment_method="d") time.sleep(2) self.SOLD_OUT = True msg = '\n########################\nALL BTC SOUL OUT\n###########################\n' cb_tools.slack_msg(msg) print msg #f.write("%s\r\n" % msg) #cb_tools.sold_out_nose() #while True: #time.sleep(5) except: msg = 'sale failed' print msg #f.write("%s\r\n" % msg) time.sleep(1) else: pass # msg = '#########\nprice in safe region\n########\n' + str(current_balance - SELL_ALL_THREAD) + ' USD above sell price' # print msg # f.write("%s\r\n" % msg) # current_balance = cb_tools.sell_total() # if time.time() - int(start_time) > NEW_FILE_INTERVAL: # f_sell.close() # start_time =(str(int(time.time()))) # f_sell_price = 'Logs/sell price recorder history ' + start_time + '.txt' # f_sell = open(f_sell_price,"a+") # f_buy.close() # start_time =(str(int(time.time()))) # f_buy_price = 'Logs/buy price recorder history ' + start_time + '.txt' # f_buy = open(f_buy_price,"a+") time.sleep(2)
#If it reaches here you are in profit plus a little bit for fee's and stuff open('/root/MyPythonCode/tradingbot.log', 'a+').write("DEBUG CONSIDER SELLING!!! " + str(datetime.datetime.now()) + " " + str(price_change) + " Percentage Increase is " + str(percentage) + '\n') #Write a little market to the file to signify this fact open('/root/MyPythonCode/pricehist.txt', 'a+').write("***PROFIT MARKER*** " + str(datetime.datetime.now()) + '\n') #Example - DO NOT USE #sell = client.sell('2bbf394c-193b-5b2a-9155-3b4732659ede',amount="10",currency="BTC", payment_method="83562370-3e5c-51db-87da-752af5ab9559") #DO THE SELL! sell = client.sell( acc_id, total=float(price_change), currency="GBP" ) #Is this a float or a string??? Not sure check this out later #GET THE SELL ID! sell_id = str(sell.id) print("DEBUG: sell_id " + str(sell_id)) sell_info = client.get_sell(acc_id, sell_id) #***FOR SOME REASON THIS DOESNT WORK BUT TRANSACTIONS COMPLETE QUICKLY ANYWAY*** #while not str(sell_info.status) == "completed" or "cancelled": #time.sleep(3) #print ("DEBUG: Waiting for 5 seconds and check again, Status is " + str(sell_info.status) ) #NOTE: Status is either created, completed, canceled. loop whilst not completed!!!! We need to wait to the transaction is either cancelled or even better completed if str(sell_info.status) != "completed": print("DEBUG : " + str(sell_info.status))
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', quote='true') eth_sell = client.sell(config['eth_wallet'], amount=1.0000, currency='ETH', quote='true') ltc_sell = client.sell(config['eth_wallet'], amount=1.0000, currency='LTC', quote='true') btc_instant = Instant(btc_buy['subtotal']['amount'], btc_sell['subtotal']['amount'], btc_buy['amount']['currency'], datetime.now())
pms = client.get_payment_methods() for method in pms.data: if method['name'] == targetOutcomeMethod: paymentID = method['id'] for account in accounts.data: if account['name'] == targetSellCurrencyWallet: accountID = account['id'] # Creating the sell order the arguments quote and commit are used to create only a preview # Order can not be executed this way # The current outcome you would receive is stored to outcome variable sell = client.sell(accountID, commit="false", amount=targetAmountToSell, currency=targetCurrency, payment_method=paymentID, quote="true") outcome = float(sell["total"]["amount"]) # Last but not least: # Comparing the sell reward with the desired sell reward. # CRITICAL if desired reward (outcome) is reached # OK if its not reached yet if outcome > receiveMoneyWish: print("Your desired target outcome is reached! Time to sell! | outcome=" + str(outcome)) sys.exit(2) else: print( "Your desired target outcome is not reached yet. Keep waiting! | outcome="
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) #Buy bitcoins on Bithumb #documentation not clear ... Database.Database.WriteOrders() flag = 0
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