Bitcoin Forum

Bitcoin => Development & Technical Discussion => Topic started by: mrflibblehat on October 12, 2014, 04:12:43 PM



Title: GetBalance Python Script with Fiat Support
Post by: mrflibblehat on October 12, 2014, 04:12:43 PM
Hi,

I am writing a small program for Bitcoin as I am learning Python3 and I needed a function to return multiple Bitcoin addresses Balance and Fiat Balance, I thought it may come in useful to someone or at the very least I would get feedback about how I could improve the code to make it less lines / better error checking for some of you more experience Python Devs out there. You will need to install Python Modules urllib3 and certifi

Anyway Here it is.

Quote
Supported Currencies ARS, AUD, BRL, CAD, CHF, CZK, DKK, EUR, GBP, HKD, ILS, INR, MXN, NOK, NZD, PLN, RUB, SEK, SGD, THB, USD, ZAR
 
Usage:
python GetBalance.py <Currency> <BitcoinAddress> ...

Code:
#!/usr/bin/python3
#
# Bitcoin GetBalance
#
# Supported Currencies ARS, AUD, BRL, CAD, CHF, CZK, DKK, EUR, GBP, HKD, ILS, INR, MXN, NOK, NZD, PLN, RUB, SEK, SGD, THB, USD, ZAR
#
# Usage:
# python GetBalance.py <Currency> <BitcoinAddress> ...
#

import argparse, urllib3, json, certifi

parser = argparse.ArgumentParser(description='Get Balance of Bitcoin Addresses.')
parser.add_argument('Currency', nargs=1, help='Currency')
parser.add_argument('BitcoinAddresses', metavar='BitcoinAddress', nargs='+',
                   help='a Bitcoin Address')

args = parser.parse_args()

def GetBalance():
for BitcoinAddr in args.BitcoinAddresses:
blockchain = urllib3.PoolManager()
req = blockchain.request('GET', 'http://blockchain.info/q/addressbalance/' + BitcoinAddr)
SatoshiConvert = int(req.data) / 100000000
if FiatValue() == 'Error: No Such Currency':
print('no such currency {}'.format(args.Currency[0]))
break
else:
FiatConvert = FiatValue() * SatoshiConvert
print('{} - {} ({:,} {})'.format(BitcoinAddr, SatoshiConvert, round(FiatConvert, 2), args.Currency[0]))

def FiatValue():
fiatvalues = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED',
     ca_certs=certifi.where(),
)
req = fiatvalues.request('GET', 'https://localbitcoins.com/bitcoinaverage/ticker-all-currencies')
jsondata = json.loads(req.data.decode('utf-8'))
try:
return float(jsondata[args.Currency[0]]['rates']['last'])
except:
return 'Error: No Such Currency'

GetBalance()

Output for 3 Random Addresses
Quote
C:\Users\mrflibblehat\Desktop\Python>python GetBalance.py USD 3MkwFfGNQDve7vz1z6gUDVxk
uQpcSV3Mz8 15qwThKcv55zeJLxd8AXmK3TCgHbW8SXrQ 1QACD9ZHnBSJVWsyE6wrfBm7GvU7QCc5KQ

3MkwFfGNQDve7vz1z6gUDVxkuQpcSV3Mz8 - 4299.52149361 (1,747,841.48 USD)
15qwThKcv55zeJLxd8AXmK3TCgHbW8SXrQ - 83.55649333 (33,967.39 USD)
1QACD9ZHnBSJVWsyE6wrfBm7GvU7QCc5KQ - 1.21749614 (494.94 USD)


Title: Re: GetBalance Python Script with Fiat Support
Post by: seoincorporation on October 12, 2014, 04:25:14 PM
Its a nice code.

To get balance from a shell or a script i like to use curl:

Code:
[windows@localhost ~]$ curl http://blockchain.info/q/addressbalance/1BtcBoSSnqe8mFJCUEyCNmo3EcF8Yzhpnc
2680000

Can you migrate Linux Bash script to python? if you can please PM.


Title: Re: GetBalance Python Script with Fiat Support
Post by: deepceleron on October 13, 2014, 07:55:54 PM
I simplified it for you.

Code:
from webbrowser import open
a = input('Address? ')
open('https://blockchain.info/address/' + a)

Replace the tabs in your code with four spaces and rename all the variables to lowercase and then we can start talking..

Addresses are not wallets, and looking up an address on some chaininfoexplorer will not yield the balance you expect.


Title: Re: GetBalance Python Script with Fiat Support
Post by: mrflibblehat on October 14, 2014, 02:43:50 PM
I simplified it for you.

Code:
from webbrowser import open
a = input('Address? ')
open('https://blockchain.info/address/' + a)

Replace the tabs in your code with four spaces and rename all the variables to lowercase and then we can start talking..

Addresses are not wallets, and looking up an address on some chaininfoexplorer will not yield the balance you expect.

That doesn't show Fiat Value, which I need.

Correct me if i'm wrong but isn't variable naming personal preference? Is there any reason why it NEEDS to be lowercase?

Also my text editor (sublimetext) is using 4 spaces per tab.


Title: Re: GetBalance Python Script with Fiat Support
Post by: deepceleron on October 14, 2014, 06:04:54 PM
Correct me if i'm wrong but isn't variable naming personal preference? Is there any reason why it NEEDS to be lowercase?

Also my text editor (sublimetext) is using 4 spaces per tab.

It's personal preference unless you want to share your code with others or make consistent interchangeable code. Then you follow PEP8 (If you don't recognize the authority or authors of that document, just note that one of them is Benevolent Dictator For Life):

Lower case for functions and variables: http://legacy.python.org/dev/peps/pep-0008/#function-names

Indentation at four spaces is also specified: http://legacy.python.org/dev/peps/pep-0008/#indentation

Highlight this quote with your mouse cursor, and you will see that as you highlight the indentation, it is not spaces, but tab characters that you cut and pasted here:

Code:

def GetBalance():
for BitcoinAddr in args.BitcoinAddresses:
blockchain = urllib3.PoolManager()
req = blockchain.request('GET', 'http://blockchain.info/q/addressbalance/' + BitcoinAddr)
SatoshiConvert = int(req.data) / 100000000
if FiatValue() == 'Error: No Such Currency':
print('no such currency {}'.format(args.Currency[0]))
break
else:
FiatConvert = FiatValue() * SatoshiConvert
print('{} - {} ({:,} {})'.format(BitcoinAddr, SatoshiConvert, round(FiatConvert, 2), args.Currency[0]))



I was pointing out the blockchain.info address interface does have a currency selector at the bottom-right that will change all BTC amounts to their fiat equivalent, writing a program to get the info is superfluous unless this snippet goes on to do better things.

You should learn about and implement exception handling when programming for the web. You do not want a flaky website controlled by someone else to be able to crash your program or do unexpected things, nor do you want unparsed user input sent to an API via your program.

https://urllib3.readthedocs.org/en/latest/exceptions.html


PHP will also get you some interwebs:
http://we.lovebitco.in/img/cal.php

This uses https://bitcoinaverage.com/api - using this exchange rate API, you could retrieve the list of supported currencies and prompt the user or do sanity checks before API calls.


Title: Re: GetBalance Python Script with Fiat Support
Post by: mrflibblehat on October 14, 2014, 06:14:00 PM
Thank you for your reply.

Right I get what your saying. I will also look into PEP8 as this is something I am unaware of, This is something I can flag to my tutor.

Thanks Again.

Mrf