class TestBittrexPublicAPI(unittest.TestCase): """ Integration tests for Bittrex Public API """ def setUp(self): self.bittrex = Bittrex() def test_get_markets(self): actual = self.bittrex.get_markets() test_basic_response(self, actual, 'get_markets') def test_get_currencies(self): actual = self.bittrex.get_currencies() test_basic_response(self, actual, 'get_currencies') def test_get_ticker(self): self.assertRaises(TypeError, self.bittrex.get_ticker) actual = self.bittrex.get_ticker('BTC-LTC') test_basic_response(self, actual, 'get_ticker') false_actual = self.bittrex.get_ticker('BTC') test_failed_response(self, false_actual, 'get_ticker') def test_get_market_summaries(self): actual = self.bittrex.get_market_summaries() test_basic_response(self, actual, 'get_market_summaries') def test_get_market_summary(self): self.assertRaises(TypeError, self.bittrex.get_market_summary) actual = self.bittrex.get_ticker('BTC-LTC') test_basic_response(self, actual, 'get_market_summar') false_actual = self.bittrex.get_ticker('BTC') test_failed_response(self, false_actual, 'get_market_summar') def test_get_order_book(self): self.assertRaises(TypeError, self.bittrex.get_order_book) self.assertRaises(TypeError, self.bittrex.get_order_book, 'BTC-LTC') actual = self.bittrex.get_order_book('BTC-LTC', 'buy') test_basic_response(self, actual, 'get_order_book') def test_get_market_history(self): self.assertRaises(TypeError, self.bittrex.get_market_history) actual = self.bittrex.get_market_history('BTC-LTC') test_basic_response(self, actual, 'get_market_history')
class TestBittrexV11PublicAPI(unittest.TestCase): """ Integration tests for the Bittrex public API. These will fail in the absence of an internet connection or if bittrex API goes down """ def setUp(self): self.bittrex = Bittrex(None, None, api_version=API_V1_1) def test_handles_none_key_or_secret(self): self.bittrex = Bittrex(None, None) # could call any public method here actual = self.bittrex.get_markets() self.assertTrue(actual['success'], "failed with None key and None secret") self.bittrex = Bittrex("123", None) actual = self.bittrex.get_markets() self.assertTrue(actual['success'], "failed with None secret") self.bittrex = Bittrex(None, "123") actual = self.bittrex.get_markets() self.assertTrue(actual['success'], "failed with None key") def test_get_markets(self): actual = self.bittrex.get_markets() test_basic_response(self, actual, "get_markets") self.assertTrue(isinstance(actual['result'], list), "result is not a list") self.assertTrue(len(actual['result']) > 0, "result list is 0-length") def test_get_currencies(self): actual = self.bittrex.get_currencies() test_basic_response(self, actual, "get_currencies") def test_get_ticker(self): actual = self.bittrex.get_ticker(market='BTC-LTC') test_basic_response(self, actual, "get_ticker") def test_get_market_summaries(self): actual = self.bittrex.get_market_summaries() test_basic_response(self, actual, "get_market_summaries") def test_get_orderbook(self): actual = self.bittrex.get_orderbook('BTC-LTC', depth_type=BUY_ORDERBOOK) test_basic_response(self, actual, "get_orderbook") def test_get_market_history(self): actual = self.bittrex.get_market_history('BTC-LTC') test_basic_response(self, actual, "get_market_history") def test_list_markets_by_currency(self): actual = self.bittrex.list_markets_by_currency('LTC') self.assertListEqual(['BTC-LTC', 'ETH-LTC', 'USDT-LTC'], actual) def test_get_wallet_health(self): self.assertRaisesRegexp(Exception, 'method call not available', self.bittrex.get_wallet_health) def test_get_balance_distribution(self): self.assertRaisesRegexp(Exception, 'method call not available', self.bittrex.get_balance_distribution) def test_get_candles(self): self.assertRaisesRegexp(Exception, 'method call not available', self.bittrex.get_candles, market='BTC-LTC', tick_interval=TICKINTERVAL_ONEMIN) def test_get_latest_candle(self): self.assertRaisesRegexp(Exception, 'method call not available', self.bittrex.get_latest_candle, market='BTC-LTC', tick_interval=TICKINTERVAL_ONEMIN)
class TestBittrexV20PublicAPI(unittest.TestCase): """ Integration tests for the Bittrex public API. These will fail in the absence of an internet connection or if bittrex API goes down """ def setUp(self): self.bittrex = Bittrex(None, None, api_version=API_V2_0) def test_handles_none_key_or_secret(self): self.bittrex = Bittrex(None, None, api_version=API_V2_0) # could call any public method here actual = self.bittrex.get_market_summaries() self.assertTrue(actual['success'], "failed with None key and None secret") self.bittrex = Bittrex("123", None, api_version=API_V2_0) actual = self.bittrex.get_market_summaries() self.assertTrue(actual['success'], "failed with None secret") self.bittrex = Bittrex(None, "123", api_version=API_V2_0) actual = self.bittrex.get_market_summaries() self.assertTrue(actual['success'], "failed with None key") def test_get_currencies(self): actual = self.bittrex.get_currencies() test_basic_response(self, actual, "get_currencies") def test_get_ticker(self): self.assertRaisesRegexp(Exception, 'method call not available', self.bittrex.get_ticker, market='BTC-LTC') def test_get_market_summaries(self): actual = self.bittrex.get_market_summaries() test_basic_response(self, actual, "get_market_summaries") def test_get_market_summary(self): actual = self.bittrex.get_market_summary(market='BTC-LTC') test_basic_response(self, actual, "get_market_summary") def test_get_orderbook(self): actual = self.bittrex.get_orderbook('BTC-LTC') test_basic_response(self, actual, "get_orderbook") def test_get_wallet_health(self): actual = self.bittrex.get_wallet_health() test_basic_response(self, actual, "get_wallet_health") self.assertIsInstance(actual['result'], list) @unittest.skip("Endpoint 404s. Is this still a valid 2.0 API?") def test_get_balance_distribution(self): actual = self.bittrex.get_balance_distribution() test_basic_response(self, actual, "get_balance_distribution") self.assertIsInstance(actual['result'], list) def test_get_candles(self): actual = self.bittrex.get_candles('BTC-LTC', tick_interval=TICKINTERVAL_ONEMIN) test_basic_response(self, actual, "test_get_candles") self.assertIsInstance(actual['result'], list) def test_get_latest_candle(self): actual = self.bittrex.get_latest_candle( 'BTC-LTC', tick_interval=TICKINTERVAL_ONEMIN) test_basic_response(self, actual, "test_get_latest_candle") self.assertIsInstance(actual['result'], list)
class BittrexDriver: fee = 0.0025 name = "Bittrex" def __init__(self, api_key, secret): api_b = '' key_b = '' self.api = Bittrex(api_key, secret) pass def get_market_info(self): # to get data ask and bid for pair market = {} try: tickers = self.api.get_market_summaries() tickers = tickers['result'] for ticker in tickers: pair = ticker['MarketName'].split('-') pair = tuple(pair) market[pair] = (float(ticker['Ask']), float(ticker['Bid'])) except: market = {} return market def get_order(self, pairs): pair = '{0}-{1}'.format(pairs[0], pairs[1]) try: orders = self.api.get_orderbook(pair, 'both') ask_rate = float( orders['result']['sell'][0]['Rate']) # ask-sell rate bid_rate = float(orders['result']['buy'][0]['Rate']) #bid-buy rate ask_quanity = float(orders['result']['sell'][0]['Quantity']) bid_quanity = float(orders['result']['buy'][0]['Quantity']) order = { 'ask_rate': ask_rate, 'ask_quanity': ask_quanity, 'bid_rate': bid_rate, 'bid_quanity': bid_quanity } except: order = { 'ask_rate': '0', 'ask_quanity': '0', 'bid_rate': '0', 'bid_quanity': '0' } return order def get_txFee(self): txfee = list() currencies = self.api.get_currencies() for i in currencies['result']: txfee.append((i['Currency'], i['CurrencyLong'], float(i['TxFee']))) return txfee # create list of tuples(len = 3) 1 - trade, 2- trade name 3 - txFee def create_pairs(self): fee = self.get_txFee() # txfee list of tuples(len = 3) 1 - trade, 2- trade name 3 - txFee firstmarket = ('BTC', 'ETH', 'USDT') listpair = list() for fi in firstmarket: for tx in fee: listpair.append((fi, tx[0])) return listpair # create list of tuples-pair 1 - trade, 2- currency
from bittrex import Bittrex my_bittrex = Bittrex(None, None) print my_bittrex.get_currencies()
key = "yourkey" secret = "yoursecret" from bittrex import Bittrex from bittrex import API_V2_0 my_bittrex = Bittrex(key, secret) # Get Markets markets = my_bittrex.get_markets() marketsdf = pd.DataFrame.from_dict(markets['result']) # Get Currencies currencies = pd.DataFrame.from_dict(my_bittrex.get_currencies()['result']) currencies_list = currencies[currencies['IsActive'] == True]['Currency'].unique() # Get Ticker ticker = my_bittrex.get_ticker('BTC-LTC') print ticker['result'].head() # Get Market Summaries summaries = my_bittrex.get_market_summaries() summariesdf = pd.DataFrame.from_dict(summaries['result']) print summariesdf.head() # Get Market Summary summary = my_bittrex.get_marketsummary('BTC-LTC') summarydf = pd.DataFrame.from_dict(summary['result']) print summarydf.head() # Get Orderbook orderbook = my_bittrex.get_orderbook('BTC-LTC') orderbookbuydf = pd.DataFrame.from_dict(orderbook['result']['buy']) orderbookselldf = pd.DataFrame.from_dict(orderbook['result']['sell']) print orderbookbuydf.head() print orderbookselldf.head() # Get Market History
import time from bittrex import Bittrex import pandas as pd apikey = 'fd25ef6daf6c4d5cb8507878781df312' secret = '5f00769f175141be861bf199f089f9fd' my_bittrex = Bittrex(apikey, secret) my_bittrex.get_currencies() my_bittrex.get_marketsummary('BTC-LTC') coinList = [{ 'CoinName': x['MarketCurrency'], 'CoinName_Full': x['MarketCurrencyLong'], 'MarketName': x['MarketName'], 'BaseCurrency': x['BaseCurrency'] } for x in my_bittrex.get_markets()['result']] coinList = pd.DataFrame(coinList) coinList BTC - LTC, col = [ 'MarketName', 'High', 'Low', 'Volume', 'Last', 'BaseVolume', 'TimeStamp', 'Bid', 'Ask', 'OpenBuyOrders', 'OpenSellOrders', 'PrevDay', 'Created' ] market_price = pd.DataFrame(columns=col) i = 0 while 1: market_price = pd.DataFrame(columns=col) time = time.asctime()
class CapitVitaCrypto(CapitVita): def __init__(self, home_path='', num_coins=25, mailing_list=[], debug=False): self.num_coins = num_coins self.mailing_list = mailing_list self.coin_list = [] self.df = [] self.debug = debug self.home_path = home_path self.file_path = home_path + 'crypto-data/' self.volume_sum = [] # bittrex self.B = Bittrex(key, secret) self.b_currencies = [ x['Currency'] for x in self.B.get_currencies()['result'] ] # currencies available to trade in bittrex self.market_summaries = self.B.get_market_summaries()['result'] self.markets = [x['MarketName'] for x in self.market_summaries] # market names self.BTC_markets = [ x for x in self.markets if 'BTC' in x and 'USDT' not in x ] self.ETH_markets = [ x for x in self.markets if 'ETH' in x and 'USDT' not in x ] self.USDT_markets = [x for x in self.markets if 'USDT' in x] self.USDT_BTC = [ x for x in self.market_summaries if x['MarketName'] == 'USDT-BTC' ][-1]['Last'] self.USDT_ETH = [ x for x in self.market_summaries if x['MarketName'] == 'USDT-ETH' ][-1]['Last'] def get_coin_list(self): # get coin list (all coins, some are not tradeable on bittrex) url = 'https://www.cryptocompare.com/api/data/coinlist/' response = urllib2.urlopen(url) data = json.loads(response.read()) self.coin_list = [ x.encode('ascii', 'ignore') for x in data['Data'].keys() ] #print(len(self.coin_list)) # 1507 as of 2017-09-14 def grab_data(self, coin): # get historical OHLC for one cryptocurrency url = 'https://min-api.cryptocompare.com/data/histoday?fsym={}&tsym=USD&limit={}&aggregate=1&e=CCCAGG'.format( coin, 80) response = urllib2.urlopen(url) data = json.loads(response.read()) try: self.df = pd.DataFrame(data['Data']) self.df['date'] = self.df['time'].apply( lambda x: datetime.datetime.fromtimestamp(x)) #self.df.drop(['time', 'volumefrom'], axis = 1) #self.df.columns = ['Adj. Close', 'Adj. High', 'Adj. Low', 'Adj. Open', 'time', 'volumefrom', 'volumeto', 'date'] except KeyError: return False self.volume_sum.append(self.df['volumeto'].iloc[-20:].median()) # generate signals self.df['rsi'] = self.RSI(self.df['close'], 14) self.df['26 ema'] = self.df['close'].ewm(ignore_na=False, min_periods=0, adjust=True, com=26).mean() self.df['12 ema'] = self.df['close'].ewm(ignore_na=False, min_periods=0, adjust=True, com=12).mean() self.df['MACD'] = self.df['12 ema'] - self.df['26 ema'] self.df['MACD signal'] = self.df['MACD'] - self.df['MACD'].ewm( ignore_na=False, min_periods=0, adjust=True, com=9).mean() self.df['MACD_norm'] = self.normalize(self.df['MACD signal']) self.df['MACD_der'] = self.derivative(self.df['MACD_norm']) def get_points(self, coin): try: self.grab_data(coin) ## get the data and store it in self.df if len(self.df) < 20 or self.df['volumeto'].iloc[-20:].median( ) < 850000 * 0.8: # if grab is unsuccessful or below average volume * 0.7, end points = {'admin': -500} else: points = {} mb, tb, bb, = self.bbands(self.df['close']) if self.df['close'].iloc[-1] < (mb.iloc[-1] + bb.iloc[-1]) / 2: points['admin'] = -500 # RSI points (max 50) points['rsi'] = 50 - round( 1.2 * abs(30 - self.df['rsi'].iloc[-1])) # MACD points (max 50) points['macd1'] = round( 25 * self.df['MACD_norm'].iloc[-1] / max([abs(x) for x in self.df['MACD_norm']])) points['macd2'] = round( 25 * self.df['MACD_der'].iloc[-1] / max([abs(x) for x in self.df['MACD_der']])) # candlestick points (max 10) candlestickFactor = 1 patterns = self.detectCandlestickPatterns( self.df['open'][-7:], self.df['close'][-7:], self.df['low'][-7:], self.df['high'][-7:], candlestickFactor) points['candlesticks'] = self.rangeLimit( round(sum([x[2] for x in patterns])), -20, 20) except BufferError as e: #except Exception as e: print('problem: {}'.format(e)) return points def find_coins(self, graph=False, bittrex_currencies_only=True): # start counting duration of script start_time = time.time() print('Initiating log...') # create log ff = open(self.file_path + 'readme.txt', 'w') ff.write(str(datetime.datetime.now())) ff.write('\n') print('Deleting old plots...') # delete old files os.chdir(self.file_path) filelist = glob.glob('*.png') for f in filelist: os.remove(f) os.chdir(self.home_path) print('Fetching coin list...') if bittrex_currencies_only: self.update_B() self.coin_list = self.b_currencies else: self.get_coin_list() if self.debug: self.coin_list = self.coin_list[:30] len_coin_list = len(self.coin_list) print(' {} coins.'.format(len_coin_list)) #print(' Expect script to take approximately {} minutes'.format(round(len_coin_list*1.0613 - 14)/60, 2)) # grab data in batches print('Getting points for {} coins...'.format(len_coin_list)) coin_points = {} for i, coin in enumerate(self.coin_list): if i % (len(self.coin_list) / 25) == 0: print('{}% done'.format( round(100 * float(i) / len(self.coin_list), 1))) try: points = self.get_points(coin) coin_points[coin] = [sum([points[x] for x in points]), points] #except BufferError: except Exception as e: print('failed {} because {}'.format(coin, e)) original_len_coin_list = len(coin_points) print('Sorting coins...') # sort stocks by point system sorted_coins = sorted(coin_points.items(), key=itemgetter(1), reverse=True)[:self.num_coins] print(sorted_coins) if graph: print('Graphing coins...') for coin in [x[0] for x in sorted_coins]: try: self.graph_data(coin, saveLocation=self.file_path) except BufferError: #except Exception as e: print('failed {} because {}'.format(coin, e)) # write into log ff.write('Cheap coins to invest in for 2 days ~ 1 week: \n\n') ff.write('#\n') for i in sorted_coins: ff.write(i[0] + ': ' + str(round(i[1][0], 1)) + ' ' + str(i[1][1]) + '\n') ff.write('#\n') ff.write('\n\n ' + str(original_len_coin_list) + ' stocks shortened by point system to ' + str(len(sorted_coins)) + ' stocks') ff.write("\n\n--- %s seconds ---" % (round(time.time() - start_time, 2))) ff.write('\n\n\n Capit-Vita Crypto Version 1.1 (2017-09-22)\n\n') ff.write(' - Buying is confirmed to work\n') ff.close() #print(self.volume_sum[-20:]) #print('average volume', sum(self.volume_sum)/len(self.volume_sum)) # median volumeto: 850k # send email if len(self.mailing_list) > 0: send_email(self.file_path, 'Top ' + str(self.num_coins) + ' Coin Prospects', self.mailing_list) ###### remove coin types I currently own my_coins = [x['Currency'] for x in self.B.get_balances()['result']] print('my coins: {}'.format(my_coins)) print('before: {}'.format([x[0] for x in sorted_coins])) sorted_coins = [x for x in sorted_coins if x[0] not in my_coins] print('after: {}'.format([x[0] for x in sorted_coins])) # save wanted coins with open(self.file_path + 'wanted_coins.txt', 'w') as f: f.write('{}, '.format([str(x[0]) for x in sorted_coins])) return sorted_coins def buy_next_coin(self): # save wanted_coins if os.path.isfile(self.file_path + 'wanted_coins.txt'): with open(self.file_path + 'wanted_coins.txt', 'r') as f: data = eval(f.readlines()[0][:-2]) else: return False print(data) def update_B(self): self.b_currencies = [ x['Currency'] for x in self.B.get_currencies()['result'] ] # currencies available to trade in bittrex self.market_summaries = self.B.get_market_summaries()['result'] self.markets = [x['MarketName'] for x in self.market_summaries] # market names self.BTC_markets = [ x for x in self.markets if 'BTC' in x and 'USDT' not in x ] self.ETH_markets = [ x for x in self.markets if 'ETH' in x and 'USDT' not in x ] self.USDT_markets = [x for x in self.markets if 'USDT' in x] self.USDT_BTC = [ x for x in self.market_summaries if x['MarketName'] == 'USDT-BTC' ][-1]['Last'] self.USDT_ETH = [ x for x in self.market_summaries if x['MarketName'] == 'USDT-ETH' ][-1]['Last'] #print len(self.b_currencies) # 277 as of 2017-09-21 def thing(self): BTC_market_prices = [] ETH_market_prices = [] ### create value exchange rate for currency in self.b_currencies: if any(currency in x for x in BTC_markets): last_price = [ x['Last'] for x in self.market_summaries if x['MarketName'] == 'BTC-{}'.format(currency) ] if len(last_price) > 0: BTC_market_prices.append('Last price for {} is ${}'.format( currency, round(last_price[0] * USDT_BTC, 2))) elif any(currency in x for x in ETH_markets): last_price = [ x['Last'] for x in self.market_summaries if x['MarketName'] == 'ETH-{}'.format(currency) ] if len(last_price) > 0: ETH_market_prices.append('Last price for {} is ${}'.format( currency, round(last_price[0] * USDT_ETH, 2))) cnt_in = 0 cnt_not_in = 0 for currency in self.b_currencies: if all(currency not in x for x in self.BTC_markets + self.ETH_markets): cnt_not_in += 1 #print('{} not in any market'.format(currency)) else: cnt_in += 1 #print(cnt_in, cnt_not_in) #203 in market, 74 out of market as of 2017-09-21 ### can only buy and sell on existing markets def my_coins(self): my_coins = [x for x in self.B.get_balances()['result']] print(my_coins) total = 0 print('\n\n----------- My Wallet -----------\n') for coin in my_coins: if coin['Currency'] == 'BTC': print('{} available for {} (${})'.format( coin['Available'], coin['Currency'], round(coin['Available'] * self.USDT_BTC, 2))) total += coin['Available'] * self.USDT_BTC elif any(coin['Currency'] in x for x in self.BTC_markets): BTC_coin_rate = [ x['Last'] for x in self.market_summaries if x['MarketName'] == 'BTC-{}'.format(coin['Currency']) ][0] print('{} available for {} (${})'.format( coin['Available'], coin['Currency'], round(coin['Available'] * self.USDT_BTC * BTC_coin_rate, 2))) total += coin['Available'] * self.USDT_BTC * BTC_coin_rate else: print('{} available for {} (${})'.format( coin['Available'], coin['Currency'], 'hold')) ## add ethereum #return summary return my_coins def total_available_USD(self, BTC_ETH_only=True): balances = self.B.get_balances()['result'] total_USD = 0 for balance in balances: if balance['Balance'] > 0: if balance['Currency'] == 'BTC': total_USD += balance['Balance'] * self.USDT_BTC print('BTC: {}'.format(balance['Balance'] * self.USDT_BTC)) elif balance['Currency'] == 'ETH': total_USD += balance['Balance'] * self.USDT_ETH print('ETH: {}'.format(balance['Balance'] * self.USDT_ETH)) elif not BTC_ETH_only: if any(balance['Currency'] in x for x in self.BTC_markets): to_add = balance['Balance'] * [ x['Last'] for x in self.market_summaries if x['MarketName'] == 'BTC-{}'.format(balance['Currency']) ][0] * self.USDT_BTC total_USD += to_add print('{}: {}'.format(balance['Currency'], to_add)) elif any(balance['Currency'] in x for x in self.ETH_markets): to_add = balance['Balance'] * [ x['Last'] for x in self.market_summaries if x['MarketName'] == 'ETH-{}'.format(balance['Currency']) ][0] * self.USDT_ETH total_USD += to_add print('{}: {}'.format(balance['Currency'], to_add)) # consider only BTC and ETH liquid? print('Total available: {}'.format(total_USD)) return total_USD def buy_altcoin(self, coin): if any(coin in x['Currency'] for x in self.B.get_balances()['result']): print('not buying, already have') return False if any(coin in x for x in self.BTC_markets): market = [x for x in self.BTC_markets if coin in x][0] print(market) available_USD = self.total_available_USD() print('available USD', available_USD) increment_USD = available_USD / 20 print('5% available USD: {}'.format(increment_USD)) BTC_coin_rate = self.B.get_marketsummary( market)['result'][0]['Last'] print('BTC - {} conversion: {}'.format(coin, BTC_coin_rate)) print('BTC - USD conversion: {}'.format(self.USDT_BTC)) print('want to buy {} {} coins'.format( increment_USD / self.USDT_BTC / BTC_coin_rate, coin)) print('buying {}: {}'.format( coin, self.B.buy_limit(market, increment_USD / self.USDT_BTC / BTC_coin_rate, BTC_coin_rate))) # market, quantity, rate def sell_altcoin(self, order): # takes a buy order and reverses it (sell) coin = order['Exchange'][4:] if any(coin in x for x in self.BTC_markets): market = [x for x in self.BTC_markets if coin in x][0] elif any(coin in x for x in self.ETH_markets): market = [x for x in self.ETH_markets if coin in x][0] coin_rate = self.B.get_marketsummary(market)['result'][0]['Last'] quantity = order['Quantity'] if all(coin not in x['Currency'] for x in self.B.get_balances()['result']): print('cannot sell, do not have') return False #print('selling {}: {}'.format(market, self.B.sell_limit(market, quantity, coin_rate))) # market, quantity, rate def coin_to_USD(self, order): coin = order['Exchange'][4:] market = [x for x in self.BTC_markets if coin in x][0] BTC_coin_rate = self.B.get_marketsummary(market)['result'][0]['Last'] if coin == 'BTC': return order['Quantity'] * self.USDT_BTC elif coin == 'ETH': pass elif any([coin in x for x in self.BTC_markets]): last_price = [ x['Last'] for x in self.market_summaries if coin in x['MarketName'] ] return order['Quantity'] * self.USDT_BTC * BTC_coin_rate elif any(coin in x for x in self.ETH_markets): pass else: pass def my_coin_price_change(self): orders = self.B.get_order_history()['result'] ## remove orders that I don't own orders = [x for x in orders] print(orders) self.update_B() for order in orders: bought_at = round( order['Quantity'] * order['PricePerUnit'] * self.USDT_BTC, 2) currently = round(self.coin_to_USD(order), 2) perc_change = round((currently / bought_at - 1) * 100, 1) timestamp = datetime.datetime.now() - datetime.datetime.strptime( order['TimeStamp'], '%Y-%m-%dT%H:%M:%S.%f') print( ' bought {} ({} ago) for relative BTC value of ${}, currently ${}: {}% change' .format(order['Exchange'][4:], timestamp, bought_at, currently, perc_change)) ### formula for selling: # cost of trade = 0.35% x 2 = 0.7% # have an open sell order at 10% -> 9.3% up # if simulataneous orders are possible, have an open sell order at -10% -> 10.7% down # if the coin is older than 5 days, lower the upper sell limit by 2% to 8% -> 7.3% up # every 3 days after that lower by 2% until @ 2% lower_limit = -10 if timestamp < datetime.timedelta(days=5): upper_limit = 10 elif timestamp < datetime.timedelta(days=8): # approx one week upper_limit = 8 elif timestamp < datetime.timedelta(days=11): upper_limit = 6 elif timestamp < datetime.timedelta(days=14): # two weeks upper_limit = 4 elif timestamp < datetime.timedelta(days=17): upper_limit = 2 elif timestamp > datetime.timedelta( days=21): # sell no matter what after 3 weeks upper_limit = -10 if perc_change < lower_limit or perc_change > upper_limit: self.sell_altcoin(order)
class CryptoCommander: def __init__(self, poloapicreds=['', ''], bittrexapicreds=['', '']): print( "Initializing Crypto Commander, Intelligent and Responsive Crypto-Currency Platform..." ) print( "Disclaimer!! You have launched this via command line, great caution is advised and the developers are NOT responsible for proper usage or lost coins!" ) print( "Notice - :: :: Bitcoin & Crypto-Currencies are largely untested and come with no assurances! Trade with care. :: ::" ) if poloapicreds == ['', '']: print( "No poloniex credentials found, skipping initialization. This may cause instability!" ) else: try: self.poloniexBot = poloniex(poloapicreds[0], poloapicreds[1]) self.btcBalance, self.btsBalance, self.clamBalance, self.dashBalance, self.dogeBalance, self.ethBalance, self.fctBalance, self.ltcBalance, self.maidBalance, self.strBalance, self.xmrBalance, self.xrpBalance, = Decimal( 0.0), Decimal(0.0), Decimal(0.0), Decimal(0.0), Decimal( 0.0), Decimal(0.0), Decimal(0.0), Decimal( 0.0), Decimal(0.0), Decimal(0.0), Decimal( 0.0), Decimal(0.0) except AttributeError: print( "An error occurred trying to initialize Poloniex functionality." ) if bittrexapicreds == ['', '']: print( "No bittrex credentials detected, skipping initialization. This may cause instability!" ) else: try: self.bittrexBot = Bittrex(bittrexapicreds[0], bittrexapicreds[1]) except AttributeError: print( "An error occurred trying to initialized Bittrex functionality." ) def convert_coinpair_poloniex(self, coinpair): return coinpair.replace('-', '_') def get_tickers_raw(self, market): # A clone of the bittrex get_markets() & poloniex returnTicker commands, in a unified stream. if market == 'poloniex': return self.poloniexBot.returnTicker() elif market == 'bittrex': return self.bittrexBot.get_markets() def get_coinpair_ticker_raw(self, market, coinpair): # Returns raw market information on coin pair on market if market == 'poloniex': coinpair = self.convert_coinpair_poloniex(coinpair) rawtickerdata = self.get_tickers_raw(market) for coinpairdata in rawtickerdata: if coinpairdata == coinpair: return rawtickerdata[coinpairdata] if market == 'bittrex': return self.bittrexBot.get_ticker(coinpair.capitalize()) def getTickerData(self, market, bitcoinMarketsOnly=True, activeOnly=True, printFriendly=False, decimalTypes=True): #if market == 'poloniex: if market == 'bittrex': cryptoCommandTickers = {'BTC': [], 'Other': []} btcMarketsList = cryptoCommandTickers['BTC'] otherMarketsList = cryptoCommandTickers['Other'] stagingList = [] if printFriendly == True: decimalTypes = False for ticker in self.bittrexBot.get_markets()['result']: if ticker != None: stagingList.append([ str(ticker['MarketName']), str(ticker['BaseCurrency']), bool(str(ticker['IsActive'])) ]) for ticker in self.bittrexBot.get_market_summaries()['result']: if ticker != None: for list in stagingList: if list[0] == str(ticker['MarketName']): list.extend([ ticker['High'], ticker['Low'], ticker['Ask'], ticker['Bid'], ticker['Last'], ticker['PrevDay'], ticker['Volume'], ticker['BaseVolume'], (ticker['High'] + ticker['Low'] / 2.0) ]) for list in stagingList: if list[1] == 'BTC': btcMarketsList.append(list) else: otherMarketsList.append(list) if printFriendly == True: for dictobject in cryptoCommandTickers: for list in cryptoCommandTickers[dictobject]: for n, listobject in enumerate(list): if type(listobject) == float: list[n] = format(listobject, '.8f') elif decimalTypes == True: for dictobject in cryptoCommandTickers: for list in cryptoCommandTickers[dictobject]: for n, listobject in enumerate(list): if type(listobject) == float: list[n] = Decimal(format(listobject, '.8f')) return cryptoCommandTickers def getActiveMarketCurrencies(self, market, appendString=''): currentMarketList = [] if market == 'poloniex': rawCoinPairData = self.poloniexBot.api_query('returnTicker') for coinPairData in rawCoinPairData: if str(rawCoinPairData[coinPairData]['isFrozen']) == '0': currentMarketList.append( str(coinPairData).split('_', 1)[1]) if market == 'bittrex': for coinData in self.bittrexBot.get_currencies()['result']: if coinData['IsActive'] == True: currentMarketList.append(appendString + str(coinData['Currency'])) return set(currentMarketList) def getCurrentBalance(self, market, coin): if market == 'poloniex': return self.poloniexBot.returnBalances()[coin.upper()] elif market == 'bittrex': return self.bittrexBot.get_balance(coin)['result']['Balance'] def getTopOrder(self, market, coinPair, buyOrders): if buyOrders == True: if market == 'poloniex': for i in self.poloniexBot.returnOrderBook( coinPair.replace('-', '_'))['bids']: return i elif market == 'bittrex': for i in self.bittrexBot.get_orderbook(coinPair, 'buy')['result']: return i else: print('Not a valid market: ' + str(market)) else: if market == 'poloniex': for i in self.poloniexBot.returnOrderBook( coinPair.replace('-', '_'))['asks']: return i elif market == 'bittrex': for i in self.bittrexBot.get_orderbook(coinPair, 'sell')['results']: return i else: print('Not a valid market: ' + str(market)) def getWalletAddress(self, market, coin): if market == "poloniex" or market == "Poloniex": return self.poloniexBot.api_query('returnDepositAddresses')[coin] elif market == "bittrex" or market == "Bittrex": return self.bittrexBot.get_balance(coin)['result']['CryptoAddress'] def compareMarkets(self, market1, market2): currentActiveMarketsLists = [ self.getActiveMarketCurrencies(market1), self.getActiveMarketCurrencies(market2) ] comparisonList = [] for i in currentActiveMarketsLists[0]: for y in currentActiveMarketsLists[1]: if i == y: comparisonList.append(i) else: continue return comparisonList def getCoinPairPriceDifferencePercent(self, buyPrice, sellPrice): return (((float(buyPrice) - float(sellPrice)) / float(buyPrice)) * 100.00) def arbitrageScan(self, market1, market2, minPercent=0.45): try: arbOpportunitiesList = [] for coinpair in self.doMarketComparison(market1, market2): print("Scanning Coin Pair : " + str(coinpair)) differenceBetweenMarket1and2 = format( self.getCoinPairPriceDifferencePercent( float(self.getTopOrder(market1, coinpair, False, 1)), float(self.getTopOrder(market2, coinpair, True, 1)))) differenceBetweenMarket2and1 = format( self.getCoinPairPriceDifferencePercent( float(self.getTopOrder(market2, coinpair, False, 1)), float(self.getTopOrder(market1, coinpair, True, 1)))) if float(differenceBetweenMarket2and1) < (-.525 - minPercent): if (float(self.getTopOrder(market1, coinpair, True)[0]) * float( self.getTopOrder(market1, coinpair, True)[1]) ) >= float(self.getCurrentBalance(market1, "BTC")): print("Arb Op: " + str(differenceBetweenMarket2and1) + " for coin pair ") print("Info: Bittrex: Buy:: ") print(self.getTopOrder('bittrex', coinpair, True)) print("- Sell:: ") print(self.getTopOrder('bittrex', coinpair, False)) arbOpportunity = (coinpair, "Market2to1", differenceBetweenMarket2and1, 1) arbOpportunitiesList.append(arbOpportunity) else: continue elif float(differenceBetweenMarket1and2) < (-.525 - minPercent): if float( self.getTopOrder('bittrex', coinpair, True, 3)[0] ) * float(self.getTopOrder( 'bittrex', coinpair, True)[1]) >= float( self.getCurrentBalance(market2, "BTC")): print("Arb Op: ") print(str(differenceBetweenMarket1and2)) print("Info: Bittrex: Buy:: ") print(self.getTopOrder('poloniex', coinpair, True)) print("- Sell:: ") print(self.getTopOrder('poloniex', coinpair, False)) print("Info: Poloniex: Buy:: ") print(self.getTopOrder('bittrex', coinpair, True)) print("- Sell:: ") print(self.getTopOrder('bittrex', coinpair, False)) arbOpportunity = (coinpair, "Market1to2", differenceBetweenMarket1and2, 1) arbOpportunitiesList.append(arbOpportunity) else: continue else: print(differenceBetweenMarket1and2 + " or " + differenceBetweenMarket2and1 + " is more than -.7") continue return arbOpportunitiesList except AttributeError: print("Attribute Error") def selectBestOpportunity(self, market1, market2, minPercent=0.45): opportunitiesList = [] while opportunitiesList == []: opportunitiesList = self.arbitrageScan(market1, market2, minPercent) if len(opportunitiesList) != 0: bestOpportunity = opportunitiesList[0] for opportunity in opportunitiesList: if bestOpportunity[2] < opportunity[2]: bestOpportunity = opportunity else: print("No Opportunities Found") bestOpportunity = ("", "", 0.0, 0) return bestOpportunity def activateArbitrage(self, market1, market2, minPercent=0.45): bestArbitrageOpportunity = self.selectBestOpportunity( market1, market2, minPercent) coinName = str(bestArbitrageOpportunity[0]).replace("BTC-", "") if bestArbitrageOpportunity[1] == 'Market1to2': fullTopBuyOrder = self.getTopOrder(market1, bestArbitrageOpportunity[0], False) btcBuyOrderAvailable = (float(fullTopBuyOrder[0]) * float(fullTopBuyOrder[1])) btcBalanceOnMarket = float( self.getCurrentBalance('poloniex', "BTC")) if float(btcBuyOrderAvailable) > float(btcBalanceOnMarket): btcBuyOrderAvailable = float(btcBalanceOnMarket) coinAvailable = float(btcBuyOrderAvailable) / float( fullTopBuyOrder[0]) if market1 == "poloniex" or market1 == "Poloniex": try: if float( self.getTopOrder( market1, bestArbitrageOpportunity[0], False, 0)[0]) * float( self.getTopOrder( market1, bestArbitrageOpportunity[0], False, 0)[1]) < float( self.getBalance('poloniex', 'BTC')): self.poloniexBot.buy( bestArbitrageOpportunity[0].replace("-", "_"), fullTopBuyOrder[0], coinAvailable) print( "Successfully Bought on Poloniex, Attempting to Send to Bittrex Now..." ) time.sleep(3) self.poloniexBot.withdraw( coinName, (self.getCurrentBalance('poloniex', coinName)), self.getWalletAddress('bittrex', coinName)) tempCounter = 0 print(self.getCurrentBalance('bittrex', coinName)) while float(self.getCurrentBalance( 'bittrex', coinName)) < 0.0005: time.sleep(5) tempCounter = tempCounter + 1 if tempCounter > 15: print("Still Awaiting Deposit...") tempCounter = 0 print( "Deposit Confirmed & Active! Preparing to Dump in 5 Seconds" ) time.sleep(5) while float(self.getCurrentBalance(market2, coinName) ) > 0.00050055 or self.getCurrentBalance( market2, coinName) == None: time.sleep(3) self.bittrexBot.sell_limit( bestArbitrageOpportunity[0], self.getCurrentBalance('bittrex', coinName), self.getTopOrder(market2, bestArbitrageOpportunity[0], True, 1)) print( "Finished Selling All the Coins that Could be Sold. Cycle Complete." ) else: print( "The order didnt stay high enough, starting over") self.activateArbitrage(market1, market2, minPercent) except MemoryError: print("Error") if bestArbitrageOpportunity[1] == 'Market2to1': fullTopBuyOrder = self.getTopOrder(market2, bestArbitrageOpportunity[0], False, 0) btcBuyOrderAvailable = (float(fullTopBuyOrder[0]) * float(fullTopBuyOrder[1])) btcBalanceOnMarket = float(self.getCurrentBalance(market2, "BTC")) if btcBuyOrderAvailable > btcBalanceOnMarket: btcBuyOrderAvailable = btcBalanceOnMarket coinAvailable = float(btcBuyOrderAvailable) / float( fullTopBuyOrder[0]) if market2 == "bittrex" or market2 == "Bittrex": try: if float( self.getTopOrder( market1, bestArbitrageOpportunity[0], False, 0)[0]) * float( self.getTopOrder( market1, bestArbitrageOpportunity[0], False, 0)[1]) < float( self.getCurrentBalance( 'bittrex', 'BTC')): print("Buying " + str(bestArbitrageOpportunity[0]) + " " + str(coinAvailable)) buy = self.bittrexBot.buy_limit( bestArbitrageOpportunity[0], coinAvailable, fullTopBuyOrder[0]) print(buy) time.sleep(5) if buy['success'] == True: print( "Successfully Bought on Bittrex, Attempting to Send to Poloniex Now..." ) time.sleep(5) self.bittrexBot.withdraw( coinName, self.getCurrentBalance(market2, coinName), self.getWalletAddress(market1, coinName)) tempCounter = 0 print(self.getCurrentBalance(market1, coinName)) while float( self.getCurrentBalance(market1, coinName) ) < 0.00050055 or self.getCurrentBalance( market1, coinName) == None: time.sleep(5) tempCounter = tempCounter + 1 if tempCounter > 15: print("Still Awaiting Deposit...") tempCounter = 0 print( "Deposit Confirmed and Active! Preparing to Dump in 5 Seconds" ) time.sleep(5) while float( self.getCurrentBalance( market1, coinName)) > 0.00010055: time.sleep(5) self.poloniexBot.sell( str(bestArbitrageOpportunity[0]).replace( "-", "_"), float( self.getTopOrder( market1, bestArbitrageOpportunity[0]. replace("-", "_"), True, 1)), self.getCurrentBalance(market1, coinName)) print( "Attempting to Sell Maximum Amount of Coins that Could be Sold." ) print("Finished Selling all coins. Cycle Complete") else: print("Failed to Buy") return "Failed to Buy" else: print( "The order didn't stay high enough, starting over") self.activateArbitrage(market1, market2, minPercent) except AttributeError: print("Attribute Error, sorry") def getLendingBalances(self): #Only works with Poloniex try: return cryptoCommander.poloniexBot.api_query( 'returnAvailableAccountBalances')['lending'] except KeyError: return [] def getCurrentLoanOffers(self, coin): #Only works with Poloniex ret = urllib2.request.urlopen('http://poloniex.com/public?command=' + 'returnLoanOrders' + '¤cy=' + str(coin)) return json.loads(ret.read()) def getPrimeLendingRate(self, coin, minWeight=Decimal('25.0')): #Only works with Poloniex accumulatedWeight, bestRate = Decimal('0.0'), Decimal('0.0') print(accumulatedWeight) for offer in self.getCurrentLoanOffers(coin)['offers']: if accumulatedWeight < minWeight: print('Accumulated weight is less than 25: ' + str(accumulatedWeight)) accumulatedWeight = accumulatedWeight + Decimal( str(offer['amount'])) else: print('Best rate is: ' + str(offer['rate'])) bestRate = Decimal(str(offer['rate'])) - Decimal('0.000001') break if bestRate < Decimal('0.000001'): bestRate = Decimal('0.000001') return bestRate def getActiveLoans(self): #Only works with Poloniex return self.poloniexBot.api_query('returnActiveLoans') def getOpenLoanOffers(self): #Only works with Poloniex try: return self.poloniexBot.api_query('returnOpenLoanOffers') except KeyError: return [] def cancelLoanOffer(self, currency, orderNumber): #Only works with Poloniex return self.poloniexBot.api_query('cancelLoanOffer', { "currency": currency, "orderNumber": orderNumber }) def cancelAllLoanOffers(self): openLoansDict = self.getOpenLoanOffers() for openLoanCoin in openLoansDict: for dataObject in openLoansDict[openLoanCoin]: self.cancelLoanOffer(openLoanCoin, dataObject[id]) def createLoanOffer(self, currency, amount, duration, autoRenew, lendingRate): return self.poloniexBot.api_query( 'createLoanOffer', { "currency": currency, "amount": amount, "duration": duration, "autoRenew": autoRenew, "lendingRate": lendingRate, }) def checkLendingStagnation(self): openLoansDict = self.getOpenLoanOffers() for openLoanCoin in openLoansDict: for data in openLoansDict[openLoanCoin]: if (datetime.datetime.utcnow() - datetime.datetime.strptime( str(data['date']), '%Y-%m-%d %X') > datetime.timedelta(minutes=2)): print('Cancelling Loan Orders that are stagnant.') self.cancelLoanOffer(openLoanCoin, data['id']) def placeAllLoans(self): balances = self.getLendingBalances() for coin in balances: try: print(balances[coin]) if type(balances[coin] ) != Decimal and balances[coin] > Decimal('0.0'): balances[coin] = Decimal(str(balances[coin])) if type(balances[coin] ) == Decimal and balances[coin] >= Decimal('0.01'): #print "Print currency available is: " + str(balances[coin]) + str(coin) + ", Lending Now." while Decimal(str(balances[coin])) >= Decimal('0.01'): if Decimal(str(balances[coin])) <= Decimal( '0.02') and Decimal(str( balances[coin])) >= Decimal('0.01'): print('lending between 0.01 and 0.02') print( self.createLoanOffer( coin, float(balances[coin]), 2, 0, self.getPrimeLendingRate(coin))) else: primeRate = self.getPrimeLendingRate(coin) print("Prime Rate is: " + str(primeRate)) if primeRate <= Decimal('0.000025') or Decimal( balances[coin]) > Decimal('0.1'): if Decimal(balances[coin]) >= Decimal('10.0'): if Decimal( balances[coin] ) < Decimal('20.0') and Decimal( balances[coin]) > Decimal('10.0'): print('lending between 10 and 20') print( self.createLoanOffer( coin, float(balances[coin]), 2, 0, primeRate)) else: print('lending 10') print( self.createLoanOffer( coin, 10.0, 2, 0, primeRate)) else: if Decimal( balances[coin]) > Decimal('0.1'): if Decimal(balances[coin]) < Decimal( '0.2') and Decimal( balances[coin]) > Decimal( '0.1'): print( 'lending between 0.1 and 0.2') print( self.createLoanOffer( coin, float(balances[coin]), 2, 0, primeRate)) else: print('lending 0.1') print( self.createLoanOffer( coin, 0.1, 2, 0, primeRate)) else: print('lending 0.01') print( self.createLoanOffer( coin, 0.01, 2, 0, primeRate)) else: print('lending 0.01') print( self.createLoanOffer( coin, 0.01, 2, 0, primeRate)) time.sleep(.2) balances = self.getLendingBalances() else: print('No coins available to lend, sorry!') except KeyError: print('All loans for ' + str(coin) + ' actively being lent.') def startLendingAutomation(self): while True: try: while self.getLendingBalances( ) != None and self.getOpenLoanOffers() != None: while any(self.getLendingBalances()) > Decimal( '0.001') or any(self.getOpenLoanOffers()): self.placeAllLoans() time.sleep(150) self.checkLendingStagnation() print('All Done.') except TypeError: print("NOT done")