create account

Updated NodeJS Witness Price Feed Script by klye

View this thread on: hive.blogpeakd.comecency.com
· @klye ·
$1.40
Updated NodeJS Witness Price Feed Script
![image.png](https://files.peakd.com/file/peakd-hive/klye/YNtQ3NWD-image.png)

Rewrote my NodeJS price feed update script. Removed a shit ton of bloat as well as get rid of the naggy vote me for witness shit. No warranty or liability upon myself incurred for using this script.

```
/*------------------------------------------------------------------------
--------------------------------------------------------------------------
---- Pricesnatcher.js v0.0.3 || Open Source Price Feed Node.js Script ----
----- Developed by @KLYE || Free to Use for All! || Free to Modify -------
--------------------------------------------------------------------------
--------------------------------------------------------------------------

Having issues getting the script to run? Copy and Paste the whole line below
in order to install the necessary NodeJS dependencies for app to Function:

 npm install @hiveio/hive-js || npm install fancy-log || npm install prompt

------------------------------------------------------------------------*/

// Load dependencies for app
var hivejs = require('@hiveio/hive-js');
var log = require('fancy-log');
var prompt = require('prompt');
var request = require('request');
var fs = require('fs');

// Parse 3 decimal places
function toThree(n) {
    var number = n.toString().substring(0, n.toString().indexOf(".") + 4);
    parseFloat(number);
    return number;
}

// No need to modify these variables - setting them up for later
var witnessname;
var wif;
var url;
var bkey;
var hivefeedprice;
var sleeptime = 60000; // set this to a number to avoid sleepmins being undefined
var sleepmins = Number(sleeptime / 60000);


// Setup / New configuration file prompts
function newconfig() {
    // Start user prompts
    prompt.start();
    prompt.message = "";
    prompt.get([{
        name: 'witnessname',
        description: 'Witness Account Name? (No @)',
        required: true
    }, {
        name: 'witnessurl',
        description: "Witness Campaign URL/Website?",
        required: true
    }, {
        name: 'wifinput',
        description: "Witness Account Posting Private Key?",
        required: true,
        replace: '*',
        hidden: true
    }, {
        name: 'activekey',
        description: "Witness Account Active Key?",
        required: true,
        replace: '*',
        hidden: true
    }, {
        name: 'bkey',
        description: "Witness Account Block Signing Key?",
        required: true,
        replace: '*',
        hidden: true
    }, {
        name: 'interval',
        description: "Number of Minutes Between Update? (1 block = 3 seconds)",
        required: false,
        default: 10
    }], function(err, result) {
        // If we messed up and got error on setup
        if (err) {
            log("Prompt ERROR: Something Went Wrong During Config.. Restarting! Service! (ctrl + c to exit)")
        };
        // if setup was completed properly
        if (result) {
            // create array of answers to save
            var newconfig = {
                witnessname: result.witnessname,
                wif: result.wifinput,
                url: result.witnessurl,
                activekey: result.activekey,
                bkey: result.bkey,
                interval: result.interval * 1000,
            };
            log("SUCCESS: You Completed The Configuration - Saving to Disk!");
            // Save data to file
            fs.writeFile(__dirname + "/pricesnatcher.config", JSON.stringify(newconfig), function(err, win) {
                if (err) {
                    log("ERROR: Unable to Save Config to Disk!");
                };
                if (win) {
                    log("Config SUCCESS: New Configuration Saved");
                    // Start price feed
                    getPrice();
                };
            }); // END config writeFile
            // Start price feed (backup/redundancy)
            getPrice();
        }; //END if (result)
    }); // END Setup Prompt
}; // END newconfig();

// Update / Publish Price Function
function updateprice() {
    // if HIVE price is borked (NaN) request price again
    if (hivefeedprice == NaN) {
      log(`Price ERROR: hivefeedprice == NaN! - Restarting!!`);
      getPrice();
    } else {
        // create array vairable to contain update message
        var exchangeRate = {
            "base": hivefeedprice + " HBD",
            "quote": "1.000 HIVE"
        };
        // Set RPC Node to HIVE
        hivejs.config.set('websocket', 'wss://api.hive.blog');
        // Broadcast the updated price feed
        hivejs.broadcast.feedPublish(activekey, witnessname, exchangeRate, function(err, result) {
            // if price feed publish errors
            if (err) {
                log("Publish ERROR: Price Feed Update FAILED!");
            };
            // if price feed publish success
            if (result) {
              // Check update interval after updating and show correctly timescale to user
              if(sleepmins <= 1) {
                log(`Update SUCCESS: 1 HIVE = $${hivefeedprice} USD - Checking in ${sleeptime / 1000} Seconds`);
              } else {
                log(`Update SUCCESS: 1 HIVE = $${hivefeedprice} USD - Checking in ${sleepmins} Minutes`);
              } // END else
            }; // END if (result)
        }); // END hivejs.broadcast.feedPublish
    }; // END else
}; // END function updateprice

function getPrice(){
  // clear get getPrice loop interval (to avoid potential insanity)
  clearInterval(getPrice);
      // Read the config
      fs.readFile(__dirname + "/pricesnatcher.config", function(err, data) {
          if (err) {
              log("Config ERROR: Reading Config File!");
          };
          if (data) {
            try{
              data = JSON.parse(data);
              witnessname = data.witnessname;
              wif = data.wif;
              url = data.url;
              activekey = data.activekey;
              bkey = data.bkey;
              sleeptime = data.interval;
              sleepmins = Number(sleeptime / 60000);
            } catch(e) {
              log("Config ERROR: Reading Config File!");
            }
          }; // END if (data)
      }); // End readFile
      // Connect to Coingecko.com to retrieve HIVE/BTC price
      request('https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd&include_market_cap=false', function(error, response, body) {

        // Create a variable to stuff request response into
        var pricereply;
        // Attempt to parse received response for HIVE price
        try {
          pricereply = JSON.parse(body);
          pricereply = pricereply.hive;
          pricereply = pricereply["usd"];
          hivefeedprice = toThree(pricereply);
        } catch(e){
          log(`Fetch ERROR: Price Call Failed! - Restarting!`);
          getPrice();
        }
          // if the HIVE price has been found and isn't undefined, NaN or null
          if (hivefeedprice != undefined && hivefeedprice != NaN && hivefeedprice != null) {
             updateprice();
          } else {
            log(`Fetch ERROR: Price Call Failed! - Restarting!`);
            getPrice();
          }; // END else
      });
  };

// Check if config file exists
if (!fs.existsSync(__dirname + "/pricesnatcher.config")) {
    log("WARNING: No Configuration Found! Please Run Setup Below!");
    newconfig();
} else {
    // Read config if found
    fs.readFile(__dirname + "/pricesnatcher.config", function(err, details) {
        if (err) {
            log("Config ERROR: Unable to Read Configuration File!");
        }
        if (details) {
            details = JSON.parse(details);
            sleeptime = details.interval;

            // Start Price Feed
            log(`STARTING: Hive Price Feed v0.0.3 by @KLYE`);
            setInterval(getPrice, sleeptime);
        };
    });
};
```

It's only the coingecko average.. But I figured they aggregate their price from a variety of exchanges so rather than do a bunch of price queries just do one for efficiency sake. Includes a setup wizard and anyone with the knowledge of how to run a NodeJS script locally should be able to get this one running. Prior script had a bug in it which caused it to spaz the fuck out and try to update to much.

<center>Welp, I'm back off to go work on the upcoming Hive-Roller.com release. Cheers!</center>

<hr>

<center>[![image.png](https://files.peakd.com/file/peakd-hive/klye/kSugxl8n-image.png)](Https://www.Hive-Roller.com)<h3><a href="https://vote.hive.uno/@klye"><sub>Vote KLYE for Witness, Every Single Vote Helps, Thanks for the Support!</sub></a><br><br><b><i>Need to get in Contact with KLYE?</i></b><br><a href="https://discord.gg/mtwvCpS" rel="noopener" title="This link will take you away from steemit.com">Join the Official #KLYE Discord Server Today!</a></center></h3><br><sub><a href="https://pay.privex.io/order?r=klye">![image.png](https://files.steempeak.com/file/steempeak/klye/LrNonZ6Y-image.png)</a><br>Looking for an Affordable, Secure & Reliable Server Host for Your Witness Server or Other Web Related Projects? Check out Privex.io!</sub>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 25 others
properties (23)
authorklye
permlinkupdated-nodejs-witness-price-feed-script
categorywitness
json_metadata{"app":"peakd/2020.09.4","format":"markdown","tags":["witness","hivedev","witness-category","coding","nodejs","javascript"],"users":["KLYE","hiveio","klye"],"links":["Https://www.Hive-Roller.com","https://vote.hive.uno/@klye","https://discord.gg/mtwvCpS","https://pay.privex.io/order?r=klye"],"image":["https://files.peakd.com/file/peakd-hive/klye/YNtQ3NWD-image.png","https://files.peakd.com/file/peakd-hive/klye/kSugxl8n-image.png","https://files.steempeak.com/file/steempeak/klye/LrNonZ6Y-image.png"]}
created2020-09-20 18:03:30
last_update2020-09-20 18:03:30
depth0
children2
last_payout2020-09-27 18:03:30
cashout_time1969-12-31 23:59:59
total_payout_value0.758 HBD
curator_payout_value0.638 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,169
author_reputation412,341,527,771,769
root_title"Updated NodeJS Witness Price Feed Script"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id99,729,936
net_rshares7,001,613,714,827
author_curate_reward""
vote details (89)
@hiveqa ·
# PRICESNATCHERS!!!!!!!
👍  
properties (23)
authorhiveqa
permlinkre-klye-qgyyt7
categorywitness
json_metadata{"tags":["witness"],"app":"peakd/2020.09.4"}
created2020-09-20 18:17:30
last_update2020-09-20 18:17:30
depth1
children1
last_payout2020-09-27 18:17:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length23
author_reputation6,767,181,889,680
root_title"Updated NodeJS Witness Price Feed Script"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id99,730,119
net_rshares124,377,672,267
author_curate_reward""
vote details (1)
@klye ·
Like booty snatchers but less ass.
properties (22)
authorklye
permlinkre-hiveqa-qh0gja
categorywitness
json_metadata{"tags":["witness"],"app":"peakd/2020.09.4"}
created2020-09-21 13:37:57
last_update2020-09-21 13:37:57
depth2
children0
last_payout2020-09-28 13:37:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length34
author_reputation412,341,527,771,769
root_title"Updated NodeJS Witness Price Feed Script"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id99,743,445
net_rshares0