def get_data(number): db_name = 'BB_coins' trader = get_arg(1) # 'LANDON', 'CHRISTIAN' OR 'VIVEK. # with open('accountkey.json') as data_file: # data = json.load(data_file) # print(data) collection_name = '{}_bittrex_account'.format(trader) try: mongoserver_uri = "mongodb://*****:*****@10.8.0.2:27017/admin" # mongoserver_uri = "mongodb://*****:*****@127.0.0:1" connection = MongoClient(host=mongoserver_uri) db = connection['BB_coins'] db_collection = db[collection_name] except KeyError: host = 'localhost' db_collection = MyMongoClient(db_name, collection_name=collection_name, host=host) balance_curr_codes = [] market_names = [] # key, secret = "141172172c12458f8d0051d4c2618559", "2d944113b64844f2b3ad33030f99101a" key = get_arg(2) secret = get_arg(3) api = Bittrex(api_key=key, api_secret=secret) markets_data = api.get_markets()["result"] for markets_datum in markets_data: if markets_datum["BaseCurrency"] == 'BTC': balance_curr_codes.append(markets_datum["MarketCurrency"]) market_names.append(markets_datum["MarketName"]) for market_name in market_names: market_history_data = api.get_market_history(market_name, count=1)["result"][0] balance_curr_code = market_name.split('-')[1] json_data = ({ 'Number': number, 'balance_curr_code': balance_curr_code, 'last_price': market_history_data['Price'], 'TimeStamp': market_history_data['TimeStamp'] }) db_collection.insert_one(json_data) print('------table name-----') print(collection_name) print('Inserted: \n{}'.format(json_data))
def hist_fetch(a): global my_bitterx, history_store, markets print("Thread 1 started") while True: for store in history_store: if store["market"] == a: akt_hist = Bittrex.get_market_history( my_bitterx, a, 200)["result"] #get history for every market if akt_hist: akt_hist.reverse() for element in akt_hist: try: element = Hist_element(element['Id'], element['Quantity'], element['Price'], datetime.strptime( element['TimeStamp'], '%Y-%m-%dT%H:%M:%S.%f' )) #get required fields #print(element) except ValueError: element = Hist_element( element['Id'], element['Quantity'], element['Price'], datetime.strptime( element['TimeStamp'], '%Y-%m-%dT%H:%M:%S')) #get required fields lock.acquire() if element not in store["history"]: store["history"].append(element) #print(store["market"] + " added: "+str(element)) lock.release() lock.acquire() while (datetime.utcnow().timestamp() - store["history"][0].ts.timestamp()) > HISTORY: #print(str(history_store[i][0])) #print((history_store[i][0].ts.timestamp()-datetime.utcnow().timestamp())/60) store["flag"] = True store["history"].pop(0) if len(store["history"]) == 0: break print(store["market"] + ": " + str(len(store["history"]))) #print((datetime.utcnow().timestamp()-history_store[i][len(history_store[i])-1].ts.timestamp())/60) #print((datetime.utcnow().timestamp()-history_store[i][0].ts.timestamp())/60) lock.release() time.sleep(20)
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')
def get_data(): db_name = 'BB_coins' trader = get_arg(1, 'VIVEK') # 'LANDON', 'CHRISTIAN' OR 'VIVEK. collection = '{}_coinigy_account'.format(trader) try: db_user = '******' db_password = os.environ['MONGO-WRITE-PASSWORD'] host = 'mongodb://{}:{}@127.0.0.1'.format(db_user, db_password) except KeyError: host = 'localhost' db = MyMongoClient(db_name, collection_name=collection, host=host) json_data = [] market_history_total_data = [] balance_curr_codes = [] market_names = [] key, secret = "54680684a8cb481c9f99a5f0ccaa1841", "4009a8a233114ab8a16f03c856d03752" api = Bittrex(api_key=key, api_secret=secret) markets_data = api.get_markets()["result"] for markets_datum in markets_data: if markets_datum["BaseCurrency"] == 'BTC': balance_curr_codes.append(markets_datum["MarketCurrency"]) market_names.append(markets_datum["MarketName"]) for market_name in market_names: market_history_data = api.get_market_history(market_name, count=1)["result"][0] balance_curr_code = market_name.split('-')[1] json_data = ({ 'balance_curr_code': balance_curr_code, 'last_price': market_history_data['Price'], 'TimeStamp': market_history_data['TimeStamp']}) db.insert_one(json_data)
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)
def mainrun(): if Path(PATH+'currencyretain.pickle').is_file(): remaining = pickle.load(open(PATH+'currencyretain.pickle','rb')) else: remaining = OrderedDict() BTX = Bittrex(key=apikey,secret=apisecret) blockPrint() balances = BTX.get_balances()['result'] orders = BTX.get_open_orders()['result'] enablePrint() waitingon = [] for ORDS in orders: EX = ORDS["Exchange"] TYPE = ORDS["OrderType"] if (SelltoCurrency in EX) and ('BUY' in TYPE): continue elif (orderwait==1) and (SelltoCurrency not in EX): EX = EX.replace(SelltoCurrency+'-','') EX = EX.replace('-'+SelltoCurrency,'') if EX not in EX: waitingon.append(EX) else: continue for BAL in balances: Currency = BAL["Currency"] Available = BAL["Available"] if Currency in retainspec.keys(): retained = retainspec[Currency] else: retained = retainednorm if retentionROI == 1: ROI = 1.00 + retained + retained**2 + retained**3 + retained**4 else: ROI = ROI if Currency in remaining.keys(): CurrencyHold = remaining[Currency] Available = Available - CurrencyHold else: CurrencyHold = 0.00 if (Currency not in waitingon) and (Currency != SelltoCurrency) and ( (Available + CurrencyHold) > (CurrencyHold + Minimumtradeorder) ): Quantitytosell = (Available-(retained*Available)) blockPrint() price = BTX.get_market_history(SelltoCurrency+'-'+Currency)['result'][0]["Price"] enablePrint() #Take into account the initial fee zerofeeamount = ( price ) / (1-bidFee) Netprice = (zerofeeamount*ROI) / (1-askFee) if (Quantitytosell*price) > Minimumtradeorder: BTX.sell_limit(SelltoCurrency+'-'+Currency,Quantitytosell,Netprice) #Make sure to 'Hold' the amount remaining until it goes above this amount. remaining[Currency] = retained*Available + CurrencyHold pickle_out = open(PATH+'currencyretain.pickle','wb') pickle.dump(remaining,pickle_out) pickle_out.close() else: print("Minimum Trade order is: "+ str(Minimumtradeorder) + " " + SelltoCurrency + ", You tried to sell: " + str(Quantitytosell*price) + " " + SelltoCurrency + " Worth.")
cursor.execute("select * from btxmarkethistory") rows = cursor.fetchall() colnames = [desc[0] for desc in cursor.description] # print(colnames) #set API key bittrex = Bittrex('e281fee0429e428b9a76f63cc842f12d', 'a131b56ec7f24696a74c6b6da853d1eb') #get balance - just to test integration actual = bittrex.get_balance('BTC') dataTuple = [] for value in coinsToWatch: ## get various market summaries specificMarketHistory = bittrex.get_market_history( (market + '-' + str(value)), 30) # print(str(marketSummary['result'])) if specificMarketHistory['success'] == True: for valuetwo in specificMarketHistory['result']: currentTime = datetime.now() previousMinuteTime_nonFormat = currentTime - timedelta( minutes=1) previousMinuteReplaceSeconds = previousMinuteTime_nonFormat.replace( second=0, microsecond=0) currMinuteTime_nonFormat = currentTime currMinuteTimeReplaceSeconds = currMinuteTime_nonFormat.replace( second=0, microsecond=0) strippedMSIdx = str(valuetwo['TimeStamp']).find(".") parsedTime = ""
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 history = my_bittrex.get_market_history('BTC-LTC') historydf = pd.DataFrame.from_dict(history['result']) print historydf.head()
names = filter_market_names(list(x)) markets = list() time0 = get_t0_time() n = len(names) print("Now is {} by UTC".format(str(datetime.utcnow()))) print("t0 is {} by UTC".format(str(time0))) s = "Downloading of {} markets histories have launched. Please wait." print(s.format(n)) i = 0 for name in names: x = Market() x.name = name response = bittrex_client.get_market_history(name) h = History.load_from_web_list(response['result']) x.history = h markets.append(x) i+=1 if REPORT_PROGRESS: s = "{}: {} of {} request have done [{:.0f}%]" print(s.format(str(datetime.now()), i, n, 100*i/n)) for m in markets: q = 0 for op in m.history.operations: if (type(op) is Buy_op) and (time0 <= op.date): q+=1
class Market(object): """ Used to provide analysis of a market on Bittrex. """ def __init__(self, name, bittrex=None): """ :param name: String literal for the market (e.g. BTC-LTC) :type name: str :param bittrex: Instance of Bittrex, potentially with API_KEY and SECRET :type bittrex: Bittrex """ self.name = name self.basis, self.coin = self.name.split("-") if bittrex: self.bittrex = bittrex else: self.bittrex = Bittrex(None, None) @property def summary(self): response = self.bittrex.get_market_summary(self.name) if response['success']: return response['result'][0] raise Exception("Could not retrieve data from Bittrex: {:s}".format( response['message'])) @property def history(self): response = self.bittrex.get_market_history(self.name) if response['success']: df = pd.DataFrame(response['result']) df["TimeStamp"] = pd.to_datetime(df["TimeStamp"]) return df raise Exception("Could not retrieve data from Bittrex: {:s}".format( response['message'])) def _get_orderbook(self, depth_type, depth=20): response = self.bittrex.get_orderbook(self.name, depth_type, depth) if response['success']: return pd.DataFrame(response['result']) raise Exception("Could not retrieve data from Bittrex: {:s}".format( response['message'])) def get_buy_orderbook(self, depth=20): return self._get_orderbook(BUY_ORDERBOOK, depth) def get_sell_orderbook(self, depth=20): return self._get_orderbook(SELL_ORDERBOOK, depth) def get_both_orderbooks(self, depth=20): response = self.bittrex.get_orderbook(self.name, BOTH_ORDERBOOK, depth) if response['success']: return (pd.DataFrame(response['result']['buy']), pd.DataFrame(response['result']['sell'])) raise Exception("Could not retrieve data from Bittrex: {:s}".format( response['message'])) @property def ticker(self): response = self.bittrex.get_ticker(self.name) if response['success']: return response['result'] raise Exception("Could not retrieve data from Bittrex: {:s}".format( response['message'])) def get_price_time_series(self): return self.history[["TimeStamp", "Price"]] def __str__(self): return "{:s}\t{:s}".format(self.name, str(self.ticker))