def get_mono_bank_currency(): title = 'monobank' UAH = 980 USD = 840 EUR = 978 RUR = 643 code_lst = [USD, EUR, RUR] currency_data = [] response = requests.get('https://api.monobank.ua/bank/currency') if response.status_code == 200: data = response.json() for code in code_lst: course = [ d for d in data if d["currencyCodeB"] == UAH and d["currencyCodeA"] == code ] currency_data.append(course) currency_lst = [] i = 0 for currency in currency_data: currency_lst.append( Currency( ccy=Currency.convert_str_to_choice(currency_names[i]), buy_price=currency[0]['rateBuy'], sell_price=currency[0]['rateSell'], title=title, )) i += 1 Currency.objects.bulk_create(currency_lst) else: print(response.status_code)
def setUpClass(cls): cls.RUB = Currency(code='RUB', name='Rubles') cls.RUB.save() cls.USD = Currency(code='USD', name='US Dollars') cls.USD.save() cls.EUR = Currency(code='EUR', name='EURO') cls.EUR.save() cls.ticker_buy = \ Price(type=Price.BUY, price_rub=OrderBaseTestCase.PRICE_BUY_RUB, price_usd=OrderBaseTestCase.PRICE_BUY_USD, rate_eur=Decimal(OrderBaseTestCase.RATE_EUR)) cls.ticker_buy.save() cls.ticker_sell = \ Price(type=Price.SELL, price_rub=OrderBaseTestCase.PRICE_SELL_RUB, price_usd=OrderBaseTestCase.PRICE_SELL_USD, rate_eur=Decimal(OrderBaseTestCase.RATE_EUR)) cls.ticker_sell.save() super(OrderBaseTestCase, cls).setUpClass()
def get_kurs_currency(): title = 'kurs' headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } response = requests.get('https://kurs.com.ua/', headers=headers) if response.status_code == 200: tree = html.fromstring(response.text) currency_map = [{ 'ccy': 'USD', 'buy': '//*[@id="main_table"]/tbody/tr[1]/td[2]/div/text()', 'sale': '//*[@id="main_table"]/tbody/tr[1]/td[3]/div/text()', }, { 'ccy': 'EUR', 'buy': '//*[@id="main_table"]/tbody/tr[2]/td[2]/div/text()', 'sale': '//*[@id="main_table"]/tbody/tr[2]/td[3]/div/text()', }, { 'ccy': 'RUR', 'buy': '//*[@id="main_table"]/tbody/tr[3]/td[2]/div/text()', 'sale': '//*[@id="main_table"]/tbody/tr[3]/td[3]/div/text()', }] currency_lst = [] for row in currency_map: ccy = Currency.convert_str_to_choice(row['ccy']) if ccy: currency_lst.append( Currency( ccy=ccy, buy_price=tree.xpath(row['buy'])[0], sell_price=tree.xpath(row['sale'])[0], title=title, )) Currency.objects.bulk_create(currency_lst) else: print(response.status_code)
def get_industrial_bank_currency(): title = 'industrial_bank' headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } response = requests.get('https://industrialbank.ua/ua/', headers=headers) if response.status_code == 200: tree = html.fromstring(response.text) currency_map = [{ 'ccy': 'USD', 'buy': '//*[@id="exchange-rate"]/div[1]/ul/li[1]/span[2]', 'sale': '//*[@id="exchange-rate"]/div[2]/ul/li[1]/span[2]', }, { 'ccy': 'EUR', 'buy': '//*[@id="exchange-rate"]/div[1]/ul/li[2]/span[2]', 'sale': '//*[@id="exchange-rate"]/div[2]/ul/li[2]/span[2]', }, { 'ccy': 'RUR', 'buy': '//*[@id="exchange-rate"]/div[1]/ul/li[3]/span[2]', 'sale': '//*[@id="exchange-rate"]/div[2]/ul/li[3]/span[2]', }] currency_lst = [] for row in currency_map: ccy = Currency.convert_str_to_choice(row['ccy']) if ccy: currency_lst.append( Currency( ccy=ccy, buy_price=tree.xpath(row['buy'])[0].text, sell_price=tree.xpath(row['sale'])[0].text, title=title, )) Currency.objects.bulk_create(currency_lst) else: print(response.status_code)
def write_currency_list(currency_choice_name): found_currency_list.append( Currency(currency_name=currency_choice_name, currency_code=currency_dict['currencyCodeA'], currency_buy_rate=currency_dict['rateBuy'], currency_sell_rate=currency_dict['rateSell'], bank=bank))
def write_currency_list(currency_choice_name, currency_code): found_currency_list.append( Currency(currency_name=currency_choice_name, currency_code=currency_code, currency_buy_rate=currency_dict['bid'], currency_sell_rate=currency_dict['ask'], bank=bank))
def test_info_not_call_encrypt_decrypt(self, call_api, unlock, lock): api = ScryptRpcApiClient() curr = Currency(code='BTC', wallet='rpc5') api.get_info(curr) self.assertEqual(call_api.call_count, 1) self.assertEqual(unlock.call_count, 0) self.assertEqual(lock.call_count, 0)
def write_currency_list(name, currency_choice_name, currency_code): found_currency_list.append( Currency(currency_name=currency_choice_name, currency_code=currency_code, currency_buy_rate=(my_json_data[name])['buy'], currency_sell_rate=(my_json_data[name])['sale'], bank=bank))
def get_context_data(self, **kwargs): person = kwargs['object'] context = super(PersonDetailView, self).get_context_data(**kwargs) context['salary_form'] = SalaryForm(initial={'person': person}) context['payment_form'] = PaymentForm(initial={'currency': Currency.default(), 'amount_src': person.salary.amount}) context['person_form'] = PersonForm(instance=person) return context
def withdraw(request): """ Request Withdraw from wallet. """ try: user = request.user currency = request.data.get('currency') amount = float(request.data.get('amount')) ccAddress = request.data.get('address') freezedCurrency = Currency().getCurrency(currency) if not freezedCurrency: return Response({'success': False, 'error': 'currency.notvalid'}) cryptoAmount = amount / freezedCurrency.usd #create withdrawrequest withdrawRequest = WithdrawRequest() withdrawRequest.user = user withdrawRequest.requestedCurrency = currency withdrawRequest.requestedAmount = amount withdrawRequest.requestedCcAddress = ccAddress withdrawRequest.freezedUsd = freezedCurrency.usd withdrawRequest.freezedEur = freezedCurrency.eur withdrawRequest.save() #create notification protocol = 'http' if settings.FRONTEND_SSL: protocol = 'https' confirmationLink = "%s://%s:%s/withdrawConfirm/%s" % ( protocol, settings.FRONTEND_HOST, settings.FRONTEND_PORT, str(withdrawRequest.hash)) notification = Notification() notification.email = True notification.user = user notification.setEmailData( "Withdraw request comfirm", "notifications/email/withdraw_request_confirm_email.html", { 'user': user, 'confirmation_link': confirmationLink, 'currency': currency, 'amount': amount, 'cryptoAmount': cryptoAmount, 'freezedUsd': freezedCurrency.usd, 'freezedEur': freezedCurrency.eur }) withdrawRequest.notification = notification withdrawRequest.save() return Response({'success': True}) except Profile.DoesNotExist: return Response({'success': False, 'error': 'profile.notfound'}) except Wallet.DoesNotExist: return Response({'success': False, 'error': 'wallet.notfound'})
def lwfBundleToCryptoCurrency(request): user = request.user code = request.data.get('code') amount = float(request.data.get('amount')) try: Profile.objects.get(user=user) freezedCurrency = Currency().getCurrency(code) newAmount = (amount / freezedCurrency.usd) return Response({'success': True, 'value': "%0.8f" % (newAmount)}) except Profile.DoesNotExist: return Response({'success': False, 'error': 'auth.error'})
def EuroToDollars(request): user = request.user amount = float(request.data.get('amount')) try: Profile.objects.get(user=user) btcCurrency = Currency().getCurrency('BTC') return Response({ 'success': True, 'value': amount * (btcCurrency.usd / btcCurrency.eur) }) except Profile.DoesNotExist: return Response({'success': False, 'error': 'auth.error'})
def test_release_call_decrypt(self, get_pass, get_api, call_api, unlock, lock): get_pass.return_value = 'randomPass' get_api.return_value = mock.MagicMock() api = ScryptRpcApiClient() curr = Currency(code='BTC', wallet='rpc5') addr = Address() amount = 42 api.release_coins(curr, addr, amount) self.assertEqual(call_api.call_count, 1) self.assertEqual(lock.call_count, 1) get_api.assert_called_with('rpc5')
def get_kurstoday_rate(): response = requests.get('https://kurstoday.com.ua/') if response.status_code == 200: lxml_tree = html.fromstring(response.text) bank = 'Kurstoday' found_currency_list = [] rate_date = [ { 'currency': 1, 'code': 840, 'buy': '//*[@id="aval"]/div/div[2]/table/tbody/tr[1]/td[2]/span[1]', # noqa 'sell': '//*[@id="aval"]/div/div[2]/table/tbody/tr[1]/td[3]/span[1]' # noqa }, { 'currency': 2, 'code': 978, 'buy': '//*[@id="aval"]/div/div[2]/table/tbody/tr[2]/td[2]/span[1]', # noqa 'sell': '//*[@id="aval"]/div/div[2]/table/tbody/tr[2]/td[3]/span[1]' # noqa }, { 'currency': 3, 'code': 643, 'buy': '//*[@id="aval"]/div/div[2]/table/tbody/tr[3]/td[2]/span[1]', # noqa 'sell': '//*[@id="aval"]/div/div[2]/table/tbody/tr[3]/td[3]/span[1]' # noqa } ] for currency_dict in rate_date: found_currency_list.append( Currency(currency_name=currency_dict['currency'], currency_code=currency_dict['code'], currency_buy_rate=lxml_tree.xpath( currency_dict['buy'])[0].text, currency_sell_rate=lxml_tree.xpath( currency_dict['sell'])[0].text, bank=bank)) Currency.objects.bulk_create(found_currency_list) else: print(response.status_code) # noqa
def get_vkurse_currency(): title = 'vkurse' response = requests.get('http://vkurse.dp.ua/course.json') if response.status_code == 200: resp = response.json() dollar = resp['Dollar'] euro = resp['Euro'] rub = resp['Rub'] currency_data = [dollar, euro, rub] currency_lst = [] i = 0 for row in currency_data: currency_lst.append( Currency(ccy=Currency.convert_str_to_choice(currency_names[i]), buy_price=row['buy'], sell_price=row['sale'], title=title)) i += 1 Currency.objects.bulk_create(currency_lst) else: print(response.status_code)
def create_test_tables(self): """ Creates the current model on the testing database and inserts some well-known sample data. """ # Binds the app to the current context with self.app.app_context(): # Creates the current model on the testing database db.create_all() # Adds the test entries to the database with a unique bulk operation objects = [ Currency(iso_code='GBP', description='Pound sterling', symbol='£'), Product(name='Lavender heart', price=9.25, currency_iso='GBP'), Product(name='Personalised cufflinks', price=45., currency_iso='GBP'), Product(name='Kids T-shirt', price=19.95, currency_iso='GBP') ] db.session.bulk_save_objects(objects) db.session.commit()
def save_hg_data(): hg_data = get_hg_data() if hg_data: currency = Currency() currency.save_currency_from_hg_api(hg_data)
def update_currencies(): Currency.update_currencies()
def processCurrencies(request): r = { 'success': True, 'total_currencies': 0, 'created_currencies': 0, 'updated_currencies': 0 } cm = CurrencyManager() data = cm.getCurrencies() for c in data: try: localCurrency = Currency.objects.get(code=c['code']) r['updated_currencies'] += 1 except: localCurrency = Currency() r['created_currencies'] += 1 localCurrency.dateUpdated = django.utils.timezone.now() localCurrency.code = c['code'] localCurrency.usd = c['usd'] localCurrency.eur = c['eur'] localCurrency.save() #try: # lwfCurrency = Currency.objects.get( # code='LWF' # ) # r['updated_currencies'] += 1 #except: # lwfCurrency = Currency() # r['created_currencies'] += 1 #btcCurrency = Currency().getCurrency("BTC") #lwdUsd = (btcCurrency.usd * 0.000009148) #lwfEur = (btcCurrency.eur * 0.000009148) #lwfCurrency.dateUpdated = django.utils.timezone.now() #lwfCurrency.code = 'LWF' #lwfCurrency.usd = lwdUsd #lwfCurrency.eur = lwfEur #lwfCurrency.save() try: paypalBcCurrency = Currency.objects.get(code='PPBC') r['updated_currencies'] += 1 except: paypalBcCurrency = Currency() r['created_currencies'] += 1 paypalBcCurrency.dateUpdated = django.utils.timezone.now() paypalBcCurrency.code = 'PPBC' paypalBcCurrency.usd = 1 btcCurrency = Currency().getCurrency("BTC") paypalBcCurrency.eur = 1 * btcCurrency.eur / btcCurrency.usd paypalBcCurrency.save() r['total_currencies'] = len(Currency.objects.all()) return Response(r)
def processTransactions(request): # FREEZE CURRENCIES VALUES Cm = Currency() btcFreezedCurrency = Cm.getCurrency("BTC") lwfFreezedCurrency = Cm.getCurrency("LWF") #lwfProcess = processLwfTransactions(lwfFreezedCurrency) r = { 'success': False, "error": "", 'currency_freezedate': Cm.dateUpdated, 'BTC': { 'currency_usd': btcFreezedCurrency.usd, 'currency_eur': btcFreezedCurrency.eur, 'addresses_btc_processed': 0, 'addresses_btc_errors': [], 'transactions_btc_created': 0, 'transactions_btc_errors': [], }, 'LWF': { 'currency_usd': lwfFreezedCurrency.usd, 'currency_eur': lwfFreezedCurrency.eur, 'addresses_lwf_processed': 0, 'addresses_lwf_errors': [], 'transactions_lwf_created': 0, 'transactions_lwf_errors': [], } } # CHECK THAT ANOTHER PROCESS IS RUNNING previoustp = TransactionsProcess.objects.filter(dateEnd=None) if len(previoustp) == 0: logtp = TransactionsProcess() logtp.dateStart = django.utils.timezone.now() logtp.dateEnd = None logtp.save() try: btcProcess = processBtcTransactions(btcFreezedCurrency) r['BTC']['addresses_btc_processed'] = btcProcess[ 'processed_addresses'] r['BTC']['addresses_btc_errors'] = btcProcess['errors_addresses'] r['BTC']['transactions_btc_created'] = len( btcProcess['created_transactions']) r['BTC']['transactions_btc_errors'] = btcProcess[ 'errors_transactions'] lwfProcess = processLwfTransactions(lwfFreezedCurrency) r['LWF']['addresses_lwf_processed'] = lwfProcess[ 'processed_addresses'] r['LWF']['addresses_lwf_errors'] = lwfProcess['errors_addresses'] r['LWF']['transactions_lwf_created'] = len( lwfProcess['created_transactions']) r['LWF']['transactions_lwf_errors'] = lwfProcess[ 'errors_transactions'] r['success'] = True except Exception, ex: p_ex( request, ex, 2, 1, 'Error during transaction process: %s' % (traceback.format_exc())) r['error'] = "%s" % (traceback.format_exc()) logtp.dateEnd = django.utils.timezone.now() logtp.processData = str(r) logtp.save()
def depositPaypal(request): user = request.user paymentId = request.data.get('paymentId') payerId = request.data.get('payerId') # print(payerId) try: profile = Profile.objects.get(user=user) wallet = Wallet.objects.get(profile=profile) previousCredit = wallet.credit authUrl = settings.PAYPAL_GET_AUTH_TOKEN_ENDPOINT headers = { 'Accept': 'application/json', } authResponse = requests.post(authUrl, headers=headers, data={ 'grant_type': 'client_credentials' }, auth=HTTPBasicAuth( settings.PAYPAL_MERCHANT_ID, settings.PAYPAL_SECRET)).json() print(authResponse['access_token']) headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % authResponse['access_token'] } paymentUrl = settings.PAYPAL_PAYMENT_DETAILS_ENDPOINT % paymentId paymentResponse = requests.get(paymentUrl, headers=headers).json() # print(paymentResponse) if 'error' in paymentResponse.keys(): return Response({ 'success': False, 'error': paymentResponse['error_description'] }) if 'state' in paymentResponse.keys( ) and paymentResponse['state'] == 'approved': paypalTransaction = paymentResponse['transactions'][0] amount = float(paypalTransaction['amount']['total']) currency = paypalTransaction['amount']['currency'] transaction = TransactionPaypal() transaction.hash = paymentResponse['id'] transaction.date = paymentResponse['create_time'] transaction.type = 'deposit' transaction.currency = currency transaction.amount = amount transaction.wallet = wallet feePercentage = Configuration().getConfiguration( "paypal_deposit_percentage") freezedCurrency = Currency().getCurrency('PPBC') if currency == 'USD': pass elif currency == 'EUR': amount = (amount / freezedCurrency.eur) else: return Response({ 'success': False, 'error': 'currency.notavailable', 'message': 'deposit of %s in %s not available' % (amount, currency) }) transaction.paymentId = paymentId transaction.save() wallet.depositIn( freezedCurrency, transaction, amount, 'Paypal transaction found ID: %s with positive amount: %s (USD)' % (paymentId, amount), feePercentage, ) #all good # create transactions info for paypal transactionInfo = TransactionInfo() transactionInfo.transaction = transaction transactionInfo.description = 'Currency Rate Date: %s' % strftime( freezedCurrency.dateUpdated, '%Y-%m-%d %H:%M:%S') transactionInfo.save() transactionInfo = TransactionInfo() transactionInfo.transaction = transaction transactionInfo.description = 'BC -> USD' transactionInfo.cost = freezedCurrency.usd transactionInfo.save() transactionInfo = TransactionInfo() transactionInfo.transaction = transaction transactionInfo.description = 'BC -> EUR' transactionInfo.cost = freezedCurrency.eur transactionInfo.save() transactionInfo = TransactionInfo() transactionInfo.transaction = transaction transactionInfo.description = 'Previous Credit' transactionInfo.cost = previousCredit transactionInfo.save() transactionInfo = TransactionInfo() profile = Profile.objects.get(user=user) wallet = Wallet.objects.get(profile=profile) transactionInfo.transaction = transaction transactionInfo.description = 'Current Credit' transactionInfo.cost = wallet.credit transactionInfo.save() return Response({'success': True}) return Response({'success': False}) except Profile.DoesNotExist: return Response({'success': False, 'error': 'profile.notfound'}) except Wallet.DoesNotExist: return Response({'success': False, 'error': 'wallet.notfound'})
Confirm Withdraw request """ hash = request.data.get('hashKey') try: withdrawRequest = WithdrawRequest.objects.get(hash=hash, confirmed=False) except Exception, ex: return Response({ 'success': False, 'error': 'withdrawRequest.notfound' }) try: profile = Profile.objects.get(user=withdrawRequest.user) wallet = Wallet.objects.get(profile=profile) freezedCurrency = Currency().getCurrency( withdrawRequest.requestedCurrency) # NOW SET REAL USD/EUR VALUES WHEN WITHDRAW WAS REQUESTED!!! freezedCurrency.usd = withdrawRequest.freezedUsd freezedCurrency.eur = withdrawRequest.freezedEur if withdrawRequest.requestedAmount > wallet.credit: return Response({'success': False, 'error': 'credit.insufficient'}) # CREATE TRANSACTION withdrawTransaction = TransactionManager.createWithdrawTransaction( withdrawRequest.requestedAmount, wallet.id, freezedCurrency, withdrawRequest.requestedCcAddress) withdrawRequest.transaction = withdrawTransaction withdrawRequest.confirmed = True