def bittrexData(): betime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) try: bittrex = ccxt.bittrex() coindata = list(bittrex.fetch_tickers().values()) columns = ['symbol', 'ask', 'bid', 'close', 'last', 'high', 'low', 'info', 'datetime'] df = pd.DataFrame(coindata) df = df[columns] df['exchange'] = 'bittrex' df['vol'] = [i['Volume'] for i in df['info']] df['datetime'] = [i.replace('T', ' ') for i in df['datetime']] df['datetime'] = [i.replace('Z', '') for i in df['datetime']] df = df.drop(['info'], axis=1) df['basecurrency'] = list(i.split('/')[0] for i in df['symbol']) df['quotcurrency'] = list(i.split('/')[1] for i in df['symbol']) df['createtime'] = starttime df['codeid'] = 2 try: engine = create_engine("mysql+pymysql://coin:[email protected]:3306/coindata?charset=utf8") df.to_sql('coindata_tickers', con=engine, if_exists='append', index=False) except: with open('coindataerr.log','a') as f: f.write('%s:bittrex数据入库失败!\n' % betime) pass except: with open('coindataerr.log','a') as f: f.write('%s:bittrex数据获取失败!\n' % betime) pass
def __init__(self): self.market = Market(ccxt.bittrex({ 'apiKey': config.api_key, 'secret': config.secret, }), 'XMR/BTC') self.agent = DRQN() self.live = False
def main(): now = datetime.now() # Get markets exchange = ccxt.bittrex() markets = exchange.fetch_tickers() print('Number of markets={}'.format(len(markets))) # Bitcoin bitcoin = dict(markets.pop('BTC/USDT'), symbol='BTC') pprint(bitcoin) # Altcoins altcoins = [ dict(v, symbol=k.split('/')[0]) for k, v in markets.items() if '/BTC' in k ] # Sort by quoteVolume (Note: quoteVolume might be None, so 'or 0') altcoins.sort(key=lambda x: float(x['quoteVolume'] or 0), reverse=True) pprint(altcoins) print('Number of altcoins={}'.format(len(altcoins))) print([x['symbol'] for x in altcoins]) # Save coin data to MongoDB collection = MongoClient().bittrex['tickers'] # TODO: [bitcoin] + altcoins[:100], if you want save bitcoin and top 100 altcoins for coin in [bitcoin] + altcoins: coin['timestamp'] = datetime.fromtimestamp(coin['timestamp'] / 1000) collection.insert_one(coin) # Cleanup collection.remove( {'last_updated': { '$lt': now - timedelta(hours=24 * 10) }})
def main(): console.log('Starting...') exchanges['bitstamp'] = Exchange( ccxt.bitstamp(config=config.bitstamp.to_dict())) exchanges['binance'] = Exchange( ccxt.binance(config=config.binance.to_dict())) exchanges['bittrex'] = Exchange( ccxt.bittrex(config=config.bittrex.to_dict())) exchanges['cryptopia'] = Exchange( ccxt.cryptopia(config=config.cryptopia.to_dict())) exchanges['hitbtc'] = Exchange( ccxt.hitbtc2(config=config.hitbtc.to_dict())) telebot.add_handler( telegram.CommandHandler(command='balance', callback=TelegramCommands.get_balance)) telebot.add_handler( telegram.CommandHandler(command='start', callback=TelegramCommands.start)) telebot.add_handler( telegram.CommandHandler(command='help', callback=TelegramCommands.show_help)) telebot.start() console.log('Ready...') telebot.idle()
def __init__(self): #try except #Initiate exchange data with objects for each exchange binance = ccxt.binance() bittrex = ccxt.bittrex() bitfinex = ccxt.bitfinex() kraken = ccxt.kraken() kucoin = ccxt.kucoin() #Dictionary with the ccxt objects self.exchanges = { 'binance': binance, 'bittrex': bittrex, 'bitfinex': bitfinex, 'kraken': kraken, 'kucoin': kucoin } #Get a list of tickers from Binance exchange to use throughout self.ticker_list = [] self.get_tickers_list() #CREATE A DATAFRAME FOR THE PRICE AND VOLUME DATA self.volume = pd.DataFrame(index=self.ticker_list, columns=list(self.exchanges.keys())) self.pricedf = pd.DataFrame(index=self.ticker_list, columns=list(self.exchanges.keys())) self.spread = pd.DataFrame(index=self.ticker_list, columns=list(self.exchanges.keys()))
def add_price_table(exchange="binance"): ## API Key and Secret Key api = "" secret = "" exchange_obj = None if exchange == "binance": exchange_obj = ccxt.binance({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['bidPrice']) ask_price = float(cur_data['info']['askPrice']) cur_time = cur_data['timestamp'] elif exchange == "cryptopia": exchange_obj = ccxt.cryptopia({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['BidPrice']) ask_price = float(cur_data['info']['AskPrice']) cur_time = cur_data['timestamp'] elif exchange == "bittrex": exchange_obj = ccxt.bittrex({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['Bid']) ask_price = float(cur_data['info']['Ask']) cur_time = cur_data['timestamp'] elif exchange == "hitbtc": exchange_obj = ccxt.hitbtc2({ 'proxies': { 'http': 'http://*****:*****@us-wa.proxymesh.com:31280', 'https': 'http://*****:*****@us-wa.proxymesh.com:31280', }, 'apiKey': api, 'secret': secret, }) cur_data = exchange_obj.fetch_ticker(coin_pair) bid_price = float(cur_data['info']['bid']) ask_price = float(cur_data['info']['ask']) cur_time = cur_data['timestamp'] else: print("Unsupported Exchange platform") return
def create_exchanges(): """ instantiate the markets to include more exchanges use this function. new exchanges need to be hand-coded here """ coinbasepro = ccxt.coinbasepro({ 'apiKey': api_keys.coinbasepro['apiKey'], 'secret': api_keys.coinbasepro['secret'], }) poloniex = ccxt.poloniex({ 'apiKey': api_keys.poloniex['apiKey'], 'secret': api_keys.poloniex['secret'], }) bittrex = ccxt.bittrex({ 'apiKey': api_keys.bittrex['apiKey'], 'secret': api_keys.bittrex['secret'], }) binance = ccxt.binance({ 'apiKey': api_keys.binance['apiKey'], 'secret': api_keys.binance['secret'], }) bitfinex = ccxt.bitfinex({ 'apiKey': api_keys.bitfinex['apiKey'], 'secret': api_keys.bitfinex['secret'], }) kraken = ccxt.kraken({ 'apiKey': api_keys.kraken['apiKey'], 'secret': api_keys.kraken['secret'], }) bitmex = ccxt.bitmex({ 'apiKey': api_keys.bitmex['apiKey'], 'secret': api_keys.bitmex['secret'], }) okex = ccxt.okex({ 'apiKey': api_keys.okex['apiKey'], 'secret': api_keys.okex['secret'], }) exchanges = [ coinbasepro, poloniex, bittrex, binance, bitfinex, kraken, bitmex, okex ] timing_limits = [.35, .35, 1, .35, 2, 1, 1, .35] # requesting period limit per exchange for exchange, timing in zip(exchanges, timing_limits): g_storage.timer[exchange.name] = [0, timing] # exchanges.pop(exchanges.index(kraken)) return exchanges
def __init__(self, channels=[]): self.channels=channels self.check_tradepair() # Disabbling logging. logger = logging.getLogger() logger.disabled = True self.bittrex=ccxt.bittrex() self.bittrex.load_products() self.pub = Publisher(channels)
def scrape_and_save_market_currency_symbols(): markets = [ccxt.bittrex()] currencies = {m.name: [] for m in markets} for market in markets: market.load_markets() for marketCurr in getCurrencySymbols(market): if marketCurr not in currencies: currencies[market.name].append(marketCurr) with open('Market-Currencies.json', 'w') as outfile: json.dump(currencies, outfile)
def __init__(self): self.exchanges = { 'binanceus': ccxt.binanceus(), 'bittrex': ccxt.bittrex(), # 'coinbase': ccxt.coinbase(), # coinbase has most currency pairs, by like 3 times the next highest, consider removing. Also coinbase limits API to 3-6 calls/sec 'gemini': ccxt.gemini(), # 'kraken': ccxt.kraken(), # updating their API 'livecoin': ccxt.livecoin(), 'theocean': ccxt.theocean(), # 'okex': ccxt.okex(), #Canadian, does not allow us 'bitmart': ccxt.bitmart(), # 'cex': ccxt.cex(), # EU # 'bitbay': ccxt.bitbay(), # EU, Updating API # 'bcex': ccxt.bcex(), #candian exch, their API is updating # 'bitbay': ccxt.bitbay(), 'paymium': ccxt.paymium(), 'binance': ccxt.binance(), 'okcoin': ccxt.okcoin(), 'bitfinex': ccxt.bitfinex() # non-US } # creates a markets variable in each exchange instance. ex. exchages[0].markets will return markets self.loadMarkets() # these are tickers available on exchnage, but not US customers, or don't allow deposits/withdrawals self.unavailableTickers = { 'binanceus': [], 'bittrex': [ 'LUNA/BTC', 'ABBC/BTC', 'Capricoin/BTC', 'DRGN/BTC', 'CVT/BTC', 'NXT/BTC' ], # 'coinbase': [], 'gemini': [], # 'kraken': [], # Updating their API 'livecoin': [ 'BTM/BTC', 'BTM/ETH', 'NANO/BTC', 'NANO/ETH', 'XTZ/BTC', 'XTZ/ETH', 'THETA/BTC', 'THETA/ETH', 'ABBC/BTC', 'ABBC/ETH', 'AE/BTC', 'AE/ETH', 'IOST/BTC', 'IOST/ETH' ], 'theocean': [], # 'okex': ['AET/ETH','AET/BTC'], # does not allow US, but allows canadian 'bitmart': [], # 'cex': [], # 'bitbay': [], # 'bcex': [], #candian exch, their API is updating 'bitbay': [], 'paymium': [], 'binance': [], 'okcoin': [], 'bitfinex': [] } self.commonTickers = self.getCommonTickers() # then only call fetch_tickers for common_tickers between exchanges self.minProfit = 1 # percent profit # in USD NOTE: still need to incorporate this. I think coinmarketcap API has a quick conversion call self.minVolume = 200 self.txfrCosts = []
def __init__(self, keypath): with open(keypath, "r") as f: key = f.readline().strip() secret = f.readline().strip() self.useCoinapi = False self.orderPlacementFreq = 1 Exchange.__init__(self, 'Bittrex', bittrex({ 'apiKey': key, 'secret': secret }))
def get_bittrex_connection(key, secret): try: bittrex = ccxt.bittrex({ 'apiKey': key, 'secret': secret }) log("INFO", "Successfully established connection to Bittrex API") return bittrex except Exception as e: log("ERROR", f"Failed to establish connection to Bittrex API: {e}") return
def get_exchange_list(): bittrex_exchange = ccxt.bittrex() binance_exchange = ccxt.binance() kucoin_exchange = ccxt.kucoin() huobiPro_exchange = ccxt.huobipro() cryptopia_exchange = ccxt.cryptopia() bitmex_exchange = ccxt.bitmex() list_of_exchanges = [ bittrex_exchange, binance_exchange, kucoin_exchange, huobiPro_exchange, cryptopia_exchange ] return list_of_exchanges
def init_supported_exchanges(): objects = { "binance": ccxt.binance(), "bitfinex": ccxt.bitfinex(), "bitflyer": ccxt.bitflyer(), "bitstamp": ccxt.bitstamp(), "bittrex": ccxt.bittrex(), "coinbase": ccxt.coinbase(), "kraken": ccxt.kraken(), "poloniex": ccxt.poloniex() } return objects
def __init__(self): self.bit = bittrex() self.updater = Updater( token='472894388:AAEjG7SEVkeJe2aihlnbyLD92cV-f4O5WQ0') self.handlers() self.bot = self.dispatcher.bot self.updater.start_polling() logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def bittrexData(): bittrex = ccxt.bittrex() coindata = list(bittrex.fetch_tickers().values()) columns = ['ask', 'bid', 'close', 'high', 'low', 'last', 'symbol', 'average', 'baseVolume', 'timestamp'] df = pd.DataFrame(coindata) df = df[columns] df['exchange'] = 'bittrex' df['createtime'] = starttime df['baseCurrency'] = list(i.split('/')[0] for i in df['symbol']) df['quotCurrency'] = list(i.split('/')[1] for i in df['symbol']) engine = create_engine("mysql+pymysql://quziyou:0739#[email protected]:5389/coinData?charset=utf8") df.to_sql('coindata_tickers', con=engine, if_exists='append', index=False)
def get_coins_bittrex(): exchange = ccxt.bittrex() markets = exchange.fetch_markets() try: for market in markets: market = market['info'] symbol = market["MarketCurrency"] name = market["MarketCurrencyLong"].lower() symbol_name[symbol] = name name_symbol[name] = symbol symbol_exchange[symbol] = 'bittrex' # print(f'Found {len(markets)} markets.') except Exception as e: print(f'Failed to get markets from Bittrex ({e})')
def exchangeObject(exchange_in): exchanges = [ccxt.acx(),ccxt.bitbay(),ccxt.bitfinex(),ccxt.bitflyer(),ccxt.bithumb(),ccxt.bitlish(),ccxt.bitmarket(),ccxt.bitmex(),ccxt.bitso(), ccxt.bitstamp(),ccxt.bitstamp1(),ccxt.bittrex(),ccxt.bl3p(),ccxt.bleutrade(),ccxt.btcbox(),ccxt.btcchina(),ccxt.btcexchange(),ccxt.btcmarkets(),ccxt.btctradeua(),ccxt.btcturk(), ccxt.btcx(),ccxt.bxinth(),ccxt.ccex(),ccxt.cex(),ccxt.chbtc(),ccxt.chilebit(),ccxt.coincheck(),ccxt.coinfloor(),ccxt.coingi(),ccxt.coinmarketcap(),ccxt.coinmate(), ccxt.coinsecure(),ccxt.coinspot(),ccxt.cryptopia(),ccxt.dsx(),ccxt.exmo(),ccxt.flowbtc(),ccxt.foxbit(),ccxt.fybse(),ccxt.fybsg(),ccxt.gatecoin(),ccxt.gateio(),ccxt.gdax(), ccxt.gemini(),ccxt.getbtc(),ccxt.hitbtc(),ccxt.huobi(),ccxt.huobicny(),ccxt.independentreserve(),ccxt.itbit(),ccxt.jubi(),ccxt.kraken(),ccxt.kucoin(), ccxt.kuna(),ccxt.lakebtc(),ccxt.liqui(),ccxt.livecoin(),ccxt.luno(),ccxt.mercado(),ccxt.mixcoins(),ccxt.nova(),ccxt.okcoincny(),ccxt.okcoinusd(),ccxt.okex(),ccxt.paymium(), ccxt.poloniex(),ccxt.qryptos(),ccxt.quadrigacx(),ccxt.southxchange(),ccxt.surbitcoin(),ccxt.therock(),ccxt.tidex(),ccxt.urdubit(),ccxt.vaultoro(),ccxt.vbtc(), ccxt.virwox(),ccxt.wex(),ccxt.xbtce(),ccxt.yobit(),ccxt.yunbi(),ccxt.zaif(),ccxt.zb()] for count, exchange in enumerate([str(x) for x in exchanges]): if exchange_in.lower() in exchange: return exchanges[count] break
def getMarketPrice(EXCHANGE, SYMBOL): if EXCHANGE == "poloniex": exchange = ccxt.poloniex() elif EXCHANGE == "bittrex": exchange = ccxt.bittrex() elif EXCHANGE == "kraken": exchange = ccxt.kraken() markets = exchange.load_markets() book = ccxt.poloniex().fetch_order_book(SYMBOL, {'depth': 10}) # print(book) bid = book['bids'][0][0] if len(book['bids']) > 0 else None ask = book['asks'][0][0] if len(book['asks']) > 0 else None spread = (ask - bid) if (bid and ask) else None print({'bid': bid, 'ask': ask, 'spread': spread}, exchange.id, 'market price') return spread
def main(): bit = bittrex() fh5 = checkForFile("D:/Drive/atom/python/Bittrex.h5") markets = bit.fetch_markets() timeVolArr, priceArr = parseCandles(bit.fetch_ohlcv("XRP/USDT")) h5Groups = createGroups(fh5, markets) # print(fh5.__contains__(h5Groups[0]+"/"+"123")) # dset = fh5.create_dataset(h5Groups[0]+"/"+"123",(1,5),dtype='i8', compression='lzf') # dset[candles[0],"Time",candles[1],"adf"] # data = bit.fetch_ticker("BTC/USDT") # pprint(data) # print(len(data)) fh5.close
def get_exchange_symbols(): assets = Assets() slugs = get_coincap_slugs() exchanges = ['binance', 'bitfinex', 'bittrex', 'poloniex', 'kraken'] coins = {} # loop through exchanges, grab symbols for exchange_str in exchanges: if exchange_str == 'binance': exchange = ccxt.binance() elif exchange_str == 'bitfinex': exchange = ccxt.bitfinex() elif exchange_str == 'bittrex': exchange = ccxt.bittrex() elif exchange_str == 'poloniex': exchange = ccxt.poloniex() elif exchange_str == 'kraken': exchange = ccxt.kraken() else: exchange = None if exchange: exchange.load_markets() for sym in exchange.symbols: if '/BTC' in sym: sym = sym.replace('/BTC', '') if sym not in coins: coins[sym] = {'exchanges': [exchange_str]} else: coins[sym]['exchanges'].append(exchange_str) # handle felix and coincap assets for coin in coins: if coin in assets: coins[coin]['exchanges'].append('felix') if coin in slugs: coins[coin]['id'] = slugs[coin]['id'] coins[coin]['name'] = slugs[coin]['name'] else: coins[coin]['id'] = None coins[coin]['name'] = None sorted_coins = collections.OrderedDict(sorted(coins.items())) return sorted_coins
def live_ticker(tradepair): global listOfTradingPairs print("Ticker of Currency Pair", tradepair) if tradepair in listOfTradingPairs.keys(): bittrex = ccxt.bittrex() bittrex.load_products() tradepair = listOfTradingPairs.get(tradepair) temp = bittrex.fetch_ticker(tradepair) while True: if (bittrex.fetch_ticker(tradepair) == temp): pass else: temp = bittrex.fetch_ticker(tradepair) print(temp) else: print("Currency Pair is not from the below list \n", listOfTradingPairs.keys())
def setup_clients(self): self.exchanges['Bittrex'] = ccxt.bittrex({ 'apiKey': self.meta['Bittrex']['public'], 'secret': self.meta['Bittrex']['secret'], }) self.exchanges['Poloniex'] = ccxt.poloniex({ 'apiKey': self.meta['Poloniex']['public'], 'secret': self.meta['Poloniex']['secret'], }) self.exchanges['YoBit'] = ccxt.yobit({ 'apiKey': self.meta['YoBit']['public'], 'secret': self.meta['YoBit']['secret'], }) self.exchanges['HitBTC'] = ccxt.hitbtc2({ 'apiKey': self.meta['HitBTC']['public'], 'secret': self.meta['HitBTC']['secret'], }) self.exchanges['Tidex'] = ccxt.tidex({ 'apiKey': self.meta['Tidex']['public'], 'secret': self.meta['Tidex']['secret'], }) self.exchanges['Binance'] = ccxt.binance({ 'options': { 'adjustForTimeDifference': True }, 'apiKey': self.meta['Binance']['public'], 'secret': self.meta['Binance']['secret'], }) self.exchanges['Bitfinex'] = ccxt.bitfinex({ 'apiKey': self.meta['Bitfinex']['public'], 'secret': self.meta['Bitfinex']['secret'], })
def get(cls): return { 'binance': ccxt.binance({ 'apiKey': 'YOUR_PUBLIC_API_KEY', 'secret': 'YOUR_SECRET_PRIVATE_KEY', }), 'bitstamp': ccxt.bitstamp({ 'apiKey': 'YOUR_PUBLIC_API_KEY', 'secret': 'YOUR_SECRET_PRIVATE_KEY', }), 'bittrex': ccxt.bittrex({ 'apiKey': os.environ.get("BITTREX_KEY"), 'secret': os.environ.get("BITTREX_SECRET"), }), 'gdax': ccxt.gdax({ 'apiKey': 'YOUR_PUBLIC_API_KEY', 'secret': 'YOUR_SECRET_PRIVATE_KEY', }), 'hitbtc': ccxt.hitbtc({ 'apiKey': 'YOUR_PUBLIC_API_KEY', 'secret': 'YOUR_SECRET_PRIVATE_KEY', }), 'kraken': ccxt.kraken({ 'apiKey': 'YOUR_PUBLIC_API_KEY', 'secret': 'YOUR_SECRET_PRIVATE_KEY', }), 'liqui': ccxt.liqui({ 'apiKey': 'YOUR_PUBLIC_API_KEY', 'secret': 'YOUR_SECRET_PRIVATE_KEY', }), 'poloniex': ccxt.poloniex({ 'apiKey': 'YOUR_PUBLIC_API_KEY', 'secret': 'YOUR_SECRET_PRIVATE_KEY', }), # add additional supported exchanges }
def init_ccxt(self): self.binance = ccxt.binance({ 'apiKey': secrets.BINANCE_KEY, 'secret': secrets.BINANCE_SECRET, 'timeout': 30000, 'enableRateLimit': True, }) self.bittrex = ccxt.bittrex({ 'apiKey': secrets.BITTREX_KEY, 'secret': secrets.BITTREX_SECRET, 'timeout': 30000, 'enableRateLimit': True, }) self.bitfinex = ccxt.bitfinex2({ 'apiKey': secrets.BITFINEX_KEY, 'secret': secrets.BITFINEX_SECRET, 'timeout': 30000, 'enableRateLimit': True, })
def __init__(self): self.coinmarketcap = Pymarketcap() self.bittrex = ccxt.bittrex() #self.poloniex = ccxt.poloniex() self.quadrigacx = ccxt.quadrigacx() self.quadrigacx.userAgent = self.quadrigacx.userAgents['chrome']; self.exchanges = {'Bittrex':self.bittrex,'Quadrigacx':self.quadrigacx,'coinmarketcap':self.coinmarketcap} self.loadMarkets() self.btc = {'name':'BTC','Cmc':{'last': '0', 'current':'0','color':'black','1h':'0','24h':'0','7d':'0'}, 'Bittrex':{'last':'0','currentBTC':'0','lastBTC':'0','current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}, 'Quadrigacx':{'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}} self.eth = {'name':'ETH','Cmc': {'last':'0', 'current':'0','color':'black','1h':'0','24h':'0','7d':'0'}, 'Bittrex': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}, 'Quadrigacx': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}} self.zec = {'name':'ZEC','Cmc': {'last':'0', 'current':'0','color':'black','1h':'0','24h':'0','7d':'0'}, 'Bittrex': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}} self.ltc = {'name':'LTC','Cmc': {'last': '0', 'current': '0','color':'black','1h':'0','24h':'0','7d':'0'}, 'Bittrex': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}, 'Quadrigacx': {'last':'0','currentBTC':'0','lastBTC':'0', 'current':'0','color':'black','bid':'0','ask':'0','high':'0','low':'0','vol':'0','sell':'0','buy':'0','change':'0'}} self.coins = [self.btc,self.eth,self.zec,self.ltc]
def __init__(self, app): self.app = app self.webhook = "YOUR SLACK WEBHOOK" self.coinmarketcap = Pymarketcap() self.bittrex = ccxt.bittrex() self.poloniex = ccxt.poloniex() self.quadraigacx = ccxt.poloniex() self.exchanges = { 'bittrex': self.bittrex, 'poloniex': self.poloniex, 'quadraigacx': self.quadraigacx, 'coinmarketcap': self.coinmarketcap } self.loadMarkets() self.dispatch_map = { 'showalert': self.showAlert, 'removealert': self.removeAlert, 'alert': self.createAlert, 'topten': self.topten, 'updatecoin': self.updatecoin, 'gainers': self.gainers, 'losers': self.losers, 'symbols': self.symbols } alertFile = Path("alert.p") if alertFile.is_file(): self.alerts = pickle.load(open('alert.p', "rb")) else: self.alerts = [] self.symbols = [] self.timeframe = ['7d', '24h', '1h'] self.symbols = self.coinmarketcap.symbols self.coinmarket_latestinfo = [] self.bittrex_latestinfo = [] self.poloniex_latestinfo = [] self.quadraigacx_latestinfo = [] scheduler = BackgroundScheduler() scheduler.add_job(self.refreshinfo, 'interval', seconds=20) logging.basicConfig() scheduler.start()
def bittrexAgg(symbols): result = [] try: bittrex = ccxt.bittrex({ 'apiKey': 'apiKey', 'secret': 'secret', 'options': { 'adjustForTimeDifference': True } }) totalBalance = bittrex.fetch_balance()["free"] exchangeSymbols = bittrex.symbols checkSymbols = list(np.intersect1d(exchangeSymbols, symbols)) allData = bittrex.fetch_tickers(checkSymbols) ethPrice = bittrex.fetch_ticker("ETH/USDT")["last"] btcPrice = bittrex.fetch_ticker("BTC/USDT")["last"] for s in checkSymbols: try: quote = s.split("/")[-1] dataSymbols = allData[s] coinBalance = totalBalance.get(s.split("/")[0], 0) volume = int(float(dataSymbols["baseVolume"])) ask = dataSymbols["ask"] bid = dataSymbols["bid"] last = float(dataSymbols["last"]) if quote == "BTC": volume = int(volume * btcPrice * last) elif quote == "ETH": volume = int(volume * ethPrice * last) else: volume = int(volume * dataSymbols["last"]) volume = volume / ethPrice result.append(["bittrex", s, coinBalance, ask, bid, volume]) except: print("Bittrex couldn`t get " + s) continue except Exception as e: print(str(e)[:150]) return (result)
def fetch_exchange_data(exchange_name): bitstamp = ccxt.bitstamp() bitmex = ccxt.bitmex() bitfinex = ccxt.bitfinex2() bittrex = ccxt.bittrex() okcoin = ccxt.okcoinusd() kraken = ccxt.kraken() binance = ccxt.binance() coss = ccxt.coss() kucoin = ccxt.kucoin2() poloniex = ccxt.poloniex() # theocean = ccxt.theocean() upbit = ccxt.upbit() dict_of_exchanges = { 'kraken': kraken, 'bitmex': bitmex, 'bittrex': bittrex, 'bitstamp': bitstamp, 'bitfinex': bitfinex, 'okcoin': okcoin, 'binance': binance, 'coss': coss, 'kucoin': kucoin, 'poloniex': poloniex, # 'theocean': theocean, 'upbit': upbit } try: return dict( dict_of_exchanges[exchange_name].fetch_order_book('BTC/USD')) # return dict(dict_of_exchanges[exchange_name].fetch_order_book('XRP/USD')) # return dict(dict_of_exchanges[exchange_name].fetch_order_book('LTC/USD')) # add BitcoinCash # return dict(dict_of_exchanges[exchange_name].fetch_order_book('ETH/USD')) except Exception as ex: print('%s - erro: %s' % (exchange_name, ex)) return {}
import ccxt print(ccxt.exchanges) bittrex = ccxt.bittrex() load_markets = bittrex.load_markets() markets = bittrex.markets print(markets) symbols = bittrex.symbols print(symbols) symbols_qty = len(symbols) print(symbols_qty) symbols_active = [] for sym in range(symbols_qty): if markets[symbols[sym]]['active'] == True: symbols_active.append(symbols[sym]) print(symbols[sym], markets[symbols[sym]]['active']) print(symbols_active) symbols_active_qty = len(symbols_active) print(symbols_active_qty) markets_active = [] for sym in range(symbols_active_qty): print(markets[symbols_active[sym]])
# -*- coding: utf-8 -*- import os import sys root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 exchange = ccxt.bittrex({ "apiKey": "471b47a06c384e81b24072e9a8739064", "secret": "694025686e9445589787e8ca212b4cff", "enableRateLimit": True, }) orders = exchange.fetch_orders() print(orders) order = exchange.fetch_order(orders[0]['id']) print(order)