Code snippet to calculate the USD value of your liquid assets based on their market price

avatar
(Edited)

















Here is an easy way to calculate how much the liquid assets in your wallet are worth in US Dollars based on their real time value on the market.

This brief tutorial relies on web scraping so that you do not have to deal with third party API registration, private and public keys.

It simply extracts the small piece of information that you need from https://coingecko.com.

This code can be added in a website or in a NodeJs script.

How to test this code snippet in a browser:

  • Open your favorite browser (I strongly recommend using Brave browser for its speed and security)

  • Navigate to https://cdn.jsdelivr.net/npm/steem/dist/steem.min.js (SteemJs)

  • On that page open the DevTools (Ctrl + Shift + J on Linux/Windows and Cmd + Opt + J on Mac)

  • Copy & paste (Ctrl + A and Ctrl + C) the steem.js code displayed on that page into the Browser Console and press enter.

  • Copy & paste my script below into the Console

  • Change the variables at the top of the script:
        - TARGET_ACCOUNT: the steem/hive acount to read
        - PLATFORM: whether this script runs in a website or in Node
        - CHAIN: the chain to use (HIVE or STEEM)

  • Press enter.



Code snippet:

// ===================================================================
const TARGET_ACCOUNT = 'gaottantacinque'; // your steemit account
const PLATFORM = 'browser'; // browser or node
const CHAIN = 'hive'; // hive or steem
// ===================================================================


if (PLATFORM === 'node' && !window.steem) {
  window.steem = require('steem');
}
if (CHAIN === 'hive') {
  window.steem.api.setOptions({ url: 'https://api.hive.blog' });
  window.steem.config.set('address_prefix', 'STM');
  window.steem.config.set(
    'chain_id',
    '0000000000000000000000000000000000000000000000000000000000000000',
  );
}


var fetchUsdValue = ({ urlId, tagId }) => new Promise((resolve) => {
  const coingeckoUrl = `${
    PLATFORM === 'browser' ? 'https://cors-anywhere.herokuapp.com/' : ''
  }https://www.coingecko.com/en/coins/${urlId}`; // urlId: hive, hive_dollar, steem, steem-dollars
  fetch(coingeckoUrl)
    .then(res => res.text())
    .then((text = '') => {
      // tagId: 'hive', 'hbd', 'steem', 'sbd'
      const rawData = text.toLowerCase().split(`data-coin-symbol="${tagId}"`)[1] || '';
      const priceTail = rawData.split('$')[1] || '';
      const price = priceTail.split('</')[0];
      console.log(tagId, 'price USD:', price);
      resolve(price);
    });
});

var fetchAndCalcEstimate = ({ baseCoinConfig, usdCoinConfig }) => new Promise((resolve) => {
  const { amount: baseCoinAmount } = baseCoinConfig;
  const { amount: usdCoinAmount } = usdCoinConfig;
  const baseCoinFetch = fetchUsdValue(baseCoinConfig);
  const usdCoinFetch = fetchUsdValue(usdCoinConfig);
  Promise.all([baseCoinFetch, usdCoinFetch])
    .then(([baseCoinUsd, usdCoinUsd]) => {
      const baseCoinValue = baseCoinAmount * baseCoinUsd;
      console.log(`BaseCoinAmount ${baseCoinAmount} * baseCoinUSd ${baseCoinUsd} = ${baseCoinValue}`);
      const usdCoinValue = usdCoinAmount * usdCoinUsd;
      console.log(`usdCoinAmount ${usdCoinAmount} * usdCoinUsd ${usdCoinUsd} = ${usdCoinValue}`);
      const estimate = (baseCoinValue + usdCoinValue).toFixed(3);
      resolve(estimate);
    });
});

var getAccountValueEstimate = ({
  hive, // Int: HIVE or STEEM
  hbd, // Int: HBD or SBD
  currency, // Str: 'HIVE' or 'STEEM'
}) => new Promise(async (resolve) => {
  let config = {};
  if (currency === 'HIVE') {
    config.baseCoinConfig = { amount: hive, urlId: 'hive', tagId: 'hive' };
    config.usdCoinConfig = { amount: hbd, urlId: 'hive_dollar', tagId: 'hbd' };
  } else {
    config.baseCoinConfig = { amount: hive, urlId: 'steem', tagId: 'steem' };
    config.usdCoinConfig = { amount: hbd, urlId: 'steem-dollars', tagId: 'sbd' };
  }
  const estimate = await fetchAndCalcEstimate(config);
  resolve(estimate);
});

var printBalance = (username) => {
  steem.api.getAccounts([username], async (err, result) => {
    if (err) {
      console.error(`Unable to load balances: ${err}`);
      return;
    }
    const { balance = '', savings_balance = '', sbd_balance = '' } = result[0];
    // {"balance":"13.709 HIVE","savings_balance":"0.000 HIVE","sbd_balance":"1.136 HBD"}
    const [balanceStr, currency] = balance.split(' ');
    const [savingsStr] = savings_balance.split(' ');
    const [hbdStr] = sbd_balance.split(' ');
    const wallet = { hive: +balanceStr + +savingsStr, hbd: +hbdStr, currency };
    const hiveAmount = `${wallet.hive} ${currency}`;
    const hbdAmount = sbd_balance;
    const estimate = await getAccountValueEstimate(wallet);
    console.log(`
      Liquid assets: ${hiveAmount}, ${hbdAmount}
      
      Total value: $ ${estimate}
    `);
  });
};
printBalance(TARGET_ACCOUNT);



To execute the script again for a different account just press the UP button, change the top variable and press enter again.


Usage example on a website:

Enjoy!   =]



0
0
0.000
3 comments
avatar

I'm worried my mobile browser will wreck this neat code is it going to be compatible with the mobile browser of brave?

0
0
0.000