def root(): price_in_btc = to_btc('USD', PRICE_IN_USD) run_db("""INSERT OR IGNORE INTO invoices (invoice_id, price_in_usd, price_in_btc, product_url) VALUES(?,?,?,?)""", [INVOICE_ID, PRICE_IN_USD, price_in_btc, PRODUCT_URL]) return render_template('invoice.html', blockchain_root=app.config['BLOCKCHAIN_ROOT'], invoice_id=INVOICE_ID, price_in_btc=price_in_btc)
def root(): price_in_btc = to_btc('USD', PRICE_IN_USD) run_db( """INSERT OR IGNORE INTO invoices (invoice_id, price_in_usd, price_in_btc, product_url) VALUES(?,?,?,?)""", [INVOICE_ID, PRICE_IN_USD, price_in_btc, PRODUCT_URL]) return render_template('invoice.html', blockchain_root=app.config['BLOCKCHAIN_ROOT'], invoice_id=INVOICE_ID, price_in_btc=price_in_btc)
def jpy(): title = 'JPY Simple Converter' name = request.form['name'] btc_amo = exchangerates.to_btc('JPY', name) home = redirect(url_for('index')) excsym = ticker['JPY'].symbol excrat = ticker['JPY'].p15min priceList = [] for item in ccyprice(): priceList.append(item) usdmktprice = stats.market_price_usd return render_template('index.html', usdmktprice=usdmktprice, excrat=excrat, excsym=excsym, home=home, name=name, btc_amo=btc_amo, ccyprice=priceList, ccylists=ccylists(), title=title)
def main(): currency_symbols = er.get_ticker() for c in currency_symbols: print(c) for c in currency_symbols: print(c, ":", currency_symbols[c].p15min) for c in currency_symbols: print("1 BTC:", 1 / currency_symbols[c].p15min) cad_base_btc = er.to_btc("CAD", 5000) print("5000 CAD costs", cad_base_btc, "BTCs")
def btc_context(context, total): """ Receive context and order total. Return BTC address and BTC total """ btc_total = to_btc('USD', total) request = context["request"] addr, inv_id = create_handler(request, total, btc_total) btc_context = { 'btc_total': btc_total, 'address': addr, 'invoice_id': inv_id } return btc_context
def perform_create(self, serializer): expected_price_btc = to_btc('USD', serializer.validated_data['package'].price) channel_count = getChannelMemberCount( serializer.validated_data['entity_ident']) callbackURL = URL_HOME invoice = models.Invoice.objects.create( expected_price=expected_price_btc) callbackParams = {'secret': SECRET_KEY, 'invoiceID': invoice.pk} callbackURL += '?' + urllib.parse.urlencode(callbackParams) recv = receive(XPUB, callbackURL, API_KEY) serializer.save(address=recv.address, invoice=invoice, member_count=channel_count, target_member_count=channel_count + serializer.validated_data['package'].number, action=serializer.validated_data['package'].action)
def bitcoin_callback(request, invoice, secret): bw = BitcoinKeyInvoiceDict.objects.get(id=int(invoice)) invoice = bw.invoice if invoice.status == 'PAID': return HttpResponse("*ok*", status=200) conf = request.GET['confirmations'] tx = request.GET['transaction_hash'] precomp_secret = gen_secret(bw.id) if precomp_secret == secret: if int(conf) > 3: value = float(request.GET['value']) / 100000000 currency_conv = to_btc('USD', 2000.00) invoice.amount = Decimal(value * 2000 / currency_conv) invoice.status = 'PAID' shop = invoice.shop shop.balance += Decimal(invoice.amount) shop.save() invoice.save() a = BitcoinHistory.objects.get(invoice=invoice) a.status = 'PAID' a.txhash = tx a.time_updated = timezone.now() a.active = False a.save() mailer("urpsm/notifications/email_notifications.html", "URPSM: Notification", ctx={ 'notification': 'Bitcoin payment received, invoice #' + str(invoice.id) + '. TX Hash:' + tx }, recipient=shop.shop_email, fromemail="*****@*****.**") mailer("urpsm/notifications/email_notifications.html", "URPSM: Payment received", ctx={ 'notification': 'Bitcoin payment received, invoice #' + str(invoice.id) + '. Please verify. TX Hash:' + tx }, recipient="*****@*****.**", fromemail="*****@*****.**") return HttpResponse("*ok*", status=200) return HttpResponse("Try Again", status=500) return HttpResponse("Invalid response", status=500)
def get(self, request, *args, **kwargs): address = request.GET.get('address') secret = request.GET.get('secret') confirmations = int(request.GET.get('confirmations')) tx_hash = request.GET.get('transaction_hash') value_satoshi = float(request.GET.get('value')) invoice = get_object_or_404(models.Invoice, pk=request.GET.get('invoiceID')) task = invoice.task value = value_satoshi / 100000000 packageValue = to_btc('USD', task.package.price) print(packageValue, value, task.package.price) if address != task.address: return Response('Incorrect Receiving Address', status=400) if secret != SECRET_KEY: return Response('invalid secret', status=400) if confirmations >= CONFIRMATION_PASSED: payment = models.Payment.objects.create(task=task, amount=value) totalAcceptedPayment = sum( [payment.amount for payment in task.payments.all()]) if totalAcceptedPayment >= invoice.expected_price: if task.running_tasks.count() == 0: models.RunningTask.objects.create(task=task) task.status = models.STAT_RUN task.save() return Response('*ok*') else: return Response('Waiting for confirmations') # should never reach here! return Response('something went wrong', status=500)
# import blockchain library #essa lib, permite consultar informações sobre o bitcoin from blockchain import exchangerates from blockchain import statistics from blockchain import blockexplorer # retorna o valor do bitcoin em cada moeda ticker = exchangerates.get_ticker() #mostra o valor do bitcoin a cerca de 15 min for k in ticker: print(k, ticker[k].p15min) # Converte o valor de uma moeda para o respectivo valor em bitcoin btc = exchangerates.to_btc('EUR', 100) print(f"\n100 euros in Bitcoin: {btc}") #utilizando a lib statistics stats = statistics.get() # total de bitcoin minerados print("Bitcoin mined: %s\n" % stats.btc_mined) # valor do bitcoin em USD print(f"Bitcoin market price USD: {stats.market_price_usd}\n") #utilizando a lib blockexplorer # retorna um bloco em particular block = blockexplorer.get_block( '0000000000000000002e90b284607359f3415647626447643b9b880ee00e41fa') #pode-se obter informações desse bloco em particular
def convert_to_btc(amount): return exchangerates.to_btc('RUB', amount)
def convert_price_to_crypto(self, currency, price): return exchangerates.to_btc(currency, price)
# Copyright Chainhaus # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Rates # # Docs: https://github.com/blockchain/api-v1-client-python/blob/master/docs/exchangerates.md from blockchain import exchangerates as er symbols = er.get_ticker() for k in symbols: print(str(k), symbols[k].p15min) # How much BTC can USD buy? for d in range(0, 100000, 10000): print("$", d, " = ", er.to_btc('USD', d), " BTC")
def get_price(self, currency, amount): btc_amount = exchangerates.to_btc(currency, amount) return btc_amount
from blockchain import exchangerates ticker = exchangerates.get_ticker() print("Bitcoin Prices") for x in ticker: print(x, ticker[x].p15min) btc = exchangerates.to_btc('USD', 100) print("\n100 dollars in Bitcoin: %s" % btc)
def to_btcf(): # The 'tobtc' method converts x value in the provided currency to BTC. Returns a float btc_amount = exchangerates.to_btc('USD', 4342.11) return btc_amount
from blockchain import exchangerates ticker = exchangerates.get_ticker() print("Bitcoin Prices : ") for i in ticker: print(i, ticker[i].p15min) btc = exchangerates.to_btc('SGD', 100000) print("\n100000 SGD in Bitcoin : %s" %(btc))
from blockchain import exchangerates ticker = exchangerates.get_ticker( ) #get_ticker method will return exchange rate in dict form print("bitcoin prices in differnt currencies :") for k in ticker: print(k, ticker[k].p15min) #value from past 15 mins btc = exchangerates.to_btc('INR', 1000) #exchange the currency value in bitcoin print("\n1000 indian rupee in bitcoin : {}".format(btc))