class TestApiCoinmarketcap(unittest.TestCase): """ Tests for Coinmarketcap Api commands. These will fail in the absence of an internet connection or if Coinmarketcap API goes down. """ def setUp(self): self.coinmarketcap = Pymarketcap() def test_symbols(self): actual = self.coinmarketcap.symbols self.assertIs(type(actual), list) self.assertEqual(len(actual) > 0, True) self.assertIs(type(actual[0]), str) def test_ticker(self): actual = self.coinmarketcap.ticker() self.assertIs(type(actual), list) self.assertEqual(len(actual) > 0, True) for tick in actual: self.assertIs(type(tick), dict) actual = self.coinmarketcap.ticker(config.COIN) self.assertIs(type(actual), dict) # With param convert actual = self.coinmarketcap.ticker(config.COIN, convert="EUR") self.assertIs(type(actual), dict) actual = self.coinmarketcap.ticker("ETH", convert="CNY") self.assertIs(type(actual), dict) def test_stats(self): actual = self.coinmarketcap.stats()
async def function_cmc(self, coin): coin = coin.upper() coinmarketcap = Pymarketcap(timeout=10) cmc_json = coinmarketcap.ticker(coin, convert="EUR") rank = str("Rank : [Rank " + str(cmc_json["rank"]) + "]\n") if cmc_json["market_cap_usd"] is None: marketcap = "MarketCap : Unknown\n" else: marketcap = str("MC : " + "$" + "{:,}".format(float(cmc_json["market_cap_usd"])) + "\n") price = str("Price : ${0:.3f}".format(float(cmc_json["price_usd"])) + " | {0:.3f}€\n".format(float(cmc_json["price_eur"]))) if cmc_json["percent_change_1h"] is None: change_1 = "1h Swing : Unknown\n" else: change_1 = str("1h Swing : " + str(cmc_json["percent_change_1h"]) + "%\n") if cmc_json["percent_change_24h"] is None: change_24 = "24h Swing : Unknown\n" else: change_24 = str("24h Swing : " + str(cmc_json["percent_change_24h"]) + "%\n") if cmc_json["percent_change_7d"] is None: change_7 = "7 days Swing : Unknown\n" else: change_7 = str("7 days Swing : " + str(cmc_json["percent_change_7d"]) + "%\n") value_mc = "```css\n" + rank + marketcap + price + change_1 + change_24 + change_7 + "```" self.name = cmc_json["name"] return value_mc
def function_cmc(): coin = "BTC" coinmarketcap = Pymarketcap(timeout=10) try: cmc_json = coinmarketcap.ticker(coin, convert="EUR") rank = str("Rank : [Rank " + str(cmc_json["data"]["rank"]) + "]\n") if cmc_json["data"]["quotes"]["USD"]["market_cap"] is None: marketcap = "MarketCap : Unknown\n" else: marketcap = str( "MC : " + "$" + "{:,}".format(float(cmc_json["data"]["quotes"]["USD"]["market_cap"])) + "\n") price = str( "Price : ${0:.3f}".format(float(cmc_json["data"]["quotes"]["USD"]["price"])) + " | {0:.3f}€\n".format( float(cmc_json["data"]["quotes"]["EUR"]["price"]))) if cmc_json["data"]["quotes"]["USD"]["percent_change_1h"] is None: change_1 = "1h Swing : Unknown\n" else: change_1 = str("1h Swing : " + str(cmc_json["data"]["quotes"]["USD"]["percent_change_1h"]) + "%\n") if cmc_json["data"]["quotes"]["USD"]["percent_change_24h"] is None: change_24 = "24h Swing : Unknown\n" else: change_24 = str("24h Swing : " + str(cmc_json["data"]["quotes"]["USD"]["percent_change_24h"]) + "%\n") if cmc_json["data"]["quotes"]["USD"]["percent_change_7d"] is None: change_7 = "7 days Swing : Unknown\n" else: change_7 = str("7 days Swing : " + str(cmc_json["data"]["quotes"]["USD"]["percent_change_7d"]) + "%\n") value_mc = "```css\n" + rank + marketcap + price + change_1 + change_24 + change_7 + "```" except TypeError or KeyError: value_mc = "```css\nThis ticker does not exist on Coinmarketcap.\nMaybe you made a typo in the coin's ticker.```" return value_mc
def function_cmc(self): coin = self.coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin, convert="EUR") self.price_usd = float(cmc_json["price_usd"]) self.price_eur = float(cmc_json["price_eur"]) self.price_btc = float(cmc_json["price_btc"]) return
def function_cmc(coin): if coin == "": id_coin = "" else: coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin) id_coin = cmc_json["id"] return id_coin
def function_cmc(self, coin): self.coin = coin.upper() coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin, convert="EUR") self.btc_price = cmc_json["price_btc"] self.usd_price = cmc_json["price_usd"] self.eur_price = cmc_json["price_eur"] self.name = cmc_json["name"]
async def function_cmc(self, coin): self.coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(self.coin, convert="EUR") btc_json = coinmarketcap.ticker(self.coin, convert="BTC") self.price_usd = float(cmc_json["data"]["quotes"]["USD"]["price"]) self.price_eur = float(cmc_json["data"]["quotes"]["EUR"]["price"]) self.price_btc = float(btc_json["data"]["quotes"]["BTC"]["price"]) return
def function_cmc(self, coin): self.coin = coin.upper() coin = coin.upper() coinmarketcap = Pymarketcap() eur_json = coinmarketcap.ticker(coin, convert="EUR") btc_json = coinmarketcap.ticker(coin, convert="BTC") self.btc_price = btc_json["data"]["quotes"]["BTC"]["price"] self.usd_price = eur_json["data"]["quotes"]["USD"]["price"] self.eur_price = eur_json["data"]["quotes"]["EUR"]["price"] self.name = eur_json["data"]["name"]
def function_cmc(self, coin): if coin == "": full_name = self.empty_name else: coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin) ticker = cmc_json["symbol"] name = cmc_json["name"] full_name = name + "%20" + "(" + ticker + ")" return full_name
def getCoinResult(self): market = Pymarketcap() #Get the KRW Price of Coins cur = market.ticker(convert="KRW") # init Coin's price of up&down of price increaseCoin = 0 decreaseCoin = 0 #Rank from 50 to 100 for i in range(50, 100): #Convert array to Dict to get which I want CurInfo = cur[i] #Get the price and name of the coin which is necessary Price = float(CurInfo['price_krw']) Name = CurInfo['name'] #if file is exist. for avoid error whether file is exist or not if os.path.isfile('./coin_currency/' + Name + '_price.txt'): #get the old one from file PreInfo = open('./coin_currency/' + Name + '_price.txt', 'rt') PrePrice = PreInfo.readline() PrePrice = float(PrePrice) #compare the price if PrePrice > Price: decreaseCoin += 1 elif PrePrice < Price: increaseCoin += 1 #write down the new price to file PreInfo = open('./coin_currency/' + Name + '_price.txt', 'wt') PreInfo.write(str(Price) + '\n') PreInfo.close() else: #For the first execution which don't have coin's priceInfo PreInfo = open('./coin_currency/' + Name + '_price.txt', 'wt') PreInfo.write(str(Price) + '\n') PreInfo.close() #Compare the number of the coin if increaseCoin == 0 and decreaseCoin == 0: result = "EVEN" else: if increaseCoin > decreaseCoin: result = "UP" elif increaseCoin < decreaseCoin: result = "DOWN" return result
async def function_btcap(self): coinmarketcap = Pymarketcap() cmc_btc = coinmarketcap.ticker("bitcoin", convert=self.currency) price = str("Price : " + "$" + "{0:.3f}".format(float(cmc_btc["price_usd"])) + " | " + "{0:.3f}".format( float(cmc_btc["price_eur"])) + "€ \n") volume = "24h Volume: " "$ " + "{:,}".format(float(cmc_btc["24h_volume_usd"])) + "\n" change_1 = "24h Swing : " + str(cmc_btc["percent_change_24h"]) + "%\n" change_7 = "7 days Swing : " + str(cmc_btc["percent_change_7d"]) + "%\n\n" value_btc = "```css\n" + price + volume + change_1 + change_7 + "```" return value_btc
class TestApiCoinmarketcap(unittest.TestCase): """ Tests for Coinmarketcap Api commands. These will fail in the absence of an internet connection or if Coinmarketcap API goes down. """ def __init__(self, *args, **kwargs): super(TestApiCoinmarketcap, self).__init__(*args, **kwargs) self.coinmarketcap = Pymarketcap() self.config = ConfigTest() def tearDown(self): # Prevent TooManyRequestsError time.sleep(.25) def test_symbols(self): actual = self.coinmarketcap.symbols self.assertIs(type(actual), list) self.assertEqual(len(actual) > 0, True) self.assertIs(type(actual[0]), str) def test_ticker(self): actual = self.coinmarketcap.ticker() self.assertIs(type(actual), list) self.assertEqual(len(actual) > 0, True) for tick in actual: self.assertIs(type(tick), dict) actual = self.coinmarketcap.ticker(self.config.COIN) self.assertIs(type(actual), dict) # With param convert actual = self.coinmarketcap.ticker(self.config.COIN, convert="EUR") self.assertIs(type(actual), dict) actual = self.coinmarketcap.ticker("ETH", convert="CNY") self.assertIs(type(actual), dict) def test_stats(self): actual = self.coinmarketcap.stats()
def get_account_values(username): market = Pymarketcap() account = get_steem_account(username) steem_price = float(market.ticker("steem")["price_usd"]) steem_dollar_price = float(market.ticker("steem-dollars")["price_usd"]) steem_balance = account["balance"] steem_dollar_balance = account["sbd_balance"] savings_balance = account["savings_balance"] steem = float(steem_balance.split(" ")[0]) steem_dollars = float(steem_dollar_balance.split(" ")[0]) savings = float(savings_balance.split(" ")[0]) total_price = steem * steem_price + steem_dollars * steem_dollar_price + savings * steem_price output = { "steem": { "amount": steem, "price_usd": steem * steem_price }, "steem-dollars": { "amount": steem_dollars, "price_usd": steem_dollars * steem_dollar_price }, "savings": { "amount": savings, "price_usd": savings * steem_price }, "total":{ "price_usd": total_price } } response = jsonify(output) response.headers.add('Access-Control-Allow-Origin', '*') return response
def function_cmc(self, coin): coin = coin.upper() coinmarketcap = Pymarketcap() cmc_json = coinmarketcap.ticker(coin, convert="EUR") rank = str("Rank : [Rank " + str(cmc_json["rank"]) + "]\n") marketcap = str("MC : " + "$" + "{:,}".format(float(cmc_json["market_cap_usd"])) + "\n") price = str("Price : " + "$" + "{0:.3f}".format(float(cmc_json["price_usd"])) + " | " + "{0:.3f}".format( float(cmc_json["price_eur"])) + "€ \n") change_1 = str("1h Swing : " + str(cmc_json["percent_change_1h"]) + "%\n") change_24 = str("24h Swing : " + str(cmc_json["percent_change_24h"]) + "%\n") change_7 = str("7 days Swing : " + str(cmc_json["percent_change_7d"]) + "%\n") value_mc = "```css\n" + rank + marketcap + price + change_1 + change_24 + change_7 + "```" self.name = cmc_json["name"] return value_mc
class coinmarkets(object): 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 parseCommand(self, command, text, responseUrl, username): args = tuple(text.split()) #method = getattr(self, method_name, lambda: "nothing") print(text) print(args) print(command) if args: self.dispatch_map[command](args, responseUrl, username) else: self.dispatch_map[command](["empty"], responseUrl, username) return "processing request" def loadMarkets(self): self.bittrex.loadMarkets() self.poloniex.loadMarkets() self.quadraigacx.loadMarkets() def showAlert(self, args, responseUrl, username): if args[0] == "empty": results = tasks.search(self.alerts, 'username', username) if not results: tasks.sendTextResponse(responseUrl, "no alerts found for " + username, "ephemeral") else: data = simplejson.dumps(self.alerts, use_decimal=True) tasks.sendTextResponse(responseUrl, data, "ephemeral") else: if args[0] == "all": data = simplejson.dumps(self.alerts, use_decimal=True) tasks.sendTextResponse(responseUrl, data, "ephemeral") #tasks.sendJsonResponse(responseUrl, "all alerts" , data, "ephemeral") else: tasks.sendTextResponse(responseUrl, "invalid command", "ephemeral") def createAlert(self, args, responseUrl, username): # args = [cointype,price,market] btcUSD = 0 timestamp = str(int(time.time())) if len(args) < 3: return "invalid command" else: market = args[2] if args[0] in self.symbols: symbol = str(args[0]) if (symbol == "BTC"): pair = "BTC/USDT" exchange = self.exchanges[args[2]] currentPrice = exchange.fetch_ticker(pair)['last'] else: pair = symbol + "/BTC" exchange = self.exchanges[args[2]] results = exchange.fetch_ticker(pair) if not results: return tasks.sendTextResponse( responseUrl, "currency not found in " + market, "ephemeral") else: btcUSD = exchange.fetch_ticker('BTC/USDT')['last'] currentPrice = float(results['last'] * btcUSD) if ('%' in args[1]): change = args[1].replace('%', ' ') if ('-' in change): change = float(change.replace('-', ' ')) percentage = float((100 - change) / 100) setPrice = float(percentage * float(currentPrice)) else: percentage = float((100 + float(change)) / 100) setPrice = float(percentage * float(currentPrice)) else: setPrice = float(args[1]) if float(currentPrice) < setPrice: alertType = "high" elif float(currentPrice) > setPrice: alertType = 'low' #alert when the price is lower than the setPrice else: return tasks.sendTextResponse( responseUrl, "error: current price == set price", "ephemeral") alert = { 'symbol': symbol, 'setPrice': setPrice, 'market': market, 'originalPrice': currentPrice, 'type': alertType, 'username': username, "timestamp": timestamp } self.alerts.append(alert) pickle.dump(self.alerts, open("alert.p", "wb")) tasks.createAlertResponse(alert, str(currentPrice), "Alert Created", responseUrl) return tasks.sendTextResponse(responseUrl, "command received", "ephemeral") else: return tasks.sendTextResponse(responseUrl, "invalid command", "ephemeral") def topten(self, args1, responseUrl, username): results = self.coinmarketcap.ticker(limit=10) results = results[0] print(results) return json.dumps(results, default=decimal_default) def updatecoin(self, args, responseUrl, username): if len(args) < 2: market = self.coinmarketcap.ticker(args[0], convert='USD') percentChange = " | 1h: " + str( market['percent_change_1h']) + " % " + " | 24h: " + str( market['percent_change_24h']) + " % " + " | 7d: " + str( market['percent_change_7d']) + " % " text = str("Current Price for " + str(args[0]) + ": " + str(market['price_usd']) + percentChange + " | " + "coinmarketcap") return tasks.sendTextResponse(responseUrl, text, "in_channel") elif args[1] == "all": data = self.coinmarketcap.markets(args[0]) tasks.updateAllCoinHelper.delay(args, data, responseUrl) else: #data = self.coinmarketcap.exchange(args[1]) exchange = self.exchanges[args[1]] tasks.updateCoinHelper( args, exchange, responseUrl, ) return tasks.sendTextResponse(responseUrl, "updatecoin received", "ephemeral") return "command received" def symbols(self, args1, responseUrl, username): print(args1) print(self.coinmarketcap.symbols) return json.dumps(self.coinmarketcap.symbols) def gainers(self, args, responseUrl, username): if args[0] == "empty" or args[0] not in self.timeframe or args[ 0] == "1h": args[0] = '1h' json_data = (self.coinmarketcap.ranks('gainers', args[0])[args[0]]) elif args[0] == '24h': json_data = (self.coinmarketcap.ranks('gainers', args[0])[args[0]]) elif args[0] == '7d': json_data = (self.coinmarketcap.ranks('gainers', args[0])[args[0]]) else: return tasks.sendTextResponse(responseUrl, "invalid timeframe", "ephemeral") tasks.gainerLoserHelper.delay(args, responseUrl, json_data, "gainers") return tasks.sendTextResponse(responseUrl, "top gainers received", "ephemeral") def losers(self, args, responseUrl, username): if args[0] == "empty" or args[0] not in self.timeframe or args[ 0] == "1h": json_data = (self.coinmarketcap.ranks('losers', '1h')['1h']) elif args[0] == '24h': json_data = (self.coinmarketcap.ranks('losers', args[0])[args[0]]) elif args[0] == '7d': json_data = (self.coinmarketcap.ranks('losers', args[0])[args[0]]) else: return tasks.sendTextResponse(responseUrl, "invalid timeframe", "ephemeral") tasks.gainerLoserHelper.delay(args, responseUrl, json_data, "losers") return tasks.sendTextResponse(responseUrl, "top losers received", "ephemeral") def refreshinfo(self): #self.coinmarket_latestinfo = self.coinmarketcap.ticker(limit=20) self.bittrex_latestinfo = self.bittrex.fetch_tickers() self.poloniex_latestinfo = self.poloniex.fetch_tickers() self.quadrigacx_latestinfo = self.quadraigacx.fetch_tickers() self.evaluateAlert(self.alerts) def removeAlert(self, args, responseUrl, username): for i, alert in enumerate(self.alerts): if alert['timestamp'] == args[0]: self.alerts.pop(i) pickle.dump(self.alerts, open("alert.p", "wb")) print("alerts list") print(*self.alerts) if responseUrl != "empty": return tasks.sendTextResponse( responseUrl, "alert " + alert['timestamp'] + " removed", "ephemeral") return "alert " + alert['timestamp'] + " removed" if responseUrl != "empty": return tasks.sendTextResponse(responseUrl, "alert not found", "ephemeral") return "alert not found" def evaluateAlert(self, alerts): if not alerts: return else: for i, alert in enumerate(alerts): alertType = alert["type"] if alert['market'] == 'coinmarketcap': currentPrice = float( self.coinmarketcap.ticker(alert['symbol'], convert='USD')['price_usd']) if alertType == 'low': if (currentPrice <= float(alert['setPrice'])): data = tasks.createAlertResponse( alert, currentPrice, "Price reached", self.webhook) requests.post(self.webhook, json=data) alerts.pop(i) elif alertType == 'high': if (currentPrice >= float(alert['setPrice'])): data = tasks.createAlertResponse( alert, currentPrice, "Price reached", self.webhook) requests.post(self.webhook, json=data) alerts.pop(i) elif alert['market'] == 'bittrex': tasks.sendAlert.delay(alerts, alert, self.webhook, self.bittrex_latestinfo) elif alert['market'] == 'quadrigacx': tasks.sendAlert.delay(alerts, alert, self.webhook, self.quadrigacx_latestinfo) elif alert['market'] == 'poloniex': tasks.sendAlert.delay(alerts, alert, self.webhook, self.poloniex_latestinfo)
class TestApiCoinmarketcapFull(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.coinmarketcap = Pymarketcap() def test_ticker(self): currencies_not_found = [] value_types = { "id": str, "name": str, "symbol": str, "rank": self.coinmarketcap.parse_int, "price_usd": self.coinmarketcap.parse_float, "price_btc": self.coinmarketcap.parse_float, "24h_volume_usd": [self.coinmarketcap.parse_float, type(None)], "market_cap_usd": [self.coinmarketcap.parse_float, type(None)], # Some currencies "available_supply": [self.coinmarketcap.parse_float, type(None)], # haven"t got "total_supply": [self.coinmarketcap.parse_float, type(None)], # all data available "max_supply": [self.coinmarketcap.parse_float, type(None)], "percent_change_1h": [self.coinmarketcap.parse_float, type(None)], "percent_change_24h": [self.coinmarketcap.parse_float, type(None)], "percent_change_7d": [self.coinmarketcap.parse_float, type(None)], "last_updated": self.coinmarketcap.parse_int } print("Testing all currencies in coinmarketcap.com (%d)" \ % len(self.coinmarketcap.symbols)) impatient_symbols = [] current_symbols = self.coinmarketcap.symbols first_test = True while impatient_symbols or first_test: if impatient_symbols: print("Testing symbols not tested...") current_symbols = impatient_symbols for symbol in tqdm(current_symbols): try: tick = self.coinmarketcap.ticker(symbol) for key, value in tick.items(): if type(value_types[key]) is list: self.assertIn(type(value), value_types[key]) else: self.assertIs(type(value), value_types[key]) except CoinmarketcapCurrencyNotFoundError as error: # Currency not found? currencies_not_found.append( # Notify me with all {error.currency: error.url}) except CoinmarketcapTooManyRequestsError: print("Too many requests, sleeping 60 seconds...") impatient_symbols.append(symbol) time.sleep(60) time.sleep(.2) first_test = False # Display all currencies not found print("\nCurrencies not found:") pprint(currencies_not_found) self.assertEqual(len(currencies_not_found), 0)
def main(): cmc = Pymarketcap() # Get all currencies ranked by volume currencies = cmc.ticker() print(currencies[0]) # Show first currency
class coinmarkets(object): 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 loadMarkets(self): self.bittrex.loadMarkets() self.quadrigacx.loadMarkets() def updateCoinHelper(self,args, exchange): print("updatecoinhelper") if (args[0] == 'BTC'): # index = next(index for (index, d) in enumerate(data) if d['market'] == str(args[0] + "-USDT")) if(exchange == self.quadrigacx): pair = 'BTC/CAD' data = exchange.fetch_ticker(pair) sell = '0' buy = '0' vol = data['quoteVolume'] else: pair = 'BTC/USDT' data = exchange.fetch_ticker(pair) sell = data['info']['OpenSellOrders'] buy = data['info']['OpenBuyOrders'] currentPrice = int(data['last']) currentPriceBTC = "1k" bid = int(data['bid']) ask = int(data['ask']) high = int(data['high']) low = int(data['low']) vol = data['quoteVolume'] else: # index = next(index for (index, d) in enumerate(data) if d['market'] == str(args[0] + "-BTC")) pair = args[0] + '/BTC' if(exchange == self.quadrigacx): dataCAD = exchange.fetch_ticker(args[0] + '/CAD') currentPrice = round(Decimal(float(dataCAD['last'])), 2) sell = '0' buy = '0' try: currentPriceBTC = round(Decimal(float(exchange.fetch_ticker(pair)['last'] * 1000)), 1) except: pass traceback.print_exc() currentPriceBTC = '0' bid = float(dataCAD['bid']) ask = float(dataCAD['ask']) high = round(Decimal(float(dataCAD['high'])),2) low = round(Decimal(float(dataCAD['low'])),2) vol = dataCAD['quoteVolume'] else: dataUSDT = exchange.fetch_ticker(args[0] + '/USDT')['last'] data = exchange.fetch_ticker(pair) currentPrice = round(Decimal(float(dataUSDT)),2) currentPriceBTC = round(Decimal(float(data['last'] * 1000)),1) sell = data['info']['OpenSellOrders'] buy = data['info']['OpenBuyOrders'] bid = float(data['bid']* 1000) ask = float(data['ask']* 1000) high = round(Decimal(float(data['high'] * 1000)),1) low = round(Decimal(float(data['low'] * 1000)),1) vol = data['quoteVolume'] for coin in self.coins: if coin['name'] == args[0]: coin[args[1]]['last'] = str(coin[args[1]]['current']) coin[args[1]]['current'] = str(currentPrice) coin[args[1]]['lastBTC'] = str(coin[args[1]]['currentBTC']) coin[args[1]]['currentBTC'] = str(currentPriceBTC) coin[args[1]]['bid'] = str(bid) coin[args[1]]['ask'] = str(ask) coin[args[1]]['high'] = str(high) coin[args[1]]['low'] = str(low) coin[args[1]]['vol'] = str(vol) coin[args[1]]['buy'] = str(buy) coin[args[1]]['sell'] = str(sell) if float(coin[args[1]]['current']) < float(coin[args[1]]['last']): coin[args[1]]['color'] = "red" else: coin[args[1]]['color'] = "black" def updatecoin(self, args): if len(args) < 2: market = self.coinmarketcap.ticker(args[0], convert='USD') for coin in self.coins: if coin['name'] == args[0]: coin['Cmc']['last'] = str(coin['Cmc']['current']) coin['Cmc']['current'] = str(market['price_usd']) if float(coin['Cmc']['current']) < float(coin['Cmc']['last']): coin['Cmc']['color'] = "red" else: coin['Cmc']['color'] = "black" coin['Cmc']['1h'] = str(market['percent_change_1h']) + "%" coin['Cmc']['24h'] = str(market['percent_change_24h']) + "%" coin['Cmc']['7d'] = str(market['percent_change_7d']) + "%" else: # data = self.coinmarketcap.exchange(args[1]) exchange = self.exchanges[args[1]] self.updateCoinHelper(args, exchange)
class CryptoBacktester: def __init__(self, allowed_exchanges): self.allowed_exchanges = allowed_exchanges self.cmc = Pymarketcap() self.indicator_calc = IndicatorCalc() def filter_markets(self): ranks_filtered = { 'gainers': { '1h': [], '24h': [], '7d': [] }, 'losers': { '1h': [], '24h': [], '7d': [] } } failed_products = { 'gainers': { '1h': [], '24h': [], '7d': [] }, 'losers': { '1h': [], '24h': [], '7d': [] } } time_bins = ['1h', '24h', '7d'] ranks = self.cmc.ranks() gainers = ranks['gainers'] losers = ranks['losers'] for bin in time_bins: logger.debug('bin: ' + str(bin)) for mkt in gainers[bin]: logger.debug('[gainers] mkt: ' + str(mkt)) try: markets = self.cmc.markets(mkt['website_slug']) for exch in markets['markets']: if exch['source'].lower() in self.allowed_exchanges: ranks_filtered['gainers'][bin].append((mkt, exch)) except Exception as e: logger.exception(e) failed_products['gainers'][bin].append(mkt) for mkt in losers[bin]: logger.debug('[losers] mkt: ' + str(mkt)) try: markets = self.cmc.markets(mkt['website_slug']) for exch in markets['markets']: if exch['source'].lower() in self.allowed_exchanges: ranks_filtered['losers'][bin].append((mkt, exch)) except Exception as e: logger.exception(e) failed_products['losers'][bin].append(mkt) return ranks_filtered, failed_products def get_best_pairs(self, ranked_products): best_pairs = {'success': True, 'result': {}} #conversion_currencies = ['BTC', 'ETH', 'USD'] try: for rank_type in ranked_products: logger.debug('rank_type: ' + rank_type) best_pairs['result'][rank_type] = {} for time_bin in ranked_products[rank_type]: logger.debug('time_bin: ' + time_bin) best_pairs['result'][rank_type][time_bin] = {} for product in ranked_products[rank_type][time_bin]: logger.debug('product: ' + str(product)) if product[0]['symbol'] not in best_pairs['result'][ rank_type][time_bin]: best_pairs['result'][rank_type][time_bin][ product[0]['symbol']] = {} if product[1]['pair'].split('/')[1] not in best_pairs[ 'result'][rank_type][time_bin][product[0] ['symbol']]: best_pairs['result'][rank_type][time_bin][ product[0]['symbol']][product[1]['pair'].split( '/')[1]] = self.cmc.ticker( currency=product[0]['website_slug'], convert=product[1]['pair'].split('/') [1])['data']['quotes'][ product[1]['pair'].split('/')[1]] time.sleep(2) except Exception as e: logger.exception('Exception raised in get_best_pairs().') logger.exception(e) best_pairs['success'] = False finally: return best_pairs def get_candles(self, exchange, market, interval=0): candles = {'success': True, 'result': {}} #try: logger.debug('exchange: ' + exchange) logger.debug('market: ' + market) logger.debug('interval: ' + interval) valid_intervals = [ 60, 180, 300, 900, 1800, 3600, 7200, 14400, 21600, 43200, 86400, 259200, 604800 ] endpoint = '/markets/' + exchange.lower() + '/' + market.lower( ) + '/ohlc' url = 'https://api.cryptowat.ch' + endpoint url_params = {} if interval == 0: pass else: candle_url_param = str(int(round(float(interval), 0))) url_params['periods'] = candle_url_param if interval not in valid_intervals: logger.error( 'Invalid interval passed to get_candles(). Exiting.') sys.exit(1) try: r = requests.get(url, params=url_params) time.sleep(request_delay) results = r.json() if 'result' not in results or 'allowance' not in results: logger.debug( '[get_candles()] Failed to acquire valid candles.') candles['success'] = False if 'error' in results: logger.error('Error while calling Cryptowat.ch API.') logger.error(results['error']) if results['error'] == 'Out of allowance': allowance_remaining = 0 else: allowance_remaining = results['allowance']['remaining'] allowance_cost = results['allowance']['cost'] #allowance_avg_cost = average_api_cost(allowance_cost) if candles['success'] == True: for time_bin in results['result']: data = results['result'][time_bin] np_historical = np.array(data, dtype='f8') candles[time_bin] = {} candles[time_bin]['close_time'] = np_historical[:, 0] candles[time_bin]['open'] = np_historical[:, 1] candles[time_bin]['high'] = np_historical[:, 2] candles[time_bin]['low'] = np_historical[:, 3] candles[time_bin]['close'] = np_historical[:, 4] candles[time_bin]['volume'] = np_historical[:, 5] except requests.exceptions.RequestException as e: logger.exception('RequestException while retrieving candles.') logger.exception(e) #candle_data['RequestException'] = True candles['success'] = False except requests.exceptions.ConnectionError as e: logger.error('ConnectionError while retrieving candles.') logger.error(e) #candle_data['Error'] = True candles['success'] = False except json.JSONDecodeError as e: logger.error('JSONDecodeError while retrieving candles.') logger.error(e) #candle_data['Error'] = True candles['success'] = False except Exception as e: logger.exception('Uncaught exception while retrieving candles.') logger.exception(e) #candle_data['Exception'] = True candles['success'] = False finally: return candles
class CryptoToFiatConverter(): # Constants SUPPORTED_FIAT = [ "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD" ] def __init__(self) -> None: try: self._coinmarketcap = Pymarketcap() except BaseException: self._coinmarketcap = None self._pairs = [] def convert_amount(self, crypto_amount: float, crypto_symbol: str, fiat_symbol: str) -> float: """ Convert an amount of crypto-currency to fiat :param crypto_amount: amount of crypto-currency to convert :param crypto_symbol: crypto-currency used :param fiat_symbol: fiat to convert to :return: float, value in fiat of the crypto-currency amount """ price = self.get_price(crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol) return float(crypto_amount) * float(price) def get_price(self, crypto_symbol: str, fiat_symbol: str) -> float: """ Return the price of the Crypto-currency in Fiat :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: Price in FIAT """ crypto_symbol = crypto_symbol.upper() fiat_symbol = fiat_symbol.upper() # Check if the fiat convertion you want is supported if not self._is_supported_fiat(fiat=fiat_symbol): raise ValueError('The fiat {} is not supported.'.format(fiat_symbol)) # Get the pair that interest us and return the price in fiat for pair in self._pairs: if pair.crypto_symbol == crypto_symbol and pair.fiat_symbol == fiat_symbol: # If the price is expired we refresh it, avoid to call the API all the time if pair.is_expired(): pair.set_price( price=self._find_price( crypto_symbol=pair.crypto_symbol, fiat_symbol=pair.fiat_symbol ) ) # return the last price we have for this pair return pair.price # The pair does not exist, so we create it and return the price return self._add_pair( crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol, price=self._find_price( crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol ) ) def _add_pair(self, crypto_symbol: str, fiat_symbol: str, price: float) -> float: """ :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: price in FIAT """ self._pairs.append( CryptoFiat( crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol, price=price ) ) return price def _is_supported_fiat(self, fiat: str) -> bool: """ Check if the FIAT your want to convert to is supported :param fiat: FIAT to check (e.g USD) :return: bool, True supported, False not supported """ fiat = fiat.upper() return fiat in self.SUPPORTED_FIAT def _find_price(self, crypto_symbol: str, fiat_symbol: str) -> float: """ Call CoinMarketCap API to retrieve the price in the FIAT :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: float, price of the crypto-currency in Fiat """ # Check if the fiat convertion you want is supported if not self._is_supported_fiat(fiat=fiat_symbol): raise ValueError('The fiat {} is not supported.'.format(fiat_symbol)) try: return float( self._coinmarketcap.ticker( currency=crypto_symbol, convert=fiat_symbol )['price_' + fiat_symbol.lower()] ) except BaseException: return 0.0
def coinMarketCapData(): from pymarketcap import Pymarketcap coinmarketcap = Pymarketcap() symbols = coinmarketcap.symbols # ###### Set initial Date/Time.. Will be setting throughout # In[45]: #Pulls date and time information moment = time.strftime("%Y-%b-%d__%H_%M_%S", time.localtime()) today = pd.Timestamp("today").strftime("%m/%d/%Y") hh = pd.Timestamp("today").strftime("%H") mm = pd.Timestamp("today").strftime("%M") # ###### Coinmarketcap statistics - up to date 1/14/2018 # In[47]: try: stats = coinmarketcap.stats() stats = pd.DataFrame(stats, index=[0]) stats['Date'] = today stats['Hour'] = hh stats['Minute'] = mm stats['Now'] = pd.Timestamp("today") stats.to_csv('Coinmarketcap/boom/stats/stats_' + moment + '.csv', sep=',') print("Look at all those stats 0.o") except: print("*NO STATS GATHERED*") # ###### Coin Data - Updated 1/14/2018 # In[49]: try: from pymarketcap import Pymarketcap coinmarketcap = Pymarketcap() ticker = coinmarketcap.ticker(limit=1500, convert="BTC") ticker = pd.DataFrame(ticker) ticker['Date'] = today ticker['Hour'] = hh ticker['Minute'] = mm ticker['Now'] = pd.Timestamp("today") ticker.to_csv('Coinmarketcap/boom/coins/coins_' + moment + '.csv', sep=',') print("Chaaaa-CHING! The coin data is in") except: print("*NO COINS GATHERED* *YOU ARE LOSING OUT ON BAGS*") # ###### Coin exchange info for each token - Updated 1/14/2018 # In[ ]: for coin2 in symbols: try: from pymarketcap import Pymarketcap coinmarketcap = Pymarketcap() markets = coinmarketcap.markets(coin2) markets = pd.DataFrame(markets['markets']) markets['Date'] = today markets['Hour'] = hh markets['Minute'] = mm markets['Now'] = pd.Timestamp("today") markets.to_csv('Coinmarketcap/boom/markets/markets_' + coin2 + '_' + moment + '.csv', sep=',') except: print("No market data was captured for ", coin2) pass print("I hear the exchange trades from here.. exchange data collected :)") # ###### Gainers and Losers (1h, 24h, 7d) - Updated 1/14/2018 # ###### ******Currently no 7d Gainers being captured****** # ###### New coins - Updated 1/14/2018 # In[102]: #Set date and time today = pd.Timestamp("today").strftime("%m/%d/%Y") hh = pd.Timestamp("today").strftime("%H") mm = pd.Timestamp("today").strftime("%M") moment = time.strftime("%Y-%b-%d__%H_%M_%S", time.localtime()) data = coinmarketcap.recently() data = pd.DataFrame(data) data.head() data['Date'] = today data['Hour'] = hh data['Minute'] = mm data['days_ago'] = data['added'].str.extract('(\d.)', expand=True) data['Now'] = pd.Timestamp("today") data['days_ago'] = data['days_ago'].apply(pd.to_numeric) data['Date_Added'] = data['Now'] - pd.to_timedelta(data['days_ago'], unit='d') data['Date_Added'] = data['Date_Added'].dt.date #Reimport due to naming issues from pymarketcap import Pymarketcap coinmarketcap = Pymarketcap() #Get Market date for new coins for coin2 in data["symbol"]: try: markets = coinmarketcap.markets(coin2) markets = pd.DataFrame(markets['markets']) #add 'Today' 'Hour' and 'minutes' column markets['Date'] = today markets['Hour'] = hh markets['Minute'] = mm markets['Now'] = pd.Timestamp("today") #Save CSV markets.to_csv('Coinmarketcap/boom/markets/new/markerts_' + coin2 + '_' + moment + '.csv', sep=',') print("Market info for new coin", coin2, " captured!") except: print("************ERROR COIN", coin2, "DATA NOT CAPUTRED*************") pass ###Upload datafile data.to_csv('Coinmarketcap/boom/new/new_' + moment + '.csv', sep=',') print("Gotta catch all the new coins!")
class CryptoToFiatConverter(): # Constants SUPPORTED_FIAT = [ "AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PKR", "PLN", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "ZAR", "USD" ] def __init__(self) -> None: try: self._coinmarketcap = Pymarketcap() except BaseException: self._coinmarketcap = None self._pairs = [] def convert_amount(self, crypto_amount: float, crypto_symbol: str, fiat_symbol: str) -> float: """ Convert an amount of crypto-currency to fiat :param crypto_amount: amount of crypto-currency to convert :param crypto_symbol: crypto-currency used :param fiat_symbol: fiat to convert to :return: float, value in fiat of the crypto-currency amount """ price = self.get_price(crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol) return float(crypto_amount) * float(price) def get_price(self, crypto_symbol: str, fiat_symbol: str) -> float: """ Return the price of the Crypto-currency in Fiat :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: Price in FIAT """ crypto_symbol = crypto_symbol.upper() fiat_symbol = fiat_symbol.upper() # Check if the fiat convertion you want is supported if not self._is_supported_fiat(fiat=fiat_symbol): raise ValueError( 'The fiat {} is not supported.'.format(fiat_symbol)) # Get the pair that interest us and return the price in fiat for pair in self._pairs: if pair.crypto_symbol == crypto_symbol and pair.fiat_symbol == fiat_symbol: # If the price is expired we refresh it, avoid to call the API all the time if pair.is_expired(): pair.set_price(price=self._find_price( crypto_symbol=pair.crypto_symbol, fiat_symbol=pair.fiat_symbol)) # return the last price we have for this pair return pair.price # The pair does not exist, so we create it and return the price return self._add_pair(crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol, price=self._find_price( crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol)) def _add_pair(self, crypto_symbol: str, fiat_symbol: str, price: float) -> float: """ :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: price in FIAT """ self._pairs.append( CryptoFiat(crypto_symbol=crypto_symbol, fiat_symbol=fiat_symbol, price=price)) return price def _is_supported_fiat(self, fiat: str) -> bool: """ Check if the FIAT your want to convert to is supported :param fiat: FIAT to check (e.g USD) :return: bool, True supported, False not supported """ fiat = fiat.upper() return fiat in self.SUPPORTED_FIAT def _find_price(self, crypto_symbol: str, fiat_symbol: str) -> float: """ Call CoinMarketCap API to retrieve the price in the FIAT :param crypto_symbol: Crypto-currency you want to convert (e.g BTC) :param fiat_symbol: FIAT currency you want to convert to (e.g USD) :return: float, price of the crypto-currency in Fiat """ # Check if the fiat convertion you want is supported if not self._is_supported_fiat(fiat=fiat_symbol): raise ValueError( 'The fiat {} is not supported.'.format(fiat_symbol)) try: return float( self._coinmarketcap.ticker( currency=crypto_symbol, convert=fiat_symbol)['price_' + fiat_symbol.lower()]) except BaseException: return 0.0