def cryptocurrency_exchanges(): countries = ['AUD', 'BGN', 'BRL', 'CAD', 'CHF', 'CNY', 'CZK', 'DKK', 'EUR', 'GBP', 'HKD', 'HRK', 'HUF', 'IDR', 'ILS', 'INR', 'ISK', 'JPY', 'KRW', 'MXN', 'MYR', 'NOK', 'NZD', 'PHP', 'PLN', 'RON', 'RUB', 'SEK', 'SGD', 'THB', 'TRY', 'USD', 'ZAR'] bitc = BtcConverter() raw_data = [] for data in countries: raw_data.append([data, bitc.get_latest_price(data)]) return render_template('cryptocurrency_exchanges.html', raw_data = raw_data)
def getexchange(self, message=None, match=None, to=None): amount = match.group("amount") price = BtcConverter() return TextMessageProtocolEntity( amount + " INR = " + str(price.convert_to_btc(int(amount), 'BTC')) + " INR", to=message.getFrom())
def fetch_exchange_rates( target_currency: str, currencies: Iterable[str], amount: float = 1.0, bitcoin_proxy: str = 'USD', ) -> Dict[str, Optional[float]]: """ Given an amount and a base currency, returns the exchange rates for a set of currencies. """ rates: Dict[str, Optional[float]] = {} rates_select: Dict[str, Optional[float]] = {} is_bitcoin: bool = False # Special case if base currency is BitCoin if target_currency == 'BTC': is_bitcoin = True target_currency = bitcoin_proxy # Instantiate converter converter = CurrencyRates() converter_btc = BtcConverter() # Get rates for base currency try: rates = converter.get_rates(target_currency) except ConnectionError: logger.warning( f"Could not connect to currency rates service. No exchange rates " \ f"available." ) return rates_select # Get Bitcoin rate for base currency try: rates['BTC'] = converter_btc.convert_to_btc(amount=amount, currency=bitcoin_proxy) except ConnectionError: logger.warning( f"Could not connect to currency rates service. No BitCoin " \ f"exchange rate available." ) return rates_select # Select rates for currency in currencies: if currency in rates: rates_select[currency] = rates[currency] else: rates_select[currency] = None # Convert to base BitCoin if BitCoin was base currency if is_bitcoin: rate_btc = rates_select['BTC'] for currency in rates_select.keys(): if rates_select[currency]: rates_select[currency] = rates_select[currency] / rate_btc return rates_select
def populate_table(): conn1 = sqlite3.connect('asset_prices.db') c1 = conn1.cursor() cur1 = CurrencyRates() cur2 = CurrencyRates() dollar = cur1.get_rate('USD', 'GBP') pound = cur2.get_rate('GBP', 'USD') yen = cur1.get_rate('JPY', 'USD') euro = cur2.get_rate('EUR', 'USD') b = BtcConverter() #getting the live updated price of bitcoin from forex python api bp = b.get_latest_price('USD') v = bp #print(bp) #print("===============") c1.execute( "INSERT INTO PRICES(Bitcoin_value,Dollar_value,Pound_value,Yen_value,Euro_value) VALUES (?,?,?,?,?)", ( bp, dollar, pound, yen, euro, )) conn1.commit()
def convert(c1, c2, amount): try: if amount == "": messagebox.showerror("Error", "Amount not specified") elif c1 == "Select" or c2 == "Select": messagebox.showinfo("Error", "Currency not selected") else: try: amount = float(amount) b = BtcConverter() c = CurrencyRates() if c1 == c2: result = amount elif c1 == "BTC": result = b.convert_btc_to_cur(amount, c2) elif c2 == "BTC": result = b.convert_to_btc(amount, c1) else: result = c.convert(c1, c2, int(amount)) print(result) label_down[ "text"] = f"Conversion Result: {amount} {c2}\n{amount} {c1} = {result} {c2}" except ValueError: messagebox.showerror("Error", "Invalid amount") clear() except Exception: messagebox.showerror("Error", "Please try again")
def currency_exchange(string): return_str = "" try: l = [] print(string) string = string.strip() string = re.sub(" +", " ", string) l = string.split(" ") l = [x.upper() for x in l] print(l) l = [x.replace(' ', '') for x in l] if "BITCOIN" in l: b = BtcConverter() if (l[0]).upper() == "BITCOIN": return_str = str(float(l[2]) * b.get_latest_price(l[1])) elif (l[1]).upper() == "BITCOIN": return_str = str(float(l[2]) / b.get_latest_price(l[0])) else: return_str = "Result Not found" else: c = CurrencyRates() return_str = str(c.convert(l[0], l[1], float(l[2]))) except Exception as e: return_str = "Give proper input" print(e) return return_str
def arcturus_cal(money, arcturus_rate, c_type, bonus=0): c = CurrencyRates() b = BtcConverter() print(c_type) if c_type == "USD": if int(money) >= 100: usd = float(money) no_of_btc = b.convert_to_btc(usd, 'USD') return {"no_of_arcturus": float(usd) / float(arcturus_rate)} else: return { "no_of_arcturus": "Error... Minimum transaction should be more then 100 usd" } elif c_type.upper() == "BTC": usd = b.convert_btc_to_cur(float(money), 'USD') if int(usd) >= 100: usd = float(usd) return {"no_of_arcturus": float(usd) / float(arcturus_rate)} else: return { "no_of_arcturus": "Minimum transaction should be more then 100 usd" } else: return {"no_of_arcturus": "Usupported cryptotype.... "}
async def currency_to_bitcoin(self, ctx, amount, currency="USD"): try: b = BtcConverter() amount = int(amount) except: embed = discord.Embed(color=self.bot.embed_color, title="→ Money Error!", description="• Not a valid amount of money!") await ctx.send(embed=embed) try: btc = round(b.convert_to_btc(amount, currency), 4) except: embed = discord.Embed( color=self.bot.embed_color, title="→ Currency Error!", description="• Not a valid currency!" "\n• Example: `l!tobtc 10 CAD`" "\n• Pro Tip: `If you use USD currency, you do not have to specify the currency in the command.`" ) await ctx.send(embed=embed) embed = discord.Embed( color=self.bot.embed_color, title="→ Currency To Bitcoin!", description=f"• {amount} {currency} is around {btc} Bitcoin!") await ctx.send(embed=embed) logger.info(f"Utility | Sent Currency_To_btc: {ctx.author}")
def getprice(self, message=None, match=None, to=None, currency="INR"): currency = match.group("currency").upper() if "RUPEES" in currency: currency = "INR" price = BtcConverter() return TextMessageProtocolEntity( "1BTC = " + str(price.get_latest_price(currency)) + " " + currency, to=message.getFrom())
def background(self): def get_quandl_data(quandl_id): '''Download and cache Quandl dataseries''' ''' cache_path = '{}.pkl'.format(quandl_id).replace('/','-') try: f = open(cache_path, 'rb') df = pickle.load(f) #print('Loaded {} from cache'.format(quandl_id)) except (OSError, IOError) as e: #print('Downloading {} from Quandl'.format(quandl_id)) df = quandl.get(quandl_id, returns="pandas") df.to_pickle(cache_path) #print('Cached {} at {}'.format(quandl_id, cache_path)) ''' df = quandl.get(quandl_id, returns="pandas") return df b = BtcConverter( ) # add "force_decimal=True" parmeter to get Decimal rates btc = b.get_latest_price('USD') self.btc_rate = btc btc_usd_price_kraken = get_quandl_data('BCHARTS/KRAKENUSD') X = btc_usd_price_kraken.index Y = btc_usd_price_kraken['Weighted Price'] x = X[-70:] y = Y[-70:] #print x #print y height = 14 width = 70 range_x = max(x) - min(x) range_y = max(y) - min(y) #dx = range_x//width self.dy = range_y // height self.height = height self.width = width self.max_x = max(x) self.min_x = min(x) self.max_y = max(y) self.min_y = min(y) self.coords = [0 for i in x] self.x = x self.y = y #graph = [[" " for j in range(width)] for i in range(height)] for i, xx in enumerate(x): x_coord = int((x[i] - min(x)).total_seconds() / (range_x.total_seconds()) * (width - 1)) #from IPython import embed #embed() y_coord = int((y[i] - min(y)) / range_y * (height - 1)) self.coords[i] = (x_coord, y_coord)
def bitcoin_data(): ''' Gets bitcoin values from last 365 days. ''' b = BtcConverter() year_ago = DATE - timedelta(days=365) bitcoin_values = list( b.get_previous_price_list('USD', year_ago, DATE).values()) return bitcoin_values
def price(): b = BtcConverter() bitcoin_price = b.get_latest_price('USD') coinmarketcap = Market() y = coinmarketcap.ticker(start=0, limit=2, convert='USD') return { "btc": bitcoin_price, "eth": y["data"]["1027"]["quotes"]['USD']['price'] }
def get(self, request): try: form = CurrencyForm() value = 0 btc = BtcConverter() price = round(btc.get_latest_price('PLN'), 2) context = {'form': form, 'value': value, 'price': price} return render(request, self.template_name, context) except: return redirect('/')
def do_update(self): from forex_python.bitcoin import BtcConverter log.info("fetching currency update") bitcoin = BtcConverter() try: btc = bitcoin.get_latest_price('EUR') self.text = "1 Bitcoin = %s%.2f EUR" % (self.get_color_compare( btc, self.last_btc), btc) self.last_btc = btc except requests.exceptions.RequestException as e: logging.warning("couldn't get update: %s" % e)
def background(self): ''' possible_rates = ['GBPJPY=X','GBPAUD=X','GBPCNY=X','GBPBTC=X','GBPBND=X','GBPMXN=X','GBPCLP=X','GBPETB=X','GBPTRY=X','GBPCHF=X','GBPCAD=X','GBPXAU=X','BZJ16.NYM'] possible_symbols_before = [u'¥', 'A$|', u'CN¥|', u'฿', 'B$|', 'MX$|', 'CL$|', 'ETB|', u'₺', 'CHF|', 'C$|', '',''] possible_symbols_after = ['','','','','','','','','','','',u'㎎ gold','L oil'] possible_multiple = [1,1,1,1000,1,1,1,1,1,1,1,31103,1] possible_format = ['{:.0f}','{:.2f}','{:.2f}','{:.2f}','{:.2f}','{:.2f}','{:.0f}','{:.2f}','{:.2f}','{:.2f}','{:.2f}','{:.0f}','{:.2f}'] from random import randint random_rate1 = randint(0,len(possible_rates)-1) random_rate2 = random_rate1 random_rate3 = random_rate1 while random_rate2 == random_rate1: random_rate2 = randint(0,len(possible_rates)-1) while random_rate3 == random_rate1 or random_rate3 == random_rate2: random_rate3 = randint(0,len(possible_rates)-1) ask_for_rates = ['GBPUSD=X', 'GBPEUR=X', possible_rates[random_rate1], possible_rates[random_rate2], possible_rates[random_rate3]] self.currency_symbol_before = ['$',u"€",possible_symbols_before[random_rate1],possible_symbols_before[random_rate2],possible_symbols_before[random_rate3]] self.currency_symbol_after = ['','',possible_symbols_after[random_rate1],possible_symbols_after[random_rate2],possible_symbols_after[random_rate3]] self.currency_multiple = [1,1,possible_multiple[random_rate1],possible_multiple[random_rate2],possible_multiple[random_rate3]] self.currency_format = ['{:.2f}','{:.2f}',possible_format[random_rate1],possible_format[random_rate2],possible_format[random_rate3]] self.currency_rate = [] self.currency_change = [] results = url_handler.load('http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1p2d1t1&s='+','.join(ask_for_rates)) for i in range(len(ask_for_rates)): try: self.currency_rate.append(float(results.split(",")[4*i+1])) except: self.currency_rate.append(1) try: self.currency_change.append(float(results.split(",")[4*i+2][1:-2])) except: self.currency_change.append(0) # result = "USDNOK=X",5.9423,"5/3/2010","12:39pm" if random_rate1 == 12: #oil self.currency_rate[2] = 1./self.currency_rate[2]*158.987*self.currency_rate[0] self.currency_change[2] = "" if random_rate2 == 12: #oil self.currency_rate[3] = 1./self.currency_rate[3]*158.987*self.currency_rate[0] self.currency_change[3] = "" if random_rate3 == 12: #oil self.currency_rate[4] = 1./self.currency_rate[4]*158.987*self.currency_rate[0] self.currency_change[4] = "" ''' c = CurrencyRates() rates = c.get_rates('GBP') b = BtcConverter() # add "force_decimal=True" parmeter to get Decimal rates btc = b.get_latest_price('GBP') self.currency_rate = [rates['USD'], rates['EUR'], rates['CHF'], rates['JPY'], btc]
def convert(amount, input_currency, output_currency): input_currency_code = get_currency_code(input_currency) if input_currency_code is None: # Input currency code was not found - unknown currency raise UnknownCurrencyError if output_currency is not None: output_currency_code = get_currency_code(output_currency) if output_currency_code is None: # Output currency code was not found - unknown currency raise UnknownCurrencyError currency_data = [{'cc': output_currency_code}] else: # Getting currency data from file currency_data = get_currency_data() c = CurrencyRates() b = BtcConverter() output_currencies = dict( ) # Dictionary to store converted amounts for each currency # Converting currency for item in currency_data: if item['cc'] == input_currency_code: # Out currency == in currency if output_currency is None: continue else: raise SameCurrencyError try: if input_currency_code == "BTC": # Bitcoin is input currency output_currencies[item['cc']] = round( b.convert_btc_to_cur(amount, item['cc']), 2) elif item['cc'] == "BTC": # Bitcoin is output currency output_currencies[item['cc']] = round( b.convert_to_btc(amount, input_currency_code), 5) else: # Other currencies than bitcoin output_currencies[item['cc']] = round( c.convert(input_currency_code, item['cc'], amount), 2) except RatesNotAvailableError: if output_currency is None: # Output currency not entered, currencies without available rates are skipped pass else: # Output currency entered => not available currency rate yields error raise RatesNotAvailableError output_data = dict() output_data['input'] = {'amount': amount, 'currency': input_currency_code} output_data['output'] = output_currencies return json.dumps(output_data, indent='\t')
def index(): c = CurrencyRates() btc_converter = BtcConverter() price_json = c.get_rates('INR') result = [None, None, None] if (request.method == 'POST'): stock_name = request.form['stock_name'] if (stock_name != ""): result = callback(stock_name) else: result = [None, None, None, None] prices = [] for key, value in price_json.items(): prices.append((key, value, btc_converter.get_latest_price(key))) print('No of Supported Currencies: ', len(price_json), '||||File Type: ', type(price_json)) legend = 'BitCoin Price Index' temperatures = [ 73.7, 73.4, 73.8, 72.8, 68.7, 65.2, 61.8, 58.7, 58.2, 58.3, 60.5, 65.7, 70.2, 71.4, 71.2, 70.9, 71.3, 71.1 ] times = [ time(hour=11, minute=14, second=15), time(hour=11, minute=14, second=30), time(hour=11, minute=14, second=45), time(hour=11, minute=15, second=00), time(hour=11, minute=15, second=15), time(hour=11, minute=15, second=30), time(hour=11, minute=15, second=45), time(hour=11, minute=16, second=00), time(hour=11, minute=16, second=15), time(hour=11, minute=16, second=30), time(hour=11, minute=16, second=45), time(hour=11, minute=17, second=00), time(hour=11, minute=17, second=15), time(hour=11, minute=17, second=30), time(hour=11, minute=17, second=45), time(hour=11, minute=18, second=00), time(hour=11, minute=18, second=15), time(hour=11, minute=18, second=30) ] links = ['a', 'b', 'c'] return render_template('index.html', values=temperatures, labels=times, legend=legend, links=links, current_prices=prices, result=result)
def get_rate(currency='USD'): """ Return price of 1 currency in BTC Supported currencies available at http://forex-python.readthedocs.io/en/latest/currencysource.html#list-of-supported-currency-codes :param currency: currency to convert to :return: conversion rate from currency to BTC """ if currency is None: return None b = BtcConverter() factor = b.get_latest_price(currency) if factor is None: factor = 1.0 / fallback_get_rate(currency) return 1.0 / factor
def fetch_btc_price(self): """ Method to fetch the current bitcoin price. The price is in USD and is retreived from the CoinDesk index. : param self : return btc_price(float) error_val(int) """ error_val = -1 try: day_count = 1 today = datetime.now() start_date = today - timedelta(days=day_count) btc_price = pd.DataFrame([{ 'Date': start_date.strftime(DATE_FORMAT), 'btc_price': BtcConverter().get_previous_price(CURRENCY, start_date) }]) return btc_price.set_index(INDEX) except Exception as e: # self.logger.error(e) print(e) return error_val
def convert(currency, amount): # create a new converter object with standardized date b = BtcConverter() x = b.get_latest_price(currency) cprint('Powered by Coindesk | https://www.coindesk.com/price/', 'green') print("[" + str(dts) + "]" + " " + currency.upper() + " for 1.0 Bitcoin (BTC) is " + str(x)) # convert to BTC conversion_amount = b.convert_to_btc(amount, currency.upper()) print( "[{}] Converting {} to BTC: {} {} is currently worth {} BTC!".format( str(dts), currency.upper(), "%0.2f" % (amount), currency.upper(), conversion_amount))
def Left_click(event): btc_rate = BtcConverter() year = int(input_year.get()) month = int(input_month.get()) day = int(input_day.get()) period = int(input_forecast_period.get()) #forecast จากกี่วันย้อนหลัง refer_date = datetime( year, month, day - 2 ) #Current date ใส่ -2 เนื่องจากไม่สามารถดึงราคาปัจจุบันได้ bitcoin price deley 2 day sum_previous_price = 0 for i in range(period): date = refer_date - timedelta(days=i) previous_price = btc_rate.get_previous_price('THB', date) sum_previous_price += previous_price sample_moving_average = sum_previous_price / period result.configure(text=sample_moving_average)
def load_dreammarket(self): with pymongo.MongoClient('localhost', 27017) as client: db = client['drug_database'] table = db['dreammarket-testbase'] table1 = db['dreammarket'] docs = list(table.find()) + list(table1.find()) docs = add_scraping_session(docs) docs = {(doc['vendor'], doc['title'], doc['scraping_session'], doc['price']): doc for doc in docs}.values() #remove duplicates counts = sorted(Counter(d['scraping_session'] for d in docs).items()) bad_dates = [date for date, count in counts if count < 40000] docs = [d for d in docs if d['scraping_session'] not in bad_dates] c = BtcConverter() start_date = min(d['scraping_session'] for d in docs) end_date = max(d['scraping_session'] for d in docs) self.btc_rates = c.get_previous_price_list('EUR', start_date, end_date) self.btc_rates = {dt.datetime.strptime(date, '%Y-%m-%d'): rate for date, rate in self.btc_rates.items()} find_unit = re.compile(r'(\d+\.?\d*)\s*({})'.format('|'.join(self.units)), re.IGNORECASE) find_multi = re.compile(r'(\d+)\s*x', re.IGNORECASE) for doc in docs: del doc['_id'] doc['market'] = 'dreammarket' doc['ships_from'] = doc['ships_from'].strip() doc['ships_to'] = [s.strip() for s in doc['ships_to'].split(',')] match = find_unit.search(doc['title']) doc['price_unit'] = match.group(2).lower() if match else None doc['amount'] = float(match.group(1)) if match and float(match.group(1)) != 0 else 1 multi = find_multi.search(doc['title']) if multi and int(multi.group(1)) != 0: doc['amount'] *= int(multi.group(1)) if doc['price_unit'] not in self.gram_factors: self.bad_docs.append(doc) else: doc['price'] = to_float(doc['price'].strip('฿')) / doc['amount'] / self.gram_factors[doc['price_unit']] doc['date_mid'] = dt.datetime.combine(doc['scraping_session'].date(), dt.datetime.min.time()) # transfer dates to midnight doc['price'] *= self.btc_rates[doc['date_mid']] self.docs.append(doc)
def _load_bitcoin(start=date(2015, 1, 1), end=date.today(), currency='EUR'): """Load bitcoin dataset""" btcc = BtcConverter() def get_rate(day): return btcc.get_previous_price(currency, day) return _fetch(get_rate, start=start, end=end)
def currencyconverter(self): global audresp currency1 = audresp.currenciesinspeech[0].replace("£", "GBP").replace("$", "USD").replace("dollars", "USD").replace( "pounds", "GBP") currency2 = audresp.currenciesinspeech[1].replace("£", "GBP").replace("$", "USD").replace("dollars", "USD").replace( "pounds", "GBP") amount = audresp.numbers[0] crypto = ["bitcoin", "litcoin"] if currency2 == "bitcoin": b = BtcConverter() return str(b.convert_to_btc(amount, currency1)) + " btc" else: c = CurrencyRates() convertion = c.convert(currency1, currency2, amount) return currency2.replace("GBP", "£").replace("USD", "$") + str(convertion)
def currencyconv(self, jarvis, amount, fr, to): """ currencyconv converts the given amount to another currency using fore-python """ b = BtcConverter(force_decimal=True) c = CurrencyRates(force_decimal=True) if (to == "BTC"): result = b.convert_to_btc(Decimal(amount), fr) elif (fr == "BTC"): result = b.convert_btc_to_cur(Decimal(amount), to) else: result = c.convert(fr, to, Decimal(amount)) jarvis.say(str(result))
async def bitcoin(self, ctx, currency="USD"): try: b = BtcConverter() amount = round(b.get_latest_price(currency), 2) except: embed = discord.Embed(color=self.bot.embed_color, title="→ Currency error!", description="• Not a valid currency type!" "\n• Example: `l!bitcoin CAD`") await ctx.send(embed=embed) embed = discord.Embed( color=self.bot.embed_color, title="→ BTC to Currency", description=f"• One Bitcoin is: `{amount}` {currency}") await ctx.send(embed=embed) logger.info(f"Utility | Sent Bitcoin: {ctx.author}")
def currencyconv(self, jarvis, amount, fr, to): """ currencyconv converts the given amount to another currency using fore-python """ b = BtcConverter(force_decimal=True) c = CurrencyRates(force_decimal=True) if (to == "BTC"): result = b.convert_to_btc(Decimal(amount), fr) elif (fr == "BTC"): result = b.convert_btc_to_cur(Decimal(amount), to) else: result = c.convert(fr, to, Decimal(amount)) outputText = str(amount) + " " + fr + \ " are equal to " + str(result) + " " + to jarvis.say(outputText)
def rates(self): usd = CurrencyRates().get_rate('USD', 'TRY') eur = CurrencyRates().get_rate('EUR', 'TRY') btc = BtcConverter().get_latest_price('USD') return { 'full_text': '$: ' + str(usd) + ' €: ' + str(eur) + ' ₿: ' + str(btc), 'cached_until': self.py3.time_in(self.cache_timeout) }
def base(): """Show base.html.""" c = CurrencyRates() x = c.get_rates("USD") res = {item: "{0:.2f}".format(round(x[item], 2)) for item in x} session["rates"] = res b = BtcConverter() bit = {} bit["bitcoin_usd"] = round(b.get_latest_price("USD"), 2) bit["bitcoin_eur"] = round(b.get_latest_price("EUR"), 2) bit["bitcoin_gbp"] = round(b.get_latest_price("GBP"), 2) cc = CurrencyCodes() bit["name_usd"] = cc.get_currency_name("USD") bit["name_eur"] = cc.get_currency_name("EUR") bit["name_gbp"] = cc.get_currency_name("GBP") bit["symbol"] = b.get_symbol() bit["symbol_eur"] = cc.get_symbol("EUR") bit["symbol_gbp"] = cc.get_symbol("GBP") session["bit"] = bit return render_template("base.html", rates=res, bit=bit)
def post(self, request): try: form = CurrencyForm(request.POST) if form.is_valid(): a = form.cleaned_data['currency_one'].upper() amount = form.cleaned_data['amount'] b = form.cleaned_data['currency_two'].upper() value = convert(a, b, amount) btc = BtcConverter() price = round(btc.get_latest_price('PLN'), 2) context = { 'form': form, 'value': value, 'a': a, 'b': b, 'amount': amount, 'price': price } return render(request, self.template_name, context) except: return redirect('/')
async def execute(self, args, msg): amount, origin, destination = args try: amount = Decimal(amount) except Exception as _: raise ValueError(f'Cannot parse decimal: {amount}') try: o_code, o_symbol = self.currency_code_and_symbol(origin) except TypeError: raise ValueError(f'Unknown currency: {origin}') try: d_code, d_symbol = self.currency_code_and_symbol(destination) except TypeError: raise ValueError(f'Unknown currency: {destination}') c = CurrencyRates() if o_code == 'BTC': b = BtcConverter() res = b.convert_btc_to_cur(amount, 'USD') if d_code != 'USD': res = c.convert('USD', d_code, res) elif d_code == 'BTC': b = BtcConverter() if o_code != 'USD': amount = c.convert(o_code, 'USD', amount) res = b.convert_to_btc(amount, o_code) else: res = c.convert(o_code, d_code, amount) res = self.format_number(res, 4, 2) await msg.channel.send(f'{amount: f} {o_code} = {res or 0} {d_code}')