def test_handles_invalid_key_or_secret(self): self.bittrex = Bittrex('invalidkey', self.secrets['secret'], api_version=API_V2_0) actual = self.bittrex.get_balance('BTC') test_auth_basic_failures(self, actual, 'Invalid key, valid secret') self.bittrex = Bittrex(None, self.secrets['secret'], api_version=API_V2_0) actual = self.bittrex.get_balance('BTC') test_auth_basic_failures(self, actual, 'None key, valid secret') self.bittrex = Bittrex(self.secrets['key'], 'invalidsecret', api_version=API_V2_0) actual = self.bittrex.get_balance('BTC') test_auth_basic_failures(self, actual, 'valid key, invalid secret') self.bittrex = Bittrex(self.secrets['key'], None, api_version=API_V2_0) actual = self.bittrex.get_balance('BTC') test_auth_basic_failures(self, actual, 'valid key, None secret') self.bittrex = Bittrex('invalidkey', 'invalidsecret', api_version=API_V2_0) actual = self.bittrex.get_balance('BTC') test_auth_basic_failures(self, actual, 'invalid key, invalid secret')
def scrape(chunk=1, ticker_interval=TICKINTERVAL_HOUR): producer = KafkaProducer(bootstrap_servers=rose_host) for coin in coins[(chunk - 1) * 10:chunk * 10]: market = 'BTC-' + coin["symbol"] if coin["symbol"] == 'BTC': market = 'USDT-' + coin["symbol"] bittrex = Bittrex(os.environ['CRYPTOEYES_KEY'], os.environ['CRYPTOEYES_SEC']) bittrexv2 = Bittrex(os.environ['CRYPTOEYES_KEY'], os.environ['CRYPTOEYES_SEC'], api_version=API_V2_0) # histories = bittrex.get_market_history(market) if last == "True": candles = bittrexv2.get_latest_candle(market, ticker_interval) else: candles = bittrexv2.get_candles(market, ticker_interval) if candles.get("success") == True and candles.get( "result") is not None: topic = 'bittrex.' + market + '.candle.' + ticker_interval + '.' + partition for can in candles["result"]: producer.send(topic, json.dumps(can).encode()) else: print(market, candles) print("there're " + str(len(coins)) + " of coins are tracking.")
def set_buy_point(market_, price, money, price_offset_factor = 0.99): from bittrex.bittrex import Bittrex, API_V1_1, API_V2_0 API_V20 = Bittrex('','',api_version=API_V2_0) API_V11 = Bittrex('','',api_version=API_V1_1) # place a buy order, price could be lower than macd price buy_price = price*price_offset_factor buy_amount = money/buy_price while(1): text = '>>>>>>>>>>>' + market_ + ": place a buy order of amount of" + str(buy_amount) + "@$" + str(buy_price) print(text) # place order(market_, price, amount) # check respond # take care of double order if (1): break # leave a record buy_set_info = dict() buy_set_info['market_'] = market_ buy_set_info['price'] = buy_price buy_set_info['amount'] = buy_amount buy_set_info['activity'] = 'buy_set' buy_set_info['time'] = API_V11.get_marketsummary(market='USDT-OMG')['result'][0]['TimeStamp'] return buy_set_info
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") self.assertTrue(actual['success'], "failed with None key")
def __init__(self, session): """ Costructor method. Args: session (sqlalchemy.orm.session.Session): Connection to the database. """ OhlcvBaseClass.__init__(self, session = session) self.bittrex = Bittrex(api_key = "APIKEY", api_secret = "SECRETKEY", api_version = API_V1_1) self.bittrex2 = Bittrex(api_key = "APIKEY", api_secret = "SECRETKEY", api_version = API_V2_0)
def get_markets_list(base_coin = 'USDT'): from bittrex.bittrex import Bittrex, API_V1_1, API_V2_0 API_V20 = Bittrex('','',api_version=API_V2_0) API_V11 = Bittrex('','',api_version=API_V1_1) markets_list = [] market_sum = API_V20.get_market_summaries() markets_all_list = market_sum['result'] for market_ in markets_all_list: if market_['Market']['BaseCurrency'] == base_coin: markets_list.append(market_['Market']['MarketName']) return markets_list
def __init__( self, n_coins=20, cap=0.1, mcap_limit=50, min_trade_limit=0.001): self.BITTREX_API_KEY = os.getenv('BITTREX_API_KEY') self.BITTREX_API_SECRET = os.getenv('BITTREX_API_SECRET') self.coinmarketcap = Market() self.v1_bittrex = Bittrex('', '', api_version=API_V1_1) self.v2_bittrex = Bittrex( self.BITTREX_API_KEY, self.BITTREX_API_SECRET, api_version=API_V2_0) self.blacklist = pd.Series(['USDT', 'BCC']) self.n_coins = n_coins self.cap = cap self.mcap_limit = mcap_limit self.min_trade_limit = min_trade_limit
def getData(mercado, intervalo, bot, update, evento1, evento2): evento1.acquire() print("Empieza hilo 1") global contador1 try: texto = "[" + str( contador1 ) + "] ACTUALIZANDO EXCEL DE " + mercado + " CON INTERVALO " + intervalo bot.send_message(chat_id=update.message.chat_id, text=texto) except telegram.error.TimedOut: print("Ha habido un error enviando mensaje en getData") contador1 += 1 my_bittrex = Bittrex(None, None, api_version=API_V2_0) data = my_bittrex.get_candles(mercado, intervalo) """ data["result"] para limpiar los datos anteriores a result """ df = pd.DataFrame(data["result"]) df = df.rename(index=str, columns={ "BV": 'basevolume', "C": 'close', "H": 'high', "L": 'low', "O": 'open', "T": 'date', "V": '24hvolume' }) df.to_excel("data/" + mercado + ".xlsx") evento2.release() print("Se da paso a hilo 2")
def control(): my_bittrex = Bittrex(None, None, api_version=API_V2_0) data=my_bittrex.get_market_summaries() btcCount=0 ethCount=0 usdtCount=0 for i in range(0,len(data['result'])): if data['result'][i]['Summary']['MarketName'][0:4]=="BTC-": btc_fmarket=data['result'][i]['Summary']['MarketName'] btc_coinname=btc_fmarket[4:len(btc_fmarket)] query_btc=Coin.objects.filter(koin_name=btc_coinname) if len(query_btc)==0: Coin.objects.create(koin_name=btc_coinname) btcCount+=1 elif data['result'][i]['Summary']['MarketName'][0:4]=="ETH-": eth_fmarket=data['result'][i]['Summary']['MarketName'] eth_coinname=eth_fmarket[4:len(eth_fmarket)] query_eth=Coin.objects.filter(koin_name=eth_coinname) if len(query_eth)==0: Coin.objects.create(koin_name=eth_coinname) ethCount+=1 if data['result'][i]['Summary']['MarketName'][0:5]=="USDT-": usdt_fmarket=data['result'][i]['Summary']['MarketName'] usdt_coinname=usdt_fmarket[5:len(usdt_fmarket)] query_usdt=Coin.objects.filter(koin_name=usdt_coinname) if len(query_usdt)==0: Coin.objects.create(koin_name=usdt_coinname) usdtCount+=1 print(btcCount,"btc") print(ethCount,"eth") print(usdtCount,"usd")
def GetInformations(self, MarketName): BittRexCo = Bittrex(None, None) Data = BittRexCo.get_markets() if Data['success']: Res = Data['result'] for item in Res: if item['MarketName'] == MarketName: self.MarketName = item['MarketName'] self.MarketCurrency.GetInformation(item['MarketCurrency']) self.BaseCurrency.GetInformation(item['BaseCurrency']) self.MinTradeSize = item['MinTradeSize'] self.IsActive = item['IsActive'] self.Created = item['Created'] Data2 = BittRexCo.get_marketsummary(item['MarketName']) if Data2['success']: for item2 in Data2['result']: self.High = item2['High'] self.Low = item2['Low'] self.Last = item2['Last'] self.Volume = item2['Volume'] self.BaseVolume = item2['BaseVolume'] self.TimeStamp = item2['TimeStamp'] self.Bid = item2['Bid'] self.Ask = item2['Ask'] self.OpenSellOrders = item2['OpenSellOrders'] self.OpenBuyOrders = item2['OpenBuyOrders'] self.PrevDay = item2['PrevDay'] return True return False
def __init__(self): """ Costructor method. """ ExchangeBaseClass.__init__(self) self.bittrex = Bittrex(api_key=None, api_secret=None)
def init(config: dict) -> None: """ Initializes this module with the given config, it does basic validation whether the specified exchange and pairs are valid. :param config: config to use :return: None """ global _API, EXCHANGE _CONF.update(config) if config['dry_run']: logger.info('Instance is running with dry_run enabled') use_bittrex = config.get('bittrex', {}).get('enabled', False) if use_bittrex: EXCHANGE = Exchange.BITTREX _API = Bittrex(api_key=config['bittrex']['key'], api_secret=config['bittrex']['secret']) else: raise RuntimeError('No exchange specified. Aborting!') # Check if all pairs are available markets = get_markets() exchange_name = EXCHANGE.name.lower() for pair in config[exchange_name]['pair_whitelist']: if pair not in markets: raise RuntimeError('Pair {} is not available at {}'.format( pair, exchange_name))
def __init__(self, config: dict): """ Initializes the ApiWrapper with the given config, it does basic validation whether the specified exchange and pairs are valid. :param config: dict """ self.dry_run = config['dry_run'] if self.dry_run: logger.info('Instance is running with dry_run enabled') use_poloniex = config.get('poloniex', {}).get('enabled', False) use_bittrex = config.get('bittrex', {}).get('enabled', False) if use_poloniex: self.exchange = Exchange.POLONIEX self.api = Poloniex(key=config['poloniex']['key'], secret=config['poloniex']['secret']) elif use_bittrex: self.exchange = Exchange.BITTREX self.api = Bittrex(api_key=config['bittrex']['key'], api_secret=config['bittrex']['secret']) else: self.api = None raise RuntimeError('No exchange specified. Aborting!') # Check if all pairs are available markets = self.get_markets() for pair in config[self.exchange.name.lower()]['pair_whitelist']: if pair not in markets: raise RuntimeError( 'Pair {} is not available at Poloniex'.format(pair))
def setUp(self): with open("secrets.json") as secrets_file: self.secrets = json.load(secrets_file) secrets_file.close() self.bittrex = Bittrex(self.secrets['key'], self.secrets['secret'], api_version=API_V2_0)
def get_post(self, post): if not post.author or post.author != self.author: return kwargs = {'author': post.author, 'permlink': post.slug} try: blockchain_post = Post(post=kwargs, steemd_instance=self.steem) except: return votes = blockchain_post.get( 'net_votes') # len(post.get('active_votes')) post.votes = votes # pending reward reward_pending_amount = blockchain_post.get( 'total_pending_payout_value') amount = reward_pending_amount.get('amount') asset = reward_pending_amount.get('asset') if amount > 0: post.reward = amount self.set_asset(post, asset) # payouts reward total_payout_value = blockchain_post.get('total_payout_value') amount = total_payout_value.get('amount') asset = total_payout_value.get('asset') self.set_asset(post, asset) if amount > 0: post.reward = amount post.complete = True if not post.reward: post.save() return if post.provider == 'golos': # calc BTC local_course = self.get_local_course() if local_course: base_course = local_course.get('base') if base_course: gbg_course = float(base_course.split(' ')[0]) gbg_golos = post.reward / gbg_course api = Bittrex(settings.BITTREX_KEY, settings.BITTREX_SECRET) btc_cost = api.get_ticker('BTC-GOLOS').get('result').get( 'Ask') post.btc = btc_cost * gbg_golos # calc RUB reward rub_course = Coinapult().get_current_price(currency='RUB') post.rub = post.btc * float(rub_course) else: return # TODO set it for steem post.save()
def scrape(chunk=1): producer = KafkaProducer(bootstrap_servers=rose_host) for coin in coins[(chunk - 1) * 10:chunk * 10]: bittrex_market = 'BTC-' + coin["symbol"] bnb_market = coin["symbol"] + 'BTC' if coin["symbol"] == 'BTC': bittrex_market = 'USDT-' + coin["symbol"] bnb_market = coin["symbol"] + ' USDT' bnb_client = Client(os.environ['BNB_CRYPTOEYES_KEY'], os.environ['BNB_CRYPTOEYES_SEC']) bittrex = Bittrex(os.environ['BTX_CRYPTOEYES_KEY'], os.environ['BTX_CRYPTOEYES_SEC']) bittrexv2 = Bittrex(os.environ['BTX_CRYPTOEYES_KEY'], os.environ['BTX_CRYPTOEYES_SEC'], api_version=API_V2_0) histories = bittrex.get_market_history(bittrex_market) if histories.get("success") == True and histories.get( "result") is not None: hist_lenght = len(histories["result"]) - 1 topic = 'bittrex.' + bittrex_market + '.history' print(topic) check_point = r.get(topic + '.check_point') for i in range(hist_lenght, -1, -1): hist = histories["result"][i] if check_point is None or hist["Id"] > int(check_point): producer.send(topic + '.' + partition, json.dumps(hist).encode()) r.set(topic + '.check_point', histories["result"][hist_lenght]["Id"]) else: try: histories = bnb_client.get_historical_trades(symbol=bnb_market) hist_lenght = len(histories) - 1 topic = 'binance.' + bnb_market + '.history' print(topic) check_point = r.get(topic + '.check_point') for i in range(hist_lenght): hist = histories[i] if check_point is None or hist["id"] > int(check_point): producer.send(topic + '.' + partition, json.dumps(hist).encode()) r.set(topic + '.check_point', histories[hist_lenght]["id"]) except Exception as e: print(e) print("there're " + str(len(coins)) + " of coins are tracking.")
def Test(key, secret, market, coinname): # threading.Timer(10, Test, args=(key, secret, market, coinname)).start() TestTrading = Bittrex(key, secret) t = TestTrading.get_ticker(market) #balance = TestTrading.get_balance(coinname) bid = t['result']['Bid'] print("| Bid | {: .8f} ".format(bid)) return bid
def PlaceSellOrder(self, market, quantity, rate): BittRexCo = Bittrex(self.apikey, self.apisecret) Data = BittRexCo.sell_limit(market, quantity, rate) if not Data['success']: print(Data['message']) return Data['success']
def __init__(self, config, verbosity=2): super(BittrexClient, self).__init__() api_key = config['api_key'] secret = config['secret'] self.transaction_fee = float(config['transaction_fee']) self.bittrex = Bittrex(api_key, secret) self.pair_delimiter = '-' self.verbosity = verbosity
def __init__(self): self._client = Bittrex(api_key=os.getenv('bittrex_api_key'), api_secret=os.getenv('bittrex_api_secret')) r = self._client.get_balances() if not r.get('success'): if r.get('message') == 'APIKEY_INVALID': raise Exception('Invalid API Keys') raise Exception('Error: ' + r.get('message'))
def login(*args): try: # value = apikey.get() bittrex = Bittrex(apikey.get(), apisecret.get()) print(bittrex.get_balances()) # meters.set((0.3048 * value * 10000.0 + 0.5) / 10000.0) except ValueError: pass
def __init__(self, api_key=None, api_sec=None): self.orders = {} self.min_trades = {} self.api = Bittrex(api_key, api_sec, api_version=API_V1_1) self.invest = 0 self.balance = 0. self.trades = {'act': 0, 'buy': 0, 'sell': 0, 'lose': 0} self.last_tick = time.time()
def __init__(self, key, secret): self.__apiKey = key self.__apiSecret = secret self.__apiVersion = API_V1_1 self.__bittrex = Bittrex(self.__apiKey, self.__apiSecret, api_version=self.__apiVersion)
def TradingAlorythm(command, market, amount, coinname, step, stoploss, key, secret): TestTrading = Bittrex(key, secret) period = timedelta(seconds=20) next_tick = datetime.now() + period seconds = 20 firstCycle = True if command == "y": print("buying {0} of {1} coins".format(amount, coinname)) # раскомментировать для созадния ордера на покупку # TestTrading.buy_limit(market, amount, coinprice) while command == "y": # таймер каждые 20 секунд if next_tick <= datetime.now(): print("Connecting to Bittrex") seconds += 20 next_tick += period print("Timer ticked") print("Updating stock exchange...") # Считываем значения курса t = TestTrading.get_ticker(market) # Запрашиваем баланс balance = TestTrading.get_balance(coinname) # Запрашиваем текущие ордера orders = TestTrading.get_open_orders(market) a = json.dumps(t) # Печатаем значения курса print(t) # Печатаем баланс print("Balance is {} ".format(balance['result']['Available'])) # Печатаем ордера print(orders) # Раскладываем по переменным bid = t['result']['Bid'] ask = t['result']['Ask'] last = t['result']['Last'] if firstCycle: StartValue = bid firstCycle = False Stop_loss = StartValue - 0.00000007 print("*--------------------------") print("| Start Value | {: .8f} ".format(StartValue)) print("| Stop loss | {: .8f} ".format(Stop_loss)) print("|--------------------------") print("| Bid | {: .8f} ".format(bid)) print("| Ask | {: .8f} ".format(ask)) print("| Last | {: .8f} ".format(last)) print("*--------------------------") # Добавляем Bid в конец массива # A.append(float(bid)) if bid >= step + StartValue: print("MOVE STOP-LOSS") StartValue = bid if bid <= stoploss: print("Sell order sent")
def __init__(self): args = self.arg_parser.parse_known_args()[0] super(BittrexClient, self).__init__() api_key = args.bittrex_api_key secret = args.bittrex_secret self.transaction_fee = float(args.bittrex_txn_fee) self.bittrex = Bittrex(api_key, secret) self.pair_delimiter = '-' self.verbosity = args.verbosity
def bittrex(market='BTC-XLM'): global API bittrex = Bittrex(None, None, api_version=API) ticket_bittrex = bittrex.get_ticker(market)['result'] print("Ask : " + FORMAT.format(ticket_bittrex['Ask']) + " Bid : " + FORMAT.format(ticket_bittrex['Bid'])) ask_Bittrex = ticket_bittrex['Ask'] bid_Bittrex = ticket_bittrex['Bid'] return ask_Bittrex, bid_Bittrex
def __init__(self, auth=False): if auth: with open('bittrex.key') as kfile: api_key = kfile.readline().strip() api_secret = kfile.readline().strip() else: api_key = None api_secret = None self.conn = Bittrex(api_key, api_secret, api_version=API_V2_0)
def __init__(self, **kwargs): api_key = kwargs["api_key"] api_secret = kwargs["api_secret"] if not all([api_key, api_secret]): raise Exception( f"Both api_key and api_secret are required for {name} exchange") self.client = Bittrex(api_key, api_secret, API_V1_1) self.debug_mode = environ.get("DEBUG", False)
def SetupBittrex(secrets_file_path = None): if (secrets_file_path is None): secrets_file_path = "bittrex-sec.json" with open(secrets_file_path) as secrets_file: secrets = json.load(secrets_file) secrets_file.close() return Bittrex(secrets['key'], secrets['secret']) return None
def __init__(self, marketPair, riskPercent): self.client = Bittrex(API_KEY, API_SECRET) self.marketPair = marketPair self.riskPercent = riskPercent self.tickerData = self.client.get_ticker(marketPair) self.currentPrice = self.tickerData.get('result').get('Last') self.highPrice = self.currentPrice self.priceDifference = 0 self.limitPrice = round((self.currentPrice * (1 - self.riskPercent)), 8)