async def view(self, ctx, store=None): """ View store """ user = await author.get(ctx.author) store_list = '' stores = StoreModel.find() loaded_store = None if store is None: if not stores: return await ctx.send(f'```fix\nThere are no stores setup"\n```') if stores.count() == 1: loaded_store = Prodict.from_dict(stores[0]) item_list = '' loaded_store.inventory = sorted(loaded_store.inventory, key=curried.get_in(['price']), reverse=False) for i, item in enumerate(loaded_store.inventory): item = Prodict.from_dict(item) if user['quote_to'] != 'USD': rates = await coins.rate_convert() item.price = rates[user['quote_to']] * item.price item.payout = rates[user['quote_to']] * item.payout formatted_price = currency.symbol(user["quote_to"]) + '{0:.2f}'.format(item.price) formatted_payout = "{0:.2f}".format(item.payout) item_list += f'{i + 1}. {item.name}{" " * (15 - len(item.name))}{formatted_price}{" " * (10 - len(formatted_price))}{item.about.format(payout=formatted_payout, rate=str(item.rate) + " minutes")}\n' return await ctx.send( f'```py\n{user.quote_to}\nStore name: {loaded_store.name}\n\nItem{" " * (18 - len("item"))}Price{" " * (10 - len("price"))}Description\n\n{item_list}\n\nQoins represent a USD value by default, the prices will convert depending upon what quote currency you have set on your account. Use the "{self.config.prefix[0]}sq <currency symbol>" command to change it```') for i, _store in enumerate(stores): _store = Prodict.from_dict(_store) item_count = len(_store.inventory) store_list += f'\n{i + 1}. {_store.name}{" " * (12 - len("Name"))}{item_count}{" " * (10 - len(str(item_count)))}{_store.about}' store_list_head = f'\nName{" " * (15 - len("Name"))}Item Count{" " * (10 - len("item"))}Description' await ctx.send(f'```diff\nStore list:\n{store_list_head}{store_list}\n```') return await ctx.send_help('view') store_list = [] for i, _store in enumerate(stores): store_list.append(_store) if store.isnumeric(): if int(store) - 1 in range(len(store_list)): loaded_store = store_list[int(store) - 1] else: loaded_store = StoreModel.find_one({'name': store}) if not loaded_store: return await ctx.send(f'```fix\nCould not find store "{store}"\n```') loaded_store = Prodict.from_dict(loaded_store) item_list = '' for i, item in enumerate(loaded_store.inventory): item = Prodict.from_dict(item) if user['quote_to'] != 'USD': rates = await coins.rate_convert() item.price = rates[user['quote_to']] * item.price item.payout = rates[user['quote_to']] * item.payout formatted_price = currency.symbol(user["quote_to"]) + '{0:.2f}'.format(item.price) formatted_payout = "{0:.2f}".format(item.payout) item_list += f'{i + 1}. {item.name}{" " * (18 - len(item.name))}{formatted_price}{" " * (10 - len(formatted_price))}{item.about.format(payout=formatted_payout)}\n' await ctx.send( f'```py\n{user.quote_to}\n{loaded_store.name}\n\nItem{" " * (21 - len("item"))}Price{" " * (10 - len("price"))}Description\n\n{item_list}```')
def display_results(): currency1 = request.args.get('currency1') currency2 = request.args.get('currency2') amount = request.args.get('amount') new_amount = convert(currency1, currency2, amount) if type(new_amount) is dict: validity = new_amount session['invalid'] = [validity, currency1, currency2, amount] return redirect('/') return render_template('results.html', c1=symbol(currency1), c2=symbol(currency2), amount=amount, new_amount=new_amount)
def get_symbol(self, statement): """Convert a currency abbreviation to a symbol (e.g. 'GBP' to '£') :param dict statement: Statement data :return: str symbol: The currency symbol """ symbol = currency.symbol(statement['account']['currency']) return symbol
def get_more_info(name_parts): code = name_parts['currency'] cur_name = currency.name(code) cur_symbol = currency.symbol(code) code2 = name_parts['territory'] country = pycountry.countries.get(alpha_2=code2) ter_alpha2 = country.alpha_2 ter_alpha3 = country.alpha_3 ter_name = country.name save_obj(cur_name, cur_symbol, ter_alpha3, ter_alpha2, ter_name, name_parts)
def test_symbol(self): """ test symbol """ self.assertEqual(currency.symbol('USD'), '$') self.assertEqual(currency.symbol('EUR'), '€') self.assertEqual(currency.symbol('JPY'), '¥') self.assertEqual(currency.symbol('CAD'), '$') self.assertEqual(currency.symbol('CAD', native=False), 'CA$') self.assertEqual(currency.symbol('NOK'), 'kr') self.assertEqual(currency.symbol('NOK', native=False), 'Nkr')
def FindCurrencySymbols(self, df): symbolsList = [] for countryCurrency in df["countryCurrency"]: countryCurrency = str(countryCurrency) if countryCurrency == 'BMD': symbolsList.append("$") continue if countryCurrency == "MNT": symbolsList.append("₮") continue if countryCurrency == "LAK": symbolsList.append("₭") continue else: symbol = currency.symbol(countryCurrency) symbol = str(symbol) symbolsList.append(symbol) df['currency_symbol'] = symbolsList return (df)
async def generate_chart(ctx, symbols: str, quote: str, sort_key='percent_change_24h', sort_dir='asc'): chart = '' coins = await get_coins(quote) coins = sort_coins(coins, sort_key, sort_dir, quote) for coin in coins: if coin['symbol'] in symbols: priceint = float(coin['quotes'][quote]['price']) decimal_places = '{0:.6f}' if quote not in ['BTC', 'ETH'] else '{0:.8f}' price = format_number( float('{0:.2f}'.format(priceint) if priceint > 1 else decimal_places.format(priceint))) change = '{0:.2f}'.format(float(coin['quotes'][quote]['percent_change_24h'])) chart += '\n{color}{symbol}{symbol_spacing}{currency_symbol}{price}{price_spacing}%{change}'.format( color='+' if float(change) >= 0 else '-', change=change, price=str(price), symbol=coin['symbol'] or 'N/A', currency_symbol=currency.symbol(quote), symbol_spacing=' ' * (8 - int(len(coin['symbol']))), price_spacing=' ' * (14 - int(len(price))) ) return chart
def updateDisplay(config, pricestack, whichcoin, fiat): symbolstring = currency.symbol(fiat.upper()) if fiat == "jpy": symbolstring = "¥" pricenow = pricestack[-1] currencythumbnail = 'currency/' + whichcoin + '.bmp' tokenimage = Image.open(os.path.join(picdir, currencythumbnail)) sparkbitmap = Image.open(os.path.join(picdir, 'spark.bmp')) pricechange = str("%+d" % round( (pricestack[-1] - pricestack[0]) / pricestack[-1] * 100, 2)) + "%" if pricenow > 1000: pricenowstring = format(int(pricenow), ",") else: pricenowstring = str(float('%.5g' % pricenow)) if config['display']['orientation'] == 0 or config['display'][ 'orientation'] == 180: epd = epd2in7.EPD() epd.Init_4Gray() image = Image.new('L', (epd.width, epd.height), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((110, 80), "7day :", font=font_date, fill=0) draw.text((110, 95), pricechange, font=font_date, fill=0) # Print price to 5 significant figures draw.text((15, 200), symbolstring + pricenowstring, font=font, fill=0) draw.text((10, 10), str(time.strftime("%a %H:%M %d %b %Y")), font=font_date, fill=0) image.paste(tokenimage, (10, 25)) image.paste(sparkbitmap, (10, 125)) if config['display']['orientation'] == 180: image = image.rotate(180, expand=True) if config['display']['orientation'] == 90 or config['display'][ 'orientation'] == 270: epd = epd2in7.EPD() epd.Init_4Gray() image = Image.new('L', (epd.height, epd.width), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((100, 100), "7day : " + pricechange, font=font_date, fill=0) # Print price to 5 significant figures # draw.text((20,120),symbolstring,font =fonthiddenprice,fill = 0) draw.text((10, 120), symbolstring + pricenowstring, font=fontHorizontal, fill=0) image.paste(sparkbitmap, (80, 50)) image.paste(tokenimage, (0, 0)) draw.text((85, 5), str(time.strftime("%a %H:%M %d %b %Y")), font=font_date, fill=0) if config['display']['orientation'] == 270: image = image.rotate(180, expand=True) # This is a hack to deal with the mirroring that goes on in 4Gray Horizontal image = ImageOps.mirror(image) # If the display is inverted, invert the image usinng ImageOps if config['display']['inverted'] == True: image = ImageOps.invert(image) # Send the image to the screen epd.display_4Gray(epd.getbuffer_4Gray(image)) epd.sleep()
def updateDisplay(epd, config, pricestack, other): """ Takes the price data, the desired coin/fiat combo along with the config info for formatting if config is re-written following adustment we could avoid passing the last two arguments as they will just be the first two items of their string in config """ whichcoin, fiat = configtocoinandfiat(config) days_ago = int(config['ticker']['sparklinedays']) symbolstring = currency.symbol(fiat.upper()) if fiat == "jpy" or fiat == "cny": symbolstring = "¥" pricenow = pricestack[-1] currencythumbnail = 'currency/' + whichcoin + '.bmp' tokenfilename = os.path.join(picdir, currencythumbnail) sparkbitmap = Image.open(os.path.join(picdir, 'spark.bmp')) ATHbitmap = Image.open(os.path.join(picdir, 'ATH.bmp')) # Check for token image, if there isn't one, get on off coingecko, resize it and pop it on a white background if os.path.isfile(tokenfilename): logging.info("Getting token Image from Image directory") tokenimage = Image.open(tokenfilename).convert("RGBA") else: logging.info("Getting token Image from Coingecko") tokenimageurl = "https://api.coingecko.com/api/v3/coins/" + whichcoin + "?tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false" rawimage = requests.get(tokenimageurl).json() tokenimage = Image.open( requests.get(rawimage['image']['large'], stream=True).raw).convert("RGBA") resize = 100, 100 tokenimage.thumbnail(resize, Image.ANTIALIAS) new_image = Image.new( "RGBA", (120, 120), "WHITE") # Create a white rgba background with a 10 pixel border new_image.paste(tokenimage, (10, 10), tokenimage) tokenimage = new_image tokenimage.thumbnail((100, 100), Image.ANTIALIAS) tokenimage.save(tokenfilename) pricechange = str("%+d" % round( (pricestack[-1] - pricestack[0]) / pricestack[-1] * 100, 2)) + "%" if pricenow > 1000: pricenowstring = format(int(pricenow), ",") else: # Print price to 5 significant figures pricenowstring = str(float('%.5g' % pricenow)) if config['display']['orientation'] == 0 or config['display'][ 'orientation'] == 180: image = Image.new('L', (epd.width, epd.height), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((110, 80), str(days_ago) + "day :", font=font_date, fill=0) draw.text((110, 95), pricechange, font=font_date, fill=0) writewrappedlines(image, symbolstring + pricenowstring, 40, 65, 8, 10, "Roboto-Medium") draw.text((10, 10), str(time.strftime("%H:%M %a %d %b %Y")), font=font_date, fill=0) image.paste(tokenimage, (10, 25)) image.paste(sparkbitmap, (10, 125)) if config['display']['orientation'] == 180: image = image.rotate(180, expand=True) if config['display']['orientation'] == 90 or config['display'][ 'orientation'] == 270: image = Image.new('L', (epd.height, epd.width), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) if other['ATH'] == True: image.paste(ATHbitmap, (190, 85)) draw.text((110, 90), str(days_ago) + " day : " + pricechange, font=font_date, fill=0) # uncomment the line below to show volume # draw.text((110,105),"24h vol : " + human_format(other['volume']),font =font_date,fill = 0) writewrappedlines(image, symbolstring + pricenowstring, 50, 55, 8, 10, "Roboto-Medium") image.paste(sparkbitmap, (80, 40)) image.paste(tokenimage, (0, 10)) # draw.text((5,110),"In retrospect, it was inevitable",font =font_date,fill = 0) draw.text((95, 15), str(time.strftime("%H:%M %a %d %b %Y")), font=font_date, fill=0) if config['display']['orientation'] == 270: image = image.rotate(180, expand=True) # This is a hack to deal with the mirroring that goes on in 4Gray Horizontal image = ImageOps.mirror(image) # If the display is inverted, invert the image usinng ImageOps if config['display']['inverted'] == True: image = ImageOps.invert(image) # Return the ticker image # sparkbitmap.close() tokenimage.close() return image
async def _portfolio(self, ctx, page: int = 1): """ Check your portfolio """ if ctx.invoked_subcommand is None: user = await author.get(ctx.author) if not user.game.portfolio.coins: await ctx.send( f'```fix\nYou don\'t have any coins in your portfolio```') return await ctx.send_help('buy coin') message = await ctx.send(f'```Fetching prices...```') per_page = self.config.game.portfolio_per_page page_count = 1 coin_list = await coins.get_coins(user['quote_to']) portfolio = '' total_value = await coins.portfolio_value(user, coin_list) total_cost = 0 pcoins = user.game.portfolio.coins total_cost = sum(item['cost'] for item in pcoins) if len(pcoins) > per_page: pcoins = [ pcoins[i:i + per_page] for i in range(0, len(pcoins), per_page) ] page_count = len(pcoins) user.game.portfolio.coins = pcoins[page - 1] if page == 0 or page > page_count: # remove fetch message await message.delete() return for coin in user.game.portfolio.coins: coin = Prodict.from_dict(coin) value = await coins.get_value(coin.symbol, user['quote_to'], coin.name, coin.amount, coin_list) percent_change = coins.percent(coin['cost'], value) formatted_holdings = millify(coin.amount, precision=4) formatted_percent = millify(percent_change, precision=2) formatted_value = millify(value, precision=2) color = '+' if percent_change >= 0.00 else '-' portfolio += f'{color}{coin.symbol}{" " * (7 - len(coin.symbol))}{formatted_holdings}{" " * (12 - len(formatted_holdings))}{currency.symbol(user["quote_to"])}{formatted_value}{" " * (9 - len(formatted_value))}%{formatted_percent}\n' percent_change = coins.percent(total_cost, total_value) percent_color = '+' if percent_change >= 0.00 else '-' portfolio_value = currency.symbol( user['quote_to']) + '{0:.2f}'.format(total_value + user['game']['money'] + user['game']['in_pocket']) total_value = currency.symbol( user["quote_to"]) + '{0:.2f}'.format(total_value) total_cost = currency.symbol( user["quote_to"]) + '{0:.2f}'.format(total_cost) percent_change = '{0:.2f}'.format(percent_change) in_bank = currency.symbol(user["quote_to"]) + '{0:.2f}'.format( user['game']['money']) in_pocket = currency.symbol(user["quote_to"]) + '{0:.2f}'.format( user['game']['in_pocket']) portfolio_info = f'Value{" " * (15 - len("Value"))}Invested{" " * (12 - len("Value"))}%Change\n{total_value}{" " * (15 - len(str(total_value)))}{total_cost}{" " * (15 - len(str(total_cost)))}%{percent_change}' balance = f'In Pocket: {in_pocket}\nBank: {in_bank}\nNet worth: {portfolio_value}' table_header = f'Symbol{" " * (8 - len("Symbol"))}Holdings{" " * (12 - len("Holdings"))}Value{" " * (10 - len("Value"))}%Change' mention = ctx.author.mention return await message.edit( content= f'```diff\n{user["quote_to"]}\n{table_header}\n{portfolio}\n{" " * 15}Page {page} of {page_count}``````py\n{portfolio_info}\n``````py\n{balance}```{mention}' )
async def portfolio_holding(self, ctx, symbol: str): """ View a specific portfolio holding transactions""" user = await author.get(ctx.author) mention = ctx.author.mention if not await coins.valid_symbols([symbol.upper()]): return await ctx.send(f'```fix\nInvalid symbol```') if not any(d['symbol'] == symbol.upper() for d in user.game.portfolio.transactions): return await ctx.send( f'```fix\nYou don\'t hold any {symbol.upper()}```') has_dupes = coins.portfolio_check_for_dupes(user, symbol.upper()) multiple = False if len(has_dupes) > 1: multiple = True cn_list = '' for i in range(len(has_dupes)): cn_list += f'\n{i + 1}. {has_dupes[i]}' await ctx.send( f'```diff\nPortfolio contains more than one coin with symbol "{symbol.upper()}" please select one:\n{cn_list}\n```{mention}' ) def pred(m): return m.author == ctx.message.author and m.channel == ctx.message.channel try: msg = await self.bot.wait_for('message', check=pred, timeout=15.0) selected_coin = msg.content except asyncio.TimeoutError: return await ctx.send( f'```fix\nYou took too long...\n```{mention}') else: if not selected_coin.isdigit() or (int(selected_coin) - 1) not in range( len(has_dupes)): return await ctx.send( f'```fix\nInvalid selection\n```{mention}') transactions = [ item for item in user.game.portfolio.transactions if item['symbol'] == symbol.upper() and item['name'] == has_dupes[int(selected_coin) - 1] ] else: transactions = [ item for item in user.game.portfolio.transactions if item['symbol'] == symbol.upper() ] tx_list = '' total_amount = 0 coin_name = '' for tx in transactions: coin_name = tx['name'] total_amount += float('{0:.8f}'.format(tx["amount"])) formatted_amount = millify(tx["amount"], precision=4) formatted_cost = currency.symbol(user['quote_to']) + millify( tx["cost"], precision=2 if tx['cost'] > 0 else 6) formatted_price = currency.symbol(user['quote_to']) + millify( tx["coin_price"], precision=2 if tx['coin_price'] > .01 else 6) tx_list += f'\n{formatted_amount}{" " * (12 - len(formatted_amount))}{formatted_cost}{" " * (12 - len(formatted_cost))}{formatted_price}' table_header = f'\nAmount{" " * (12 - len("Amount"))}Cost{" " * (12 - len("Cost"))}Price' await ctx.send( f'```diff\nTransactions for {symbol.upper()}{" - " + coin_name if multiple else ""}:\nTotal: {total_amount}\n{table_header}\n{tx_list}\n```{mention}' )
async def portfolio_user(self, ctx, user: Union[discord.Member, str], page: int = 1): """ View another users portfolio """ if not user == self.bot.user: if not type(user) is discord.Member: user = Prodict.from_dict(User.find_one({'name': user})) else: user = await author.get(user, False) if not user or not user.game.portfolio.coins: return await ctx.send(f'```fix\nUser has an empty portfolio```' ) message = await ctx.send(f'```Fetching prices...```') per_page = self.config.game.portfolio_per_page page_count = 1 coin_list = await coins.get_coins(user['quote_to']) portfolio = '' total_value = await coins.portfolio_value(user, coin_list) total_cost = 0 pcoins = user.game.portfolio.coins total_cost = sum(item['cost'] for item in pcoins) if len(pcoins) > per_page: pcoins = [ pcoins[i:i + per_page] for i in range(0, len(pcoins), per_page) ] page_count = len(pcoins) user.game.portfolio.coins = pcoins[page - 1] if page == 0 or page > page_count: await message.delete() return for coin in user.game.portfolio.coins: coin = Prodict.from_dict(coin) value = await coins.get_value(coin.symbol, user['quote_to'], coin.name, coin.amount, coin_list) percent_change = coins.percent(coin['cost'], value) formatted_holdings = millify(coin.amount, precision=4) formatted_percent = millify(percent_change, precision=2) formatted_value = millify(value, precision=2) color = '+' if percent_change >= 0.00 else '-' portfolio += f'{color}{coin.symbol}{" " * (7 - len(coin.symbol))}{formatted_holdings}{" " * (12 - len(formatted_holdings))}{currency.symbol(user["quote_to"])}{formatted_value}{" " * (9 - len(formatted_value))}%{formatted_percent}\n' percent_change = coins.percent(total_cost, total_value) percent_color = '+' if percent_change >= 0.00 else '-' portfolio_value = currency.symbol( user['quote_to']) + '{0:.2f}'.format(total_value + user['game']['money'] + user['game']['in_pocket']) total_value = currency.symbol( user["quote_to"]) + '{0:.2f}'.format(total_value) total_cost = currency.symbol( user["quote_to"]) + '{0:.2f}'.format(total_cost) percent_change = '{0:.2f}'.format(percent_change) in_bank = currency.symbol(user["quote_to"]) + '{0:.2f}'.format( user['game']['money']) in_pocket = currency.symbol(user["quote_to"]) + '{0:.2f}'.format( user['game']['in_pocket']) portfolio_info = f'Value: {total_value}\nInvested: {total_cost}\n{percent_color}%Change: %{percent_change}' balance = f'\nIn Pocket: {in_pocket}\nBank: {in_bank}\nNet worth: {portfolio_value}' table_header = f'Symbol{" " * (8 - len("Symbol"))}Holdings{" " * (12 - len("Holdings"))}Value{" " * (10 - len("Value"))}%Change' mention = ctx.author.mention return await message.edit( content= f'```{user.name}\'s Portfolio``````diff\n{user["quote_to"]}\n{table_header}\n{portfolio}\n{" " * 15}Page {page} of {page_count}``````diff\n{portfolio_info}\n``````py\n{balance}```{mention}' )
def updateDisplay(config, pricestack, whichcoin, fiat): """ Takes the price data, the desired coin/fiat combo along with the config info for formatting if config is re-written following adustment we could avoid passing the last two arguments as they will just be the first two items of their string in config """ days_ago = int(config['ticker']['sparklinedays']) symbolstring = currency.symbol(fiat.upper()) if fiat == "jpy": symbolstring = "¥" pricenow = pricestack[-1] currencythumbnail = 'currency/' + whichcoin + '.bmp' tokenimage = Image.open(os.path.join(picdir, currencythumbnail)) sparkbitmap = Image.open(os.path.join(picdir, 'spark.bmp')) pricechange = str("%+d" % round( (pricestack[-1] - pricestack[0]) / pricestack[-1] * 100, 2)) + "%" if pricenow > 1000: pricenowstring = format(int(pricenow), ",") else: pricenowstring = str(float('%.5g' % pricenow)) if config['display']['orientation'] == 0 or config['display'][ 'orientation'] == 180: epd = epd2in7.EPD() epd.Init_4Gray() image = Image.new('L', (epd.width, epd.height), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((110, 80), str(days_ago) + "day :", font=font_date, fill=0) draw.text((110, 95), pricechange, font=font_date, fill=0) # Print price to 5 significant figures draw.text((15, 200), symbolstring + pricenowstring, font=font, fill=0) draw.text((10, 10), str(time.strftime("%H:%M %a %d %b %Y")), font=font_date, fill=0) image.paste(tokenimage, (10, 25)) image.paste(sparkbitmap, (10, 125)) if config['display']['orientation'] == 180: image = image.rotate(180, expand=True) if config['display']['orientation'] == 90 or config['display'][ 'orientation'] == 270: epd = epd2in7.EPD() epd.Init_4Gray() image = Image.new('L', (epd.height, epd.width), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((110, 90), str(days_ago) + "day : " + pricechange, font=font_date, fill=0) # Print price to 5 significant figures # draw.text((20,120),symbolstring,font =fonthiddenprice,fill = 0) draw.text((10, 120), symbolstring + pricenowstring, font=fontHorizontal, fill=0) image.paste(sparkbitmap, (80, 40)) image.paste(tokenimage, (0, 10)) draw.text((95, 15), str(time.strftime("%H:%M %a %d %b %Y")), font=font_date, fill=0) if config['display']['orientation'] == 270: image = image.rotate(180, expand=True) # This is a hack to deal with the mirroring that goes on in 4Gray Horizontal image = ImageOps.mirror(image) # If the display is inverted, invert the image usinng ImageOps if config['display']['inverted'] == True: image = ImageOps.invert(image) # Send the image to the screen epd.display_4Gray(epd.getbuffer_4Gray(image)) epd.sleep()
def test_symbol(self): self.assertEquals(symbol('USD'), 'US$')
def crypto(update, context): new_message.new_message(update) with open('config.yaml', 'r') as f: config = yaml.full_load(f) apikey = config['CRYPTO']['API_KEY'] if enable_check.enable_check(__name__): return def changepct(time): if len(context.args) >= 2: currency1 = context.args[1] else: currency1 = "BTC" if len(context.args) == 3: currency2 = context.args[2] else: currency2 = "USD" url = f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?CMC_PRO_API_KEY={apikey}&symbol={currency1.upper()}&convert={currency2.upper()}" r = requests.get(url) msg = r.json()['data'][currency1.upper()]['quote'][ currency2.upper()][f'percent_change_{time[:-1]}'] if msg > 0.01 or msg < -0.01: msg = round(msg, 2) if msg > 0.0: msg = f"+{msg}" return msg # crypto % change for past 24h, 7d, 30d if len(context.args) >= 1 and context.args[0] in ['24h%', '7d%', '30d%']: msg = changepct(context.args[0]) context.bot.send_message(chat_id=update.message.chat_id, text=f'{msg}%') # /crypto 24h btc elif len(context.args) >= 1 and context.args[0] == "24h": if len(context.args) >= 2: currency1 = context.args[1] else: currency1 = "BTC" if len(context.args) == 3: currency2 = context.args[2] else: currency2 = "USD" try: symbol = currency.symbol(currency2, native=False) except: symbol = "" avg = cryptocompare.get_avg(currency1, currency=currency2) msg = avg['CHANGE24HOUR'] if msg > 0.01 or msg < -0.01: msg = round(msg, 2) if msg > 0.0: msg = f"+{msg}" context.bot.send_message(chat_id=update.message.chat_id, text=f"{msg}{symbol}") # /crypto btc eur elif len(context.args) >= 1: currency1 = context.args[0].upper() if len(context.args) == 2: currency2 = context.args[1].upper() else: currency2 = "USD" try: symbol = currency.symbol(currency2, native=False) except: symbol = '' price = cryptocompare.get_price(currency1, currency=currency2, full=False) if price: context.bot.send_message( chat_id=update.message.chat_id, text=f"{symbol}{price[currency1][currency2]}") else: context.bot.send_message(chat_id=update.message.chat_id, text=f"Sorry, can\'t find {currency1}") return elif not context.args or len(context.args) > 3: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/crypto <btc,eth,xmr,etc>`') return
def sendInvoiceData(): request_data = request.get_json() #extract the data we are going to use in table invoicedatas = request_data["invoice_data"] #initalized with global scope as we need them in for loop total_amount_before_tax = 0.0 total_cgst_amount = 0.0 total_sgst_amount = 0.0 total_tax_amount = 0.0 total_amount_after_tax = 0.0 # gives the amount in words server_invoice = [] for data in invoicedatas: amt_before = float(data["taxable_value"]) #check if any discounts offered if float(data["discount_percentage"]) != 0: #calculate amount of discount with calculate_gst() discount_before_tax = calculate_gst(data["discount_percentage"], amt_before) # calculate amount after applying discount discount_applied_amount = amt_before - discount_before_tax #now calculate cgst and sgst cgst_amt = calculate_gst(data["CGST"], amt_before) sgst_amt = calculate_gst(data["SGST"], amt_before) total_amount_sale_line_item = (discount_applied_amount + cgst_amt + sgst_amt) total_amount_after_tax += total_amount_sale_line_item total_amount_before_tax += amt_before total_cgst_amount += cgst_amt total_sgst_amount += sgst_amt total_tax_amount += cgst_amt + sgst_amt #adding everything we caluclated to dict array updated_json = data currency_code = request_data["currency_code"] formatted_total_before_tax = currency.pretty( amt_before, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_cgst_amount = currency.pretty( cgst_amt, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_sgst_amount = currency.pretty( sgst_amt, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_total_amount_sale_line_item = currency.pretty( total_amount_sale_line_item, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_discount_amount = currency.pretty( discount_before_tax, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") updated_json.update({ "cgst_amt": formatted_cgst_amount, "sgst_amt": formatted_sgst_amount, "formatted_total_before_tax": formatted_total_before_tax, "formatted_discount_amount": formatted_discount_amount, "formatted_total_amount_sale_line_item": formatted_total_amount_sale_line_item }) server_invoice.append(updated_json) else: #now calculate cgst and sgst for non discounted cgst_amt = calculate_gst(data["CGST"], amt_before) sgst_amt = calculate_gst(data["SGST"], amt_before) total_amount_sale_line_item = amt_before + cgst_amt + sgst_amt total_amount_after_tax += total_amount_sale_line_item total_amount_before_tax += amt_before total_cgst_amount += cgst_amt total_sgst_amount += sgst_amt total_tax_amount += cgst_amt + sgst_amt updated_json = data currency_code = request_data["currency_code"] # format the amount with currency symbol before rendering template formatted_total_before_tax = currency.pretty( amt_before, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_cgst_amount = currency.pretty( cgst_amt, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_sgst_amount = currency.pretty( sgst_amt, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_total_amount_sale_line_item = currency.pretty( total_amount_sale_line_item, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") updated_json.update({ "cgst_amt": formatted_cgst_amount, "sgst_amt": formatted_sgst_amount, "formatted_total_before_tax": formatted_total_before_tax, "total_amount_sale_line_item": formatted_total_amount_sale_line_item }) server_invoice.append(updated_json) total_amount_in_words = num2words(total_amount_after_tax) formatted_total_amount_before_tax = currency.pretty( total_amount_before_tax, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_total_cgst_amount = currency.pretty( total_cgst_amount, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_total_sgst_amount = currency.pretty( total_sgst_amount, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_total_tax_amount = currency.pretty( total_tax_amount, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_total_amount_after_tax = currency.pretty( total_amount_after_tax, currency_code, trim=True).replace( (currency.symbol(currency_code)), (currency.symbol(currency_code)) + " ") formatted_meta_invoice_data = { "total_amount_in_words": total_amount_in_words, "formatted_total_amount_before_tax": formatted_total_amount_before_tax, "formatted_total_cgst_amount": formatted_total_cgst_amount, "formatted_total_sgst_amount": formatted_total_sgst_amount, "formatted_total_tax_amount": formatted_total_tax_amount, "formatted_total_amount_after_tax": formatted_total_amount_after_tax } user_json = dumps(request_data) invoice_meta_data = json.loads(user_json) # try server_invoice is array of json so iterate it through for loop invoice_url = generateRandomUrl(request_data["company_name"]) t_data = request_data t_data.update({"invoice_url": invoice_url}) db.history.insert(t_data) htmlpage = render_template('index.html', uf_meta=invoice_meta_data, f_meta=formatted_meta_invoice_data, si=server_invoice) html_file = open("static/pdf_stored/" + invoice_url + ".html", "w") html_file.write(htmlpage) html_file.close() invoice_name = invoice_url.replace("%20", " ").replace("%2D", "-") pdfkit.from_file("static/pdf_stored/" + invoice_url + ".html", "static/pdf_stored/" + invoice_name + ".pdf") remove("static/pdf_stored/" + invoice_url + ".html") external_ip = urllib.request.urlopen('https://ident.me').read().decode( 'utf8') return "https://" + str( external_ip) + ":4004" + "/static/pdf_stored/" + invoice_name + ".pdf"
def updateDisplay(config,pricestack,whichcoin,fiat,other): """ Takes the price data, the desired coin/fiat combo along with the config info for formatting if config is re-written following adustment we could avoid passing the last two arguments as they will just be the first two items of their string in config """ days_ago=int(config['ticker']['sparklinedays']) symbolstring=currency.symbol(fiat.upper()) if fiat=="jpy" or fiat=="cny": symbolstring="¥" pricenow = pricestack[-1] currencythumbnail= 'currency/'+whichcoin+'.bmp' tokenfilename = os.path.join(picdir,currencythumbnail) sparkbitmap = Image.open(os.path.join(picdir,'spark.bmp')) ATHbitmap= Image.open(os.path.join(picdir,'ATH.bmp')) # Check for token image, if there isn't one, get on off coingecko, resize it and pop it on a white background if os.path.isfile(tokenfilename): logging.info("Getting token Image from Image directory") tokenimage = Image.open(tokenfilename).convert("RGBA") else: logging.info("Getting token Image from Coingecko") tokenimageurl = "https://api.coingecko.com/api/v3/coins/"+whichcoin+"?tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false" rawimage = requests.get(tokenimageurl).json() tokenimage = Image.open(requests.get(rawimage['image']['large'], stream=True).raw).convert("RGBA") resize = 100,100 tokenimage.thumbnail(resize, Image.ANTIALIAS) new_image = Image.new("RGBA", (120,120), "WHITE") # Create a white rgba background with a 10 pixel border new_image.paste(tokenimage, (10, 10), tokenimage) tokenimage=new_image tokenimage.thumbnail((100,100),Image.ANTIALIAS) tokenimage.save(tokenfilename) pricechange = str("%+d" % round((pricestack[-1]-pricestack[0])/pricestack[-1]*100,2))+"%" if pricenow > 1000: pricenowstring =format(int(pricenow),",") else: pricenowstring =str(float('%.5g' % pricenow)) if config['display']['orientation'] == 0 or config['display']['orientation'] == 180 : epd = epd2in13_V2.EPD() epd.init(epd.FULL_UPDATE) image = Image.new('L', (epd.width, epd.height), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((110,80),str(days_ago)+"day :",font =font_date,fill = 0) draw.text((110,95),pricechange,font =font_date,fill = 0) # Print price to 5 significant figures draw.text((15,200),symbolstring+pricenowstring,font =font,fill = 0) draw.text((10,10),str(time.strftime("%H:%M %a %d %b %Y")),font =font_date,fill = 0) image.paste(tokenimage, (10,25)) image.paste(sparkbitmap,(10,125)) if config['display']['orientation'] == 180 : image=image.rotate(180, expand=True) if config['display']['orientation'] == 90 or config['display']['orientation'] == 270 : epd = epd2in13_V2.EPD() epd.init(epd.FULL_UPDATE) image = Image.new('L', (epd.height, epd.width), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((135,85),str(days_ago)+" day : "+pricechange,font =font_date,fill = 0) #mining if config['mining']['enabled'] == True : host = 'https://api2.nicehash.com' #host connection organisation_id = str(config['mining']['organisation']) #organisation string key = str(config['mining']['key']) #public key string secret = str(config['mining']['secret']) #secret key string private_api = nicehash.private_api(host, organisation_id, key, secret) if config['mining']['display'] == "wallet,unpaid" or config['mining']['display'] == "wallet" : accounts = private_api.get_accounts() #get accounts json accountsdata = str(accounts['total']) #grab totals accountslist = accountsdata.split("'") #organize wallet = float(accountslist[7]) #isolate total balance currencydata = str(accounts['currencies']) currencylist = currencydata.split(":") rate = float('{:.8}'.format(currencylist[7])) total = wallet*rate balance = float('{:.2f}'.format(total)) if config['mining']['walletcurrency'] == "btc" : draw.text((100,13),"Wallet: "+str(wallet)+" BTC",font =font_mining2,fill = 0) #draw wallet balance if config['mining']['walletcurrency'] == "cad" : draw.text((100,13),"Wallet: $"+str(balance),font =font_mining,fill = 0) if config['mining']['display'] == "unpaid,wallet" or config['mining']['display'] == "unpaid" : unpaid = private_api.get_unpaid() #get unpaid json strdata = str(unpaid['data']) #grab "data" section and convert to string listdata = strdata.split(",") #organize maybe = float(listdata[2]) #grab total unpaid almost = format(float(maybe), '.8f') #convert form scientific to decimal float working = decimal.Decimal(almost) #convert from float to decimal ok = working * 100000000 #make whole number final = int(ok) #convert to integer to drop decimals draw.text((100,13),"Unpaid NH: "+str(final)+" Sat",font =font_mining,fill = 0) #draw unpaid mining #end mining #. uncomment the line below to show volume # draw.text((110,105),"24h vol : " + human_format(other['volume']),font =font_date,fill = 0) if config['ticker']['coinname'] == True : draw.text((100,100),symbolstring+pricenowstring+"/"+whichcoin,font =fontHorizontal,fill = 0) else: draw.text((135,100),symbolstring+pricenowstring,font =fontHorizontal,fill = 0) if other['ATH']==True: image.paste(ATHbitmap,(190,85)) image.paste(sparkbitmap,(80,25)) image.paste(tokenimage, (0,10)) # draw.text((5,110),"Inretrospect, it was inevitable",font =font_date,fill = 0) draw.text((95,1),str(time.strftime("%H:%M %a %d %b %Y")),font =font_date,fill = 0) if config['display']['orientation'] == 270 : image=image.rotate(180, expand=True) # This is a hack to deal with the mirroring that goes on in 4Gray Horizontal # image = ImageOps.mirror(image) # If the display is inverted, invert the image usinng ImageOps if config['display']['inverted'] == True: image = ImageOps.invert(image) # Send the image to the screen epd.display(epd.getbuffer(image))
def render_file(filename, search): text = textract.process('data/' + filename, method='pdfminer') text = text.decode('utf-8') months = get_months() m6 = [] print(search) if search == 'date': pattern1 = re.compile("[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]") pattern2 = re.compile("[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]") pattern3 = re.compile("[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]") pattern4 = re.compile("[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]") pattern5 = re.compile( "(?:{0})\s*[0-9][0-9]\W\s*[0-9][0-9][0-9][0-9]".format( '|'.join(months))) pattern6 = re.compile("[0-9][0-9]/(?:{0})/[0-9][0-9][0-9][0-9]".format( '|'.join(months))) pattern7 = re.compile("[0-9][0-9]-(?:{0})-[0-9][0-9][0-9][0-9]".format( '|'.join(months))) pattern8 = re.compile( "[0-9][0-9]\s*(?:{0})\s*[0-9][0-9][0-9][0-9]".format( '|'.join(months))) m1 = pattern1.findall(text) if len(m1) != 0: m6.extend(m1) m2 = pattern2.findall(text) print(m2) if len(m2) != 0: m6.extend(m2) print(m6) m3 = pattern3.findall(text) if len(m3) != 0: m6.extend(m3) m4 = pattern4.findall(text) if len(m4) != 0: m6.extend(m4) m5 = pattern6.findall(text) if len(m5) != 0: m6.extend(m5) m5 = pattern7.findall(text) if len(m5) != 0: m6.extend(m5) m5 = pattern8.findall(text) if len(m6) != 0: m6.extend(m5) m5 = pattern5.findall(text) if len(m5) != 0: m6.extend(m5) if search == 'whole numbers': pattern1 = re.compile("\d+(?!\.)") m1 = pattern1.findall(text) match = pattern1.search(text) print(match.groups('whole')) m6.extend(m1) m6 = [i for i in m6 if i != ''] if search == 'currency': print("hi") currenc = [] with open("data//currency.txt") as f: for line in f: currenc.append(line.split(" ")[0]) c = [] for i in currenc: try: c.append(currency.symbol(i)) except: pass print(c) c.append('Rs.') text = text.replace(',', '') pattern1 = re.compile("(?:{0})\s*[0-9]+".format('|'.join(c))) m1 = pattern1.findall(text) match = pattern1.search(text) m6.extend(m1) m6 = [i for i in m6 if i != ''] os.system('rm -f data/*.pdf') print("Deleted files") return render_template('index.html', text=text, matches=m6)