Skip to content

Instantly share code, notes, and snippets.

@tupui
Last active January 16, 2018 15:55
Show Gist options
  • Save tupui/1fe11ab02cb8ab745b6f8d72dd3d8bc0 to your computer and use it in GitHub Desktop.
Save tupui/1fe11ab02cb8ab745b6f8d72dd3d8bc0 to your computer and use it in GitHub Desktop.
Gather information about your crypto wallets and the market
"""Get info about Cryptocurrency wallets.
Gather information about the market and you own wallet. Using transactions
file, it also compare your investment with the available capital.
Transactions are to be stored in JSON files formated as:
{
"2018_01_15": {
"rate": 1.505,
"balance": 166.11295,
"funding": 250
},
"2018_01_16": {
"rate": 1.1,
"balance": 45.45,
"funding": 50
}
}
---------------------------
MIT License
Copyright (c) 2018 Pamphile Tupui ROY
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from collections import defaultdict
import requests
import json
import numpy as np
import numpy.testing as npt
from stellar_base.address import Address
from iota import Iota
from iota.crypto.addresses import AddressGenerator
from iota.adapter import BadApiResponse
def market_coin(name):
"""Market information.
:param str name: Coin's name.
:return: Market information.
:rtype: dict
"""
url = 'https://api.coinmarketcap.com/v1/ticker/' + name + '/?convert=EUR'
req = requests.get(url)
market = req.json()[0]
if not req.ok:
print('Cannot get market info!')
market = None
return market
colors = {
'red': '\033[91m',
'green': '\033[92m',
'end': '\033[0m'
}
def colorize_value(value):
"""Colorize value in terminal in green or red.
:param float value: Value to convert.
:return: Colorized value.
:rtype: str
"""
value = round(value, 2)
if value < 0.:
value = colors['red'] + str(value) + colors['end']
else:
value = colors['green'] + str(value) + colors['end']
return value
# ----- My wallet -----
wallet = defaultdict(lambda: {'name': None, 'address': None, 'balance': 0,
'value': 0, 'gain': 0})
wallet['xrp']['name'] = 'ripple'
wallet['xrp']['address'] = 'XXXXXXXX'
wallet['xlm']['name'] = 'stellar'
wallet['xlm']['address'] = 'XXXXXXXX'
wallet['iota']['name'] = 'iota'
wallet['iota']['address'] = [
b'XXXXXXXX',
b'XXXXXXXX',
b'XXXXXXXX',
b'XXXXXXXX']
# Ripple
url = 'https://data.ripple.com/v2/accounts/' + wallet['xrp']['address'] + '/balances'
req = requests.get(url)
out = req.json()
if req.ok:
if out['result'] == 'success':
wallet['xrp']['balance'] = float(out['balances'][0]['value'])
else:
print(f"Ripple API Error: {out['message']}")
else:
print(f"Ripple API Error: {out['message']}")
# Stellar
xlm_address = Address(wallet['xlm']['address'])
try:
xlm_address.get()
wallet['xlm']['balance'] = float(xlm_address.balances[0]['balance'])
except Exception as err:
print(f"Stellar API Error: {err}")
# Iota
# generator = AddressGenerator(b'XXXXX')
# iota_addresses = generator.get_addresses(start=0, count=10)
# print(iota_addresses)
api = Iota('http://iota.bitfinex.com:80')
try:
data = api.get_balances(wallet['iota']['address'])
wallet['iota']['balance'] = np.sum(data['balances'])
except BadApiResponse:
print('Cannot reach IOTA server!')
# Gather Market information
market = defaultdict(lambda: {'price': 0, 'changes': [0, 0]})
total_cap = 0.
total_funding = 0.
for coin in wallet:
info = market_coin(wallet[coin]['name'])
market[coin]['changes'] = [float(info['percent_change_24h']),
float(info['percent_change_7d'])]
market[coin]['price'] = float(info['price_eur'])
# Gather transactions
book = {}
with open('transactions_' + coin + '.json', 'r') as fp:
book[coin] = json.load(fp)
# Computations
balance = np.sum([order['balance'] for order in book[coin].values()])
# Verify balance from book and servers
try:
npt.assert_allclose(wallet[coin]['balance'], balance, rtol=0.1,
err_msg=f'Online balance and book differ for {coin}!')
except AssertionError as err:
print(f'{err}')
wallet[coin]['balance'] = balance
funding = np.sum([order['funding'] for order in book[coin].values()])
total_funding += funding
wallet[coin]['value'] = market[coin]['price'] * wallet[coin]['balance']
total_cap += wallet[coin]['value']
wallet[coin]['gain'] = (wallet[coin]['value'] / funding - 1) * 100.
wallet_gain = colorize_value((total_cap / total_funding - 1) * 100.)
# ----- Output visualization -----
print('\n----- Market to Wallet information -----')
template = "{0:5} {1:13} {2:>23} {3:>23} {4:>10} {5:>10} {6:>19}"
header = template.format('Coin', ' Price(€)',
colors['end'] + 'Change(24h, %)' + colors['end'],
colors['end'] + 'Change(7d, %)' + colors['end'],
'Balance',
'Value(€)',
colors['end'] + 'Gain(%)' + colors['end'])
print('\n' + header)
sep = ("--------------------------------------------"
"---------------------------------------------")
print(sep)
for coin in wallet:
print(template.format(coin, market[coin]['price'],
colorize_value(market[coin]['changes'][0]),
colorize_value(market[coin]['changes'][0]),
round(wallet[coin]['balance'], 4),
round(wallet[coin]['value'], 2),
colorize_value(wallet[coin]['gain'])))
print(sep + '\n')
print(f"Total capitalization: {total_cap}€ ({wallet_gain}%)\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment