Part 22: Calculate Account Value Based On Current Market Prices Via API
This tutorial is part of a series where different aspects of programming with steem-python
are explained. Links to the other tutorials can be found in the curriculum section below. The wallet on Steemit.com shows the account value based on the 3 day moving average of the Steem
price and it also assumes that 1 SBD
is worth 1 dollar. This tutorial will learn you how to calculate the value of your account based on current market prices for both Steem
and SBD
.
Repository
https://github.com/steemit/steem-python
What will I learn
- Use Coinmarketcap API to retrieve current market prices
- Retrieve account balances
- Convert VESTS to Steem
Requirements
- Python3.6
steem-python
Difficulty
- basic
Tutorial
Setup
Download the file from Github. There is 1 file account_value.py
which contains the code. The file takes 1 argument from the command line which sets the account
for which the market value will be calculated.
Run scripts as following:
> python account_value.py steempytutorials
Use Coinmarketcap API to retrieve current market prices
Coinmarketcap.com is a popular website that has data for over 1600 different crypto assets including Steem
and SBD
. There is an API interface which allows for easy access to current market prices.
import json, requests
def get_market_price(token):
api_url = 'https://api.coinmarketcap.com/v1/ticker/{}/'.format(token)
response = requests.get(api_url)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))[0]['price_usd']
else:
return None
In order to retrieve the current data for a specific token an API request has to be made. The request is made up out of an url, the syntax that Coinmarketcap uses is as follows https://api.coinmarketcap.com/v1/ticker/<token name>
. This will return a json object, which after decoding shows the following:
[{
'id': 'steem',
'name': 'Steem',
'symbol': 'STEEM',
'rank': '30',
'price_usd': '3.84594',
'price_btc': '0.00039802',
'24h_volume_usd': '15486900.0',
'market_cap_usd': '977568942.0',
'available_supply': '254182057.0',
'total_supply': '271156151.0',
'max_supply': None,
'percent_change_1h': '-0.16',
'percent_change_24h': '-4.08',
'percent_change_7d': '-5.93',
'last_updated': '1525448347'
}]
The data for price_usd
is contained inside a dict that is inside a list. [0]['price_usd']
will retrieve the data.
Retrieve account balances
Steem-python
has a function account.get_balances()
that is part of the Account
class which can be used to retrieve all account balances for a specific account.
from steem.account import Account
account = Account(str(username), s)
for key, value in account.get_balances()['total'].items():
if key not in stats:
stats[key] = value
Running the function will return a dict containing all the balances for the account. To calculate the total account value data under total
is needed. Steem Power
is listed as VESTS
and has to be converted into the Steem Power
equivalent.
{
'available': {
'STEEM': 11.705,
'SBD': 1.302,
'VESTS': 136673.580674
},
'savings': {
'STEEM': 0.0,
'SBD': 0.0
},
'rewards': {
'STEEM': 0.0,
'SBD': 0.0,
'VESTS': 0.0
},
'total': {
'STEEM': 11.705,
'SBD': 1.302,
'VESTS': 136673.581
}
}
Convert VESTS to Steem
To convert VESTS
to Steem
the ratio between total_vesting_shares
and total_vesting_fund_steem
has to be calculated and then multiplied with the amount of VESTS
. The Steem
class contains the function get_dynamic_global_properties
that allows this data to be retrieved. The Amount class will be used to make the data usable for calculations.
from steem.amount import Amount
data = s.get_dynamic_global_properties()
total_vesting_shares = Amount(data["total_vesting_shares"]).amount
total_vesting_fund_steem = Amount(data["total_vesting_fund_steem"]).amount
ratio = total_vesting_fund_steem/total_vesting_shares
A lot of useful information about the steem blockchain can be found in this manner. However only total_vesting_shares
and total_vesting_fund_steem
are needed for this tutorial.
{
'id': 0,
'head_block_number': 22139173,
'head_block_id': '0151d125dd33013110dff3fd612497682ac4cd82',
'time': '2018-05-04T16:00:15',
'current_witness': 'smooth.witness',
'total_pow': 514415,
'num_pow_witnesses': 172,
'virtual_supply': '271157259.064 STEEM',
'current_supply': '267866951.902 STEEM',
'confidential_supply': '0.000 STEEM',
'current_sbd_supply': '12921036.227 SBD',
'confidential_sbd_supply': '0.000 SBD',
'total_vesting_fund_steem': '191058886.451 STEEM',
'total_vesting_shares': '389019963857.433024 VESTS',
'total_reward_fund_steem': '0.000 STEEM',
'total_reward_shares2': '0',
'pending_rewarded_vesting_shares': '381908260.635943 VESTS',
'pending_rewarded_vesting_steem': '186156.473 STEEM',
'sbd_interest_rate': 0,
'sbd_print_rate': 10000,
'maximum_block_size': 65536,
'current_aslot': 22204805,
'recent_slots_filled': '340282366920938463463374607431768211455',
'participation_count': 128,
'last_irreversible_block_num': 22139156,
'vote_power_reserve_rate': 10,
'current_reserve_ratio': 45937724,
'average_block_size': 16006,
'max_virtual_bandwidth': '60693185550090240000'
}
Running the script
Running the script will fetch current market prices for Steem and SBD and retrieve the total account balances for Steem, SBD and Steem Power. In the end the dollar value of all assets will be displayed.
python account_value.py steempytutorials
...
Steem/USD: 2.26
SBD/USD: 1.69
Steem: 4.786
SBD: 1.312
Steem Power: 52.874
Dollar value: 132.52
Curriculum
Set up:
- Part 0: How To Install Steem-python, The Official Steem Library For Python
- Part 1: How To Configure The Steempy CLI Wallet And Upvote An Article With Steem-Python
Filtering
- Part 2: How To Stream And Filter The Blockchain Using Steem-Python
- Part 6: How To Automatically Reply To Mentions Using Steem-Python
Voting
- Part 3: Creating A Dynamic Autovoter That Runs 24/7
- Part 4: How To Follow A Voting Trail Using Steem-Python
- Part 8: How To Create Your Own Upvote Bot Using Steem-Python
Posting
- Part 5: Post An Article Directly To The Steem Blockchain And Automatically Buy Upvotes From Upvote Bots
- Part 7: How To Schedule Posts And Manually Upvote Posts For A Variable Voting Weight With Steem-Python
Constructing
Rewards
- Part 9: How To Calculate A Post's Total Rewards Using Steem-Python
- Part 12: How To Estimate Curation Rewards Using Steem-Python
- Part 14: How To Estimate All Rewards In Last N Days Using Steem-Python
Transfers
- Part 11: How To Build A List Of Transfers And Broadcast These In One Transaction With Steem-Python
- Part 13: Upvote Posts In Batches Based On Current Voting Power With Steem-Python
Account Analysis
- Part 15: How To Check If An Account Is Following Back And Retrieve Mutual Followers/Following Between Two Accounts
- Part 16: How To Analyse A User's Vote History In A Specific Time Period Using Steem-Python
- Part 18: How To Analyse An Account's Resteemers Using Steem-Python
The code for this tutorial can be found on GitHub!
This tutorial was written by @juliank in conjunction with @amosbastian.
Nice! This could come in handy. Here are a few small pieces of advice to make the python even slicker.
Replace
json.loads(response.content.decode('utf-8'))
withresponse.json()
in this line. Requests has a builtin function to parse JSON payloads.Use Literal String Interpolation (f-strings) in the print statements at the end:
f-strings are only available in Python 3.6+, but you've specified 3.6 as a requirement! Yay for being up to date.
Finally, you may want to look into flake8 to help lint your code... it's pretty clean but there is some non-standard styling, like the spaces after the print statements and before the parenthesis.
Keep the #python #tutorials coming!
Hey @dhimmel
Here's a tip for your valuable feedback! @Utopian-io loves and incentivises informative comments.
Contributing on Utopian
Learn how to contribute on our website.
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!
Much appreciated for the feedback! I will take it into account for the next tutorial.
very good tutorial python.
Working my way through this series. Excited that there's a new one
Glad to hear. Enjoy! Have some new ideas for new tutorials, will do my best to keep them coming again
Very helpful tutorial, kudos
You are welcome
Awesome tutorial! Thanks for the contribution.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Hey @steempytutorials
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!
Thanks for awesome tutorials! I am experimenting with python and steemit also, it's look like game with complex rules, and nice to see, that rules can be checked with any users themselves.
let's share each other also