async def Convert(ctx, *args): if len(args) != 4: await ctx.send('Invalid number of arguments') return fromCurrency = args[1].upper() toCurrency = args[3].upper() amount = args[0] if not amount.isnumeric(): await ctx.send('Amount must be numeric') return amount = float(amount) currency = Currency.Utility() if not currency.exist(fromCurrency.upper()) or not currency.exist( toCurrency.upper()): await ctx.send('One or more currency is not supported') return market = LiveMarket.API() rates = market.request(fromCurrency) if toCurrency in rates: rate = float(rates[toCurrency]) await ctx.send('%.2f %s to %s = %.2f' % (amount, fromCurrency, toCurrency, rate * amount))
def test_year(year, m1, m2): candles = Currency.CAD_Ten_Min_Candle_Container() types = Hunter.Type_Container(candles) pens = Hunter.Pen_Container(types) hubs = Hunter.Ten_Min_Hub_Container(pens) # 初始化Tran_Container对象 trans = Hunter.Tran_Container() #s1 = S1.S1(candles.container,types.container,pens.container,hubs.container) #s_b = S1_B.S(candles.container,types.container,pens.container,hubs.container) s2 = S1.S2() m = Event.Monitor(s2) # 逐月调用 for i in range(m1, m2 + 1): candles.loadDB(year, i, 0, 0, types, pens, hubs, m) """
def menu_handler(update: Update, context: CallbackContext) -> None: query = update.callback_query query.answer() if query.data == 'phone': query.edit_message_text('👈 شماره همراه خود را وارد کنید:') return FIFTH if query.data == 'increase' or query.data == 'decrease': context.user_data['wallet_action'] = query.data reply_markup = InlineKeyboardMarkup(keyboards["wallet_action"][0]) query.edit_message_text(keyboards["wallet_action"][1], reply_markup=reply_markup) return SIXTH reply_markup = InlineKeyboardMarkup(keyboards[query.data][0]) if query.data == 'market': query.edit_message_text('در حال ارزیابی قیمت ها ... ', reply_markup=reply_markup) c = Currency.Currency() c.get_prices() query.edit_message_text(c.post_reporter(), reply_markup=reply_markup) elif query.data == 'cash' or query.data == 'crypto': context.user_data['d_type'] = query.data query.edit_message_text(keyboards[query.data][1], reply_markup=reply_markup) return SECOND elif query.data == 'rules': query.edit_message_text(keyboards[query.data][1], reply_markup=reply_markup) else: query.edit_message_text(keyboards[query.data][1], reply_markup=reply_markup) return FIRST
async def Convert(self, ctx, *args): if len(args) not in range(3, 5): await ctx.send("[amount] [from_currency] [to_currency]") return fromCurrency = args[1].upper() toCurrency = args[-1].upper() amount = args[0] if not amount.isnumeric(): await ctx.send("""use numbers, that'd help""") return amount = float(amount) currency = Currency.Utility() if not currency.exist(fromCurrency.upper()) or not currency.exist( toCurrency.upper()): await ctx.send("lol") return market = LiveMarket.API() rates = market.request(fromCurrency) if toCurrency in rates: rate = float(rates[toCurrency]) await ctx.send("%.2f %s to %s = %.2f" % (amount, fromCurrency, toCurrency, rate * amount))
class Currencies: """ Stores in use currencies and provides access to the individual objects. """ _CAD = Currency.CAD() _USD = Currency.USD() _EUR = Currency.EUR() __instance = None @staticmethod def get_instance(): """ Returns the instance of Currencies. :return: Instance of Currencies.. """ if Currencies.__instance is None: Currencies() return Currencies.__instance def __init__(self): """ Singleton pattern for the Currencies class. """ if Currencies.__instance is None: Currencies.__instance = self def get_currency(self, option: str) -> Currency: """ Maps the option string to the desired currency and returns it. :param option: String that maps to a respective currency. :return: Currency object. """ valid = False while not valid: if option == "1": return self._CAD if option == "2": return self._USD if option == "3": return self._EUR else: option = input( "Invalid currency selection! Please try again.\n" "Please select the currency you would like to perform " "the transaction in:\n(1) CAD\n(2) USD\n(3) EUR\n")
def main(): display_message() while True: try: account = float(input('Enter your amount: ')) invoke_class_account = Currency(account) invoke_class_account = Currency(account) user_input = user_amount() invoke_class_user_input = Currency(user_input[0], user_input[1]) total = sub_currencies(invoke_class_account, invoke_class_user_input) print(total) except: print(' Enter values correctly') continue
def test_currency_validation(): currency, _ = Currency.objects.get_or_create(code="USD") currency.full_clean() assert "USD" in str(currency) # currency code does not exist with pytest.raises(ValidationError) as exc: Currency(code="ISD").full_clean() assert "Enter a valid ISO-4217 currency code" in exc.value.messages
def __init__(self, candles): Bucket.__init__(self, candles) if isinstance(candles, Currency.AUD_Ten_Min_Candle_Container): self.candle_container = Currency.AUD_One_Min_Candle_Container() elif isinstance(candles, Currency.CAD_Ten_Min_Candle_Container): self.candle_container = Currency.CAD_One_Min_Candle_Container() elif isinstance(candles, Currency.CHF_Ten_Min_Candle_Container): self.candle_container = Currency.CHF_One_Min_Candle_Container() elif isinstance(candles, Currency.GBP_Ten_Min_Candle_Container): self.candle_container = Currency.GBP_One_Min_Candle_Container() elif isinstance(candles, Currency.EUR_Ten_Min_Candle_Container): self.candle_container = Currency.EUR_One_Min_Candle_Container() elif isinstance(candles, Currency.JPY_Ten_Min_Candle_Container): self.candle_container = Currency.JPY_One_Min_Candle_Container() self.init() self.hubs = Hunter.One_Min_Hub_Container(self.pens, self)
def __init__(self, candles): Bucket.__init__(self, candles) if isinstance(candles, Currency.AUD_Five_Min_Candle_Container): self.candle_container = Currency.AUD_One_Min_Candle_Container() elif isinstance(candles, Currency.CAD_Five_Min_Candle_Container): self.candle_container = Currency.CAD_One_Min_Candle_Container() elif isinstance(candles, Currency.CHF_Five_Min_Candle_Container): self.candle_container = Currency.CHF_One_Min_Candle_Container() elif isinstance(candles, Currency.GBP_Five_Min_Candle_Container): self.candle_container = Currency.GBP_One_Min_Candle_Container() elif isinstance(candles, Currency.EUR_Five_Min_Candle_Container): self.candle_container = Currency.EUR_One_Min_Candle_Container() else: self.candle_container = Currency.JPY_One_Min_Candle_Container() self.init() # 中枢容器的实现具有差异化,所以没有放入init() self.hubs = Hunter.One_Min_Hub_Container(self.pens, self)
def __init__(self): config = configparser.ConfigParser() config.read('currencies.properties') self.__currencies = list() for i in range(8): name = config['Currencies']['currency' + str(i + 1) + '.name'] exchange_rate = config['Currencies']['currency' + str(i + 1) + '.exchange_rate'] divider = config['Currencies']['currency' + str(i + 1) + '.divider'] self.__currencies.append(Currency(name, exchange_rate, divider))
def loadData(self, csvFile): # We will open our currency atlas to add currency info to our airport objects CurrencyAtlas = Currency.CurrencyAtlas() dictionary = {} with open(csvFile, 'r') as f: reader = csv.reader(f, delimiter=',') for line in reader: dictionary[line[4]] = Airport(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9], line[10], line[11], CurrencyAtlas) self.airportDict = dictionary
def test_cost_shortest_path(self): """ Test to check for value returned for simple shortest path cost """ itinerary = Itinerary('testFiles/test_path_cost_simple.csv') atlas = AirportAtlas('input/airport.csv') aircraft_table = AircraftTable('input/aircraft.csv') currency = Currency('input/countrycurrency.csv', 'input/currencyrates.csv') graph = GraphRouteConstructor(itinerary.get_itinerary()[0], atlas, currency) cost = graph.shortest_path(aircraft_table.getAircraft('747'), atlas)[1] #SNN to DUB, DUB to OSL, OSL to SNN #194+1291+0.1155*1476=1655.48 self.assertTrue(cost == 1655.48)
def test_shortest_path_infeasible(self): """ Test that shortest path returns infeasible result for known infeasible journey 747 can not fly directly from Ireland to Australia so route in test_path.csv is infeasible """ itinerary = Itinerary('testFiles/test_path_infeasible_747.csv') atlas = AirportAtlas('input/airport.csv') aircraft_table = AircraftTable('input/aircraft.csv') currency = Currency('input/countrycurrency.csv', 'input/currencyrates.csv') graph = GraphRouteConstructor(itinerary.get_itinerary()[0], atlas, currency) self.assertTrue( graph.shortest_path(aircraft_table.getAircraft('747'), atlas) == "This journey is infeasible for your aircraft")
def test_shortest_path_feasible(self): """ Test that shortest path returns infeasible result for known feasible journey 747 has range of 9,800 so route within Ireland like in test_path_feasible_747.csv is feasible """ itinerary = Itinerary('testFiles/test_path_feasible_747.csv') atlas = AirportAtlas('input/airport.csv') aircraft_table = AircraftTable('input/aircraft.csv') currency = Currency('input/countrycurrency.csv', 'input/currencyrates.csv') graph = GraphRouteConstructor(itinerary.get_itinerary()[0], atlas, currency) self.assertTrue( graph.shortest_path(aircraft_table.getAircraft('747'), atlas) != "This journey is infeasible for your aircraft")
async def Rates(ctx): market = LiveMarket.API() rates = market.request('USD') parsedRates = str() currency = Currency.Utility() parsedRates += '%s %s is the base currency\n' % ( currency.getFlagEmoji('USD'), currency.getFullName('USD')) for key in rates: flag = currency.getFlagEmoji(key) fullname = currency.getFullName(key) parsedRates += '%s %s[%s] - %.4f \n' % (flag, fullname, key, rates[key]) await ctx.send(parsedRates)
def get_currency(self, base_message: str) -> str: """ prompts the user to input a valid currency and it's conversion to USD Args: base_message : message to prompt the user Returns: 3 letter code corresponding to the transaction's currency conversion : conversion to USD such that the amount in USD = (amount in currency_code)*conversion """ message = base_message while True: usr_code = self.input(message).upper() if usr_code in Currency.currency_codes(): return usr_code else: message = f"{usr_code} is not a valid currency code\n{base_message}"
def __init__(self, name, currency_name, coin_name): self.name = name if name == "Kucoin": api = API.KucoinAPI() elif name == "Gate": api = API.GateAPI() elif name == "Bithumb": api = API.BithumbAPI() elif name == "Coinnest": api = API.CoinnestAPI() elif name == "Poloniex": api = API.PoloniexAPI() elif name == "Gopax": api = API.GopaxAPI() elif name == "Binance": api = API.BinanceAPI() self.API = api self.tradeFee = GlobalVariable.marketTradeFee[self.name] self.currencyList = [ Currency(currency_name, self.name, [coin_name], self.API) ]
def set_currency_list(self): try: tickers = self.API.GetTickers() except: tickers = {} result = [] # # USDT만 해보기, 너무 오래걸림, 이따 수정필요 # try: # result.append(Currency("USDT",self.name, tickers["USDT"], self.API)) # except : # print(" Market(" + str(sys._getframe().f_lineno) + ") : (" + self.name + ") : currency : " + "USDT", "Error") for i in list(tickers.keys()): try: result.append(Currency(i, self.name, tickers[i], self.API)) except: print( " Market(" + str(sys._getframe().f_lineno) + ") : (" + self.name + ") : currency : " + i, "Error") return result
def test_month_10(market, year, month, count=0, skips=0): candles = Currency.CAD_Ten_Min_Candle_Container() types = Hunter.Type_Container(candles) pens = Hunter.Pen_Container(types) hubs = Hunter.Ten_Min_Hub_Container(pens) # 初始化Tran_Container对象 trans = Hunter.Tran_Container() #s1 = S1.S1(candles.container,types.container,pens.container,hubs.container) s2 = S1.S2() m = Event.Monitor(s2) candles.loadDB(year, month, count, skips, types, pens, hubs, m) #S1.S1._trans.clear() #S1.S2._trans.clear() ax_1 = plt.subplot(1, 1, 1) drawer = Drawer.Ten_Min_Drawer(candles.container) drawer.draw_stocks(candles.container, types.container, ax_1, trans) drawer.draw_pens(pens.container, ax_1) drawer.draw_hub(hubs.container, hubs, ax_1) #for _, hub in enumerate(hubs.container): # print(hub.pens()) plt.show() """
def amount(update: Update, context: CallbackContext) -> None: query = update.callback_query query.answer() context.user_data['T_type'] = query.data c = Currency.Currency() if context.user_data['d_type'] == 'crypto': if query.data == 'buy': query.edit_message_text(text="در حال محاسبه قیمت") c.get_prices() c.minimum_calc() query.edit_message_text( text=c.minimum_reporter(context.user_data['currency'], True)) context.user_data['unit'] = c.min_prices[ context.user_data['currency']] else: query.edit_message_text(text="در حال محاسبه قیمت") c.get_prices() c.minimum_calc() query.edit_message_text( text=c.minimum_reporter(context.user_data['currency'], False)) context.user_data['unit'] = c.min_prices[ context.user_data['currency']] return THIRD
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) # DBMS database = DBMS() all_users = database.get_users() users_dict = {} for each in all_users: users_dict[each[0]] = list(each) all_users = users_dict print(all_users) prices = Currency.Currency() def start(update: Update, context: CallbackContext) -> None: person = update.message.from_user print( f' New Thread with {person.username} at : {get_duration(update.message.date)} ago' ) context.user_data['username'] = person.username context.bot.send_message(update.message.chat_id, wellcome_text) reply_markup = InlineKeyboardMarkup(main_keyboard) update.message.reply_text(main_text, reply_markup=reply_markup) return FIRST
lat1=airport1.getLat() lng1=airport1.getLong() lat2=airport2.getLat() lng2=airport2.getLong() return AirportAtlas.greatcircledistance(lat1,lng1,lat2,lng2) def getCostOfJourney(self,Airport1,Airport2,currency): """ Calculates cost of journey from one airport to another """ distance = self.getDistanceBetweenAirports(Airport1, Airport2) airport1 = self.Atlas.get(Airport1) rate = currency.getRate(airport1.getCountry()) cost = rate*distance return cost def getAirports(self): """ Return list containing codes of all airports stored in atlas object """ return self.Atlas.keys() if __name__=="__main__": from Currency import * curr = Currency('input/countrycurrency.csv','input/currencyrates.csv') atlas=AirportAtlas('input/airport.csv') print(atlas.getCostOfJourney('LHR', 'DUB',curr))
"Snark Fee Transfers", "Coinbase Fee Transfers" ], tablefmt="pretty")) f.write("\n") print( f"We have received grand total of " f"{Currency.Currency(all_blocks_total_rewards,format=Currency.CurrencyFormat.NANO).decimal_format()} " f"mina in this window. ") f.write( f"\nWe have received grand total of " f"{Currency.Currency(all_blocks_total_rewards,format=Currency.CurrencyFormat.NANO).decimal_format()} " f"mina in this window. \n") print(f"Our fee at {fee*100}% is " + Currency.Currency(all_blocks_total_fees, format=Currency.CurrencyFormat.NANO).decimal_format() + " mina, and the total payout amount is " + Currency.Currency(all_blocks_total_rewards - all_blocks_total_fees, format=Currency.CurrencyFormat.NANO).decimal_format()) apy = round((all_blocks_total_rewards / 1e9 / total_unlocked_staking_balance) * 365 * 24 * 60 * 100 / (7140 * 3), 2) print(f"\nThe estimated APY before fees is {apy}%. \n") f.write( f"Our fee at {fee*100}% is " + Currency.Currency(all_blocks_total_fees, format=Currency.CurrencyFormat.NANO).decimal_format() + " mina, and the total payout amount is " + Currency.Currency(all_blocks_total_rewards - all_blocks_total_fees, format=Currency.CurrencyFormat.NANO).decimal_format()) f.write(f"\nThe estimated APY before fees is {apy}%. \n")
def test_converter_different(): assert currency_converter.convert(Currency(1, 'USD'), 'EUR') == Currency(0.5, "EUR")
import sys sys.path.append('C:\\Users\\victo\\Desktop\\Victor\\Programação\\Linguagem Python\\Programas Victor - Curso em Video\\Desafio_111\\Package') import Currency n = float(input('Please, type a value (R$): ')) Currency.Resume(n)
'info': ['ai03', 'goat', 'kalendar'], 'films': ['apex', 'ash', 'kebo', 'tx'], 'firmware': ['qmkgui', 'via'], 'services': ['ash'], 'artisans': ['alpha', 'jelly', 'kpr', 'kyle', 'mk', 'scraft', 'space', 'summit'], 'ergo': ['aura', 'mkultra', 'wooting'], 'springs': ['prime', 'tx'], 'deskmats': ['aura', 'cannon', 'deskhero', 'kono', 'kpr', 'nk', 'prime', 'tkc', 'tx'], 'groupbuy': [ 'candy', 'cannon', 'dclack', 'deskhero', 'dixie', 'kono', 'krelbit', 'nk', 'origin', 'tkc', 'tx', 'wei' ], 'cad': ['apex', 'ash', 'aura', 'deskhero', 'kofi', 'zeal'] } # load pickles tagDict = load_dict(Constants.TAG_DICT_PATH) siteDict = load_dict(Constants.SITE_DICT_PATH) typeDict = load_dict(Constants.TYPE_DICT_PATH) bDict = load_dict(Constants.B_DICT_PATH) aDict = load_dict(Constants.A_DICT_PATH) shareDict = load_dict(Constants.SHARE_DICT_PATH) # startup bot.add_cog(Timezone(bot)) bot.add_cog(Music(bot)) bot.add_cog(Currency(bot)) bot.run(Constants.DISCORD_SECRET)
def handleRule(rule): ic = ItemCrawler() db_avg_cost = DB.get_avg_price(rule.link) Log("{} for less then {} Chaos".format(rule.name, (PRICE_MULTIPLICATOR*db_avg_cost)),"CURRENT SCAN", "blue", 0) hits = ic.hits(rule.link) if not rule.enabled: return isFirst = True hitCnt = 0 hitSum = 0 for hit in hits: cost = Crawler.getCostFromEntry(hit) ign = Crawler.getIGNFromEntry(hit) (corrupted, item_name) = Crawler.getItemNameFromEntry(hit) item_print = item_name if not item_name: item_name = "<NOT FOUND>" else: if corrupted: item_print = Fore.RED + "Corrupted" + Fore.RESET + " " + item_name chaos_cost = Currency.getChaosValue(cost) # Solange noch kein Item gefunden wurde ist db_avg_cost = 0 und db_avg_cost * PRICE_IGNORE_MIN ebenfalls. # Das gleiche gilt für PRICE_IGNORE_MAX if not db_avg_cost: db_avg_cost = chaos_cost if chaos_cost < db_avg_cost * PRICE_IGNORE_MIN or chaos_cost > db_avg_cost * PRICE_IGNORE_MAX: Log("Someone is selling {} ({}) for {} chaos!!".format(item_print, rule.link, chaos_cost), "TROLL ALERT", "red", 0) continue if(hitCnt < MAX_HITS_FOR_AVG): hitSum += chaos_cost hitCnt += 1 # if chaos_cost <= rule.price and isFirst: if chaos_cost <= (PRICE_MULTIPLICATOR*db_avg_cost): Log("Schnappaaah : ", "INFO", "yellow", 0) Log(rule.name, "RULE", None, 1) Log(item_print, "ITEM", None, 1) Log(rule.link, "LINK", None, 1) Log(cost, "COST", None, 1) Log(chaos_cost, "CHAOS COST", None, 1) Log("@{} Hi, I would like to buy your {} listed for {} in {}\n".format(ign, item_name, cost, LEAGUE), "WHISPER", None, 1) if rule.alert: os.system("start C:\\Users\\Ramon\\workspace\\git\\rockwurst\\testsound.mp3") isFirst = False if len(hits) > 0: hitAvg = hitSum / hitCnt Log("took the first {} items with an avarage of {} chaos".format(hitCnt, hitAvg), "SCAN RESULT", "white", 0) DB.insert_scan(rule.link, hitAvg)
else: print("Please Input correct Option!") # --------------Static operations require no furthur user input # Get the average price of bitcoin # Get the average bid price # get the average ask price # display bitcoin price graph # display ask/bid graph # --------------Based on analysis # should I buy or sell (trend analysis) # convert currency (Input home currency, away currency and amount) => (output value in away currency) # Major operation (Input currency, amount [=> internally convert to USD]) => (display "You can buy x bitcoin at # this amount or can sell y # bitcoin with this") if __name__ == '__main__': global conn global th eng = create_engine("sqlite:///mydb.db") print("Filling up database. Please wait! this process might take 3-5 min.") conn = eng.connect() Currency.init() BitCoinPrice.init() bitstamp.init() th1 = Thread(target=BitFinex.init) th1.daemon = True th1.start() StartUserOperations()
import Currency ca = Currency.CurrencyAtlas() IE = ca.getCurrency('United Kingdom') print(IE.currencyCode) print(IE.currencyName) print(IE.currencyRate) print(IE.currencyRate + 1)
def test_converter_same(): assert currency_converter.convert(Currency(1, 'USD'), 'USD') == Currency(1, 'USD')
############################################################################### # Mohammd-AlKharaan-Assignment02 # # CPS 202 Assignment #02 # Mohammd AlKharaan # # Larger Programq from Currency import * a = Currency(1000, 'SAR') b = a.convert_to('USD') b1 = a.convert_to('EUR') b2 = a.convert_to('JPY') b3 = a.convert_to('AUD') b4 = a.convert_to('CAD') b5 = a.convert_to('CNY') b6 = a.convert_to('GBP') c = Currency(10000, 'CAD') d = c.convert_to('USD') e = a + 5.544 f = c + 154 e1 = a - 5.544 f1 = c - 154 e2 = 5.544 - c f2 = 154 - a f3 = a + c f4 = c + a print('a is', a) print('c is', c)
Log("@{} Hi, I would like to buy your {} listed for {} in {}\n".format(ign, item_name, cost, LEAGUE), "WHISPER", None, 1) if rule.alert: os.system("start C:\\Users\\Ramon\\workspace\\git\\rockwurst\\testsound.mp3") isFirst = False if len(hits) > 0: hitAvg = hitSum / hitCnt Log("took the first {} items with an avarage of {} chaos".format(hitCnt, hitAvg), "SCAN RESULT", "white", 0) DB.insert_scan(rule.link, hitAvg) def start(): date_str = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S am %d.%m.%Y') Log("Scan start", "INFO", "yellow", 0) rp = RuleParser() rules = rp.rules for rule in rules: handleRule(rule) Log("Scan finished --- I'll be back ! \n\n", "INFO", "yellow", 0) if __name__ == "__main__": Currency.updateCurrencys() Currency.printCurrencys() while True: start() time.sleep(180)