<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>
      NiceHash.js - Documentation
  </title>

  <link href="https://www.braintreepayments.com/images/favicon-ccda0b14.png" rel="icon" type="image/png">

  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.7.0/highlight.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.3.0/highlightjs-line-numbers.min.js"></script>
  <script>
    hljs.initHighlightingOnLoad();
  </script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

  <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
  <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
  <link type="text/css" rel="stylesheet" href="styles/monokai-sublime.css">

  

  <!-- start Mixpanel -->
  <script type="text/javascript">(function(e,a){if(!a.__SV){var b=window;try{var c,l,i,j=b.location,g=j.hash;c=function(a,b){return(l=a.match(RegExp(b+"=([^&]*)")))?l[1]:null};g&&c(g,"state")&&(i=JSON.parse(decodeURIComponent(c(g,"state"))),"mpeditor"===i.action&&(b.sessionStorage.setItem("_mpcehash",g),history.replaceState(i.desiredHash||"",e.title,j.pathname+j.search)))}catch(m){}var k,h;window.mixpanel=a;a._i=[];a.init=function(b,c,f){function e(b,a){var c=a.split(".");2==c.length&&(b=b[c[0]],a=c[1]);b[a]=function(){b.push([a].concat(Array.prototype.slice.call(arguments,
  0)))}}var d=a;"undefined"!==typeof f?d=a[f]=[]:f="mixpanel";d.people=d.people||[];d.toString=function(b){var a="mixpanel";"mixpanel"!==f&&(a+="."+f);b||(a+=" (stub)");return a};d.people.toString=function(){return d.toString(1)+".people (stub)"};k="disable time_event track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config reset people.set people.set_once people.increment people.append people.union people.track_charge people.clear_charges people.delete_user".split(" ");
  for(h=0;h<k.length;h++)e(d,k[h]);a._i.push([b,c,f])};a.__SV=1.2;b=e.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?MIXPANEL_CUSTOM_LIB_URL:"file:"===e.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";c=e.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c)}})(document,window.mixpanel||[]);
  mixpanel.init("1919205b2da72e4da3b9b6639b444d59");</script>
  <!-- end Mixpanel -->
</head>

<body>
  <svg style="display: none;">
    <defs>
      <symbol id="linkIcon" fill="#706d77" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
          <path d="M0 0h24v24H0z" fill="none"/>
          <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/>
      </symbol>
    </defs>
  </svg>

  <input type="checkbox" id="nav-trigger" class="nav-trigger" />
  <label for="nav-trigger" class="navicon-button x">
    <div class="navicon"></div>
  </label>

  <label for="nav-trigger" class="overlay"></label>

  <div class="top-nav-wrapper">
    <ul>
      <li >
        <a href="index.html">
          
            <svg fill="#6D6D6D" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
              <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
              <path d="M0 0h24v24H0z" fill="none"/>
            </svg>
          
          
        </a>
      </li>

      

    </ul>
  </div>

  <nav>
    <h3 class="reference-title">
      NiceHash
    </h3>

    <h3>Classes</h3><ul><li id="NiceHash-nav"><a href="NiceHash.html">NiceHash</a><ul class='methods'><li data-type="method" id="NiceHash-api-nav"><a href="NiceHash.html#api">api</a></li><li data-type="method" id="NiceHash-createOrder-nav"><a href="NiceHash.html#createOrder">createOrder</a></li><li data-type="method" id="NiceHash-decreaseOrderPrice-nav"><a href="NiceHash.html#decreaseOrderPrice">decreaseOrderPrice</a></li><li data-type="method" id="NiceHash-getBalance-nav"><a href="NiceHash.html#getBalance">getBalance</a></li><li data-type="method" id="NiceHash-getBuyInfo-nav"><a href="NiceHash.html#getBuyInfo">getBuyInfo</a></li><li data-type="method" id="NiceHash-getCurrentGlobalStats-nav"><a href="NiceHash.html#getCurrentGlobalStats">getCurrentGlobalStats</a></li><li data-type="method" id="NiceHash-getCurrentGlobalStats24h-nav"><a href="NiceHash.html#getCurrentGlobalStats24h">getCurrentGlobalStats24h</a></li><li data-type="method" id="NiceHash-getMultiAlgoInfo-nav"><a href="NiceHash.html#getMultiAlgoInfo">getMultiAlgoInfo</a></li><li data-type="method" id="NiceHash-getOrders-nav"><a href="NiceHash.html#getOrders">getOrders</a></li><li data-type="method" id="NiceHash-getOrdersForAlgorithm-nav"><a href="NiceHash.html#getOrdersForAlgorithm">getOrdersForAlgorithm</a></li><li data-type="method" id="NiceHash-getProviderPayments-nav"><a href="NiceHash.html#getProviderPayments">getProviderPayments</a></li><li data-type="method" id="NiceHash-getProviderStats-nav"><a href="NiceHash.html#getProviderStats">getProviderStats</a></li><li data-type="method" id="NiceHash-getProviderStatsEx-nav"><a href="NiceHash.html#getProviderStatsEx">getProviderStatsEx</a></li><li data-type="method" id="NiceHash-getSingleMultiAlgoInfo-nav"><a href="NiceHash.html#getSingleMultiAlgoInfo">getSingleMultiAlgoInfo</a></li><li data-type="method" id="NiceHash-getWorkersStats-nav"><a href="NiceHash.html#getWorkersStats">getWorkersStats</a></li><li data-type="method" id="NiceHash-refillOrder-nav"><a href="NiceHash.html#refillOrder">refillOrder</a></li><li data-type="method" id="NiceHash-removeOrder-nav"><a href="NiceHash.html#removeOrder">removeOrder</a></li><li data-type="method" id="NiceHash-setOrderLimit-nav"><a href="NiceHash.html#setOrderLimit">setOrderLimit</a></li><li data-type="method" id="NiceHash-setOrderPrice-nav"><a href="NiceHash.html#setOrderPrice">setOrderPrice</a></li><li data-type="method" id="NiceHash-testAuthorization-nav"><a href="NiceHash.html#testAuthorization">testAuthorization</a></li></ul></li></ul>
  </nav>

  <div id="main">
    
      <h1 class="page-title">
        NiceHash.js
      </h1>
    

    
      

<section>
  <article>
    <pre class="prettyprint source linenums"><code>import axios from 'axios';
import algorithms from './algorithms'

/**
 * An importable JavaScript class to make REST requests to the NiceHash APi
 */
class NiceHash {
	/**
	 * instantiate a NiceHash class that you can use to make REST requests to the NiceHash API
	 * @param {string} api_key - NiceHash api key
	 * @param {string|number} api_id - NiceHash api id
	 */

	constructor(api_key, api_id) {
		this.base_url = "https://api.nicehash.com/api";

		if (api_key &amp;&amp; (api_key.api_key || api_key.key)) {
			this.key = api_key.api_key || api_key.key
			this.id = api_key.api_id || api_key.id
		} else {
			this.key = api_key
			this.id = api_id
		}

		this.apikey = {key: this.key, id: this.id}
	}

	//----------------------------PUBLIC----------------------------------
	/**
	 * Test Authorization
	 * @async
	 * @returns {Promise&lt;Boolean>}
	 */
	async testAuthorization(){
		let api = this.api("");
		try {
			let res = (await api.get()).data;
			return !!res.result
		} catch(err) {
			throw new Error(`Test Authorization request failed: ${err}`)
		}
	}

	/**
	 * Get current profitability (price) and hashing speed for all algorithms. Refreshed every 30 seconds.
	 * ${number} [location] - 0 for Europe, 1 for USA. Both if omitted.
	 * @async
	 * @return {Promise&lt;Array.&lt;Object>>}
	 */
	async getCurrentGlobalStats(location) {
		let params = {
			method: "stats.global.current",
			location
		};
		let api = this.api("", params)
		try {
			let res = (await api.get()).data;
			if (res.result &amp;&amp; res.result.stats) {
				for (let stat of res.result.stats) {
					stat.algo = algorithms[stat.algo]
				}
				return res.result.stats
			}
		} catch (err) {
			throw new Error(`Failed to get current global state: ${err}`)
		}
	}

	/**
	 * Get average profitability (price) and hashing speed for all algorithms in past 24 hours.
	 * @async
	 * @return {Promise&lt;Array.&lt;Object>>}
	 */
	async getCurrentGlobalStats24h() {
		let params = {
			method: "stats.global.24h",
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			if (res.result &amp;&amp; res.result.stats) {
				for (let stat of res.result.stats) {
					stat.algo = algorithms[stat.algo]
				}
				return res.result.stats
			}
		} catch (err) {
			throw new Error(`Failed to get current global state: ${err}`)
		}
	}

	/**
	 * Get current stats for provider for all algorithms. Refreshed every 30 seconds. It also returns past 56 payments
	 * @param {string} addr - Provider's BTC address.
	 * @async
	 * @return {Promise&lt;Object>}
	 */
	async getProviderStats(addr) {
		let params = {
			method: "stats.provider",
			addr
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			return res.result
		} catch (err) {
			throw new Error(`Failed to get current global state: ${err}`)
		}
	}

	/**
	 * Get detailed stats for provider for all algorithms including history data and payments in past 7 days.
	 * @param {string} addr - Provider's BTC address.
	 * @param {number} [from] - Get history data from this time (UNIX timestamp). This parameter is optional and is by default considered to be 0 (return complete history)
	 * @async
	 * @return {Promise&lt;Object>}
	 */
	async getProviderStatsEx(addr, from) {
		let params = {
			method: "stats.provider.ex",
			addr,
			from
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			return res.result
		} catch (err) {
			throw new Error(`Failed to get current global state: ${err}`)
		}
	}

	/**
	 * Get payments for provider.
	 * @param {string} addr - Provider's BTC address.
	 * @param {number} [from] - Get history data from this time (UNIX timestamp). This parameter is optional and is by default considered to be 0 (return complete history)
	 * @async
	 * @return {Promise&lt;Object>}
	 */
	async getProviderPayments(addr, from) {
		let params = {
			method: "stats.provider.payments",
			addr,
			from
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			return res.result
		} catch (err) {
			throw new Error(`Failed to get payments for provider: ${err}`)
		}
	}

	/**
	 * Get detailed stats for provider's workers (rigs).
	 * @param {string} addr - Provider's BTC address;
	 * @param {number|number} algo - Algorithm marked with ID or its name
	 * @async
	 * @return {Promise&lt;Object>}
	 */
	async getWorkersStats(addr, algo) {
		let params = {
			method: "stats.provider.workers",
			addr,
			algo: checkAlgo(algo)
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			return res.result
		} catch (err) {
			throw new Error(`Failed to get stats for provider's workers: ${err}`)
		}
	}

	/**
	 * Get all orders for certain algorithm. Refreshed every 30 seconds.
	 * @param {number} location - 0 for Europe (NiceHash), 1 for USA (WestHash);
	 * @param {number|string} algo - Algorithm marked with ID or its name.
	 * @async
	 * @return {Promise&lt;Array.&lt;Object>>}
	 */
	async getOrdersForAlgorithm(location, algo) {
		let params = {
			method: "orders.get",
			location,
			algo: checkAlgo(algo)
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result.orders
			}
		} catch (err) {
			throw new Error(`Failed to get orders for algo: ${err}`)
		}
	}

	/**
	 * Get information about Mult-Algorithm Mining
	 * @async
	 * @returns {Promise&lt;Array.&lt;Object>>}
	 */
	async getMultiAlgoInfo() {
		let params = {
			method: "multialgo.info"
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result.multialgo
			}
		} catch (err) {
			throw new Error(`Failed to get multi algo info: ${err}`)
		}
	}

	/**
	 * Get information about Simple Multi-Algorithm Mining
	 * @async
	 * @returns {Promise&lt;Array.&lt;Object>>}
	 */
	async getSingleMultiAlgoInfo() {
		let params = {
			method: "simplemultialgo.info"
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result.simplemultialgo
			}
		} catch (err) {
			throw new Error(`Failed to get single multi algo info: ${err}`)
		}
	}

	/**
	 * Get needed information for buying hashing power using NiceHashBot.
	 * @async
	 * @returns {Promise&lt;Array.&lt;Object>>}
	 */
	async getBuyInfo() {
		let params = {
			method: "buy.info"
		};
		let api = this.api("", params);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result.algorithms
			}
		} catch (err) {
			throw new Error(`Failed to get buy info: ${err}`)
		}
	}

	//----------------------------PRIVATE----------------------------------
	/**
	 * Get all orders for certain algorithm owned by the customer. Refreshed every 30 seconds.
	 * @param {Object} options
	 * @param {number} [options.location=0] - 0 for Europe (NiceHash), 1 for USA (WestHash);
	 * @param {number|string} [options.algo="scrypt"] - Algorithm ID or name
	 * @async
	 * @returns {Promise&lt;Array.&lt;Object>>}
	 */
	async getOrders(options = {}) {
		if (!this.id || !this.key)
			throw new Error('Must provide api key and api id on initialize')
		options = {
			method: "orders.get",
			my: '',
			...this.apikey,
			location: options.location || 0,
			algo: checkAlgo(options.algo) || 0
		}
		let api = this.api("", options);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result.orders
			}
		} catch (err) {
			throw new Error(`Failed to get orders: ${err}`)
		}
	}

	/**
	 * Create new order. Only standard orders can be created with use of API.
	 * @param options
	 * @param {string} options.pool_host - Pool hostname or IP;
	 * @param {string} options.pool_port - Pool port
	 * @param {string} options.pool_user - Pool username
	 * @param {string} options.pool_pass - Pool password
	 * @param {string|number} [options.location=1] - 0 for Europe (NiceHash), 1 for USA (WestHash);
	 * @param {string|number} [options.algo='scrypt'] - Algorithm name or ID
	 * @param {string|number} [options.amount=0.005]  - Pay amount in BTC;
	 * @param {string|number} [options.price=] - Price in BTC/GH/day or BTC/TH/day;
	 * @param {string|number} [options.limit=0.01] - Speed limit in GH/s or TH/s (0 for no limit);
	 * @param {string|number} [options.code] - This parameter is optional. You have to provide it if you have 2FA enabled. You can use NiceHash2FA Java application to generate codes.
	 * @async
	 * @returns {Promise&lt;Object>}
	 */
	async createOrder(options = {}) {
		if (!this.id || !this.key)
			throw new Error('Must provide api key and api id on initialize')
		options = {
			method: "orders.create",
			...this.apikey,
			location: options.location || 1,
			algo: checkAlgo(options.algo) || 0,
			amount: options.amount || 0.005,
			price: options.price,
			limit: options.limit || 0.01,
			pool_host: options.pool_host,
			pool_port: options.pool_port,
			pool_user: options.pool_user,
			pool_pass: options.pool_pass || 'x',
			code: options.code || undefined
		}
		let api = this.api("", options);
		try {
			return (await api.get()).data;
		} catch (err) {
			throw new Error(`Failed to create orders: ${err}`)
		}
	}

	/**
	 * Create new order. Only standard orders can be created with use of API.
	 * @param options
	 * @param {string|number} options.location=0 - 0 for Europe (NiceHash), 1 for USA (WestHash);
	 * @param {string|number} options.algo="scrypt" - Algorithm name or ID
	 * @param {string|number} options.amount - Pay amount in BTC;
	 * @param {string|number} options.order - Order ID
	 * @async
	 * @returns {Promise&lt;Object>}
	 */
	async refillOrder(options = {}) {
		if (!this.id || !this.key)
			throw new Error('Must provide api key and api id on initialize')
		options = {
			method: "orders.refill",
			...this.apikey,
			location: options.location || 0,
			algo: checkAlgo(options.algo) || 0,
			order: options.order,
			amount: options.amount,
		}
		let api = this.api("", options);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result
			}
		} catch (err) {
			throw new Error(`Failed to refill orders: ${err}`)
		}
	}

	/**
	 * Remove existing order.
	 * @param {string|number} location=0 - 0 for Europe (NiceHash), 1 for USA (WestHash);
	 * @param {string|number} algo="scrypt" - Algorithm name or ID
	 * @param {string|number} order - Order ID
	 * @async
	 * @returns {Promise&lt;Object>}
	 */
	async removeOrder(id, location, algo) {
		if (!this.id || !this.key)
			throw new Error('Must provide api key and api id on initialize')
		let options = {
			method: "orders.remove",
			...this.apikey,
			location: location || 1,
			algo: checkAlgo(algo) || 0,
			order: id,
		}
		let api = this.api("", options);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result
			}
		} catch (err) {
			throw new Error(`Failed to remove orders: ${err}`)
		}
	}

	/**
	 * Set new price for the existing order. Only increase is possible.
	 * @param options
	 * @param {string|number} options.location=0 - 0 for Europe (NiceHash), 1 for USA (WestHash);
	 * @param {string|number} options.algo="scrypt" - Algorithm name or ID
	 * @param {string|number} options.price - Price in BTC/GH/Day or BTC/TH/Day.
	 * @param {string|number} options.order - Order ID/number
	 * @async
	 * @returns {Promise&lt;Object>}
	 */
	async setOrderPrice(options = {}) {
		if (!this.id || !this.key)
			throw new Error('Must provide api key and api id on initialize')
		options = {
			method: "orders.set.price",
			...this.apikey,
			location: options.location || 0,
			algo: checkAlgo(options.algo) || 0,
			order: options.order,
			price: options.price,
		}
		let api = this.api("", options);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result
			}
		} catch (err) {
			throw new Error(`Failed to set order price: ${err}`)
		}
	}

	/**
	 * Decrease price for the existing order. Price decrease possible every 10 minutes
	 * @param options
	 * @param {string|number} options.location=0 - 0 for Europe (NiceHash), 1 for USA (WestHash);
	 * @param {string|number} options.algo="scrypt" - Algorithm name or ID
	 * @param {string|number} options.order - Order ID/number
	 * @async
	 * @returns {Promise&lt;Object>}
	 */
	async decreaseOrderPrice(options = {}) {
		if (!this.id || !this.key)
			throw new Error('Must provide api key and api id on initialize')
		options = {
			method: "orders.set.price.decrease",
			...this.apikey,
			location: options.location || 0,
			algo: checkAlgo(options.algo) || 0,
			order: options.order,
		}
		let api = this.api("", options);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result
			}
		} catch (err) {
			throw new Error(`Failed to decrease order price: ${err}`)
		}
	}

	/**
	 * Set new limit for the existing order.
	 * @param options
	 * @param {string|number} options.location=0 - 0 for Europe (NiceHash), 1 for USA (WestHash);
	 * @param {string|number} options.algo="scrypt" - Algorithm name or ID
	 * @param {string|number} options.amount - Pay amount in BTC;
	 * @param {string|number} options.order - Order ID/number;
	 * @param {string|number} options.limit=0 - Speed limit in GH/s or TH/s (0 for no limit);
	 * @async
	 * @returns {Promise&lt;Object>}
	 */
	async setOrderLimit(options = {}) {
		if (!this.id || !this.key)
			throw new Error('Must provide api key and api id on initialize')
		options = {
			method: "orders.set.limit",
			...this.apikey,
			location: options.location || 0,
			algo: checkAlgo(options.algo) || 0,
			limit: options.limit || 0,
			order: options.order
		}
		let api = this.api("", options);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result
			}
		} catch (err) {
			throw new Error(`Failed to set order limit: ${err}`)
		}
	}

	/**
	 * Get current confirmed Bitcoin balance.
	 * @async
	 * @returns {Promise&lt;Number>}
	 */
	async getBalance() {
		if (!this.id || !this.key)
			throw new Error('Must provide api key and api id on initialize')
		let options = {
			method: "balance",
			...this.apikey
		}
		let api = this.api("", options);
		try {
			let res = (await api.get()).data;
			if (res.result) {
				return res.result.balance_confirmed
			}
		} catch (err) {
			throw new Error(`Failed to get balance: ${err}`)
		}
	}
	//-----------------------------UTIL------------------------------------
	/**
	 * Build initial AxiosInstance with baseURL = "https://api.nicehash.com/api"
	 * @param endpoint
	 * @param {Object} [params]
	 * @returns {AxiosInstance}
	 */
	api(endpoint, params) {
		return axios.create({
			baseURL: `${this.base_url}${endpoint}`,
			headers: {
				'Access-Control-Allow-Origin': '*',
			},
			params
		})
	}
}

const checkAlgo = (algoName) => {
	if (typeof algoName === 'string')
		return convertAlgoToID(algoName)
	return algoName
}
const convertAlgoToID = (algo) => {
	if (typeof algo === 'string') {
		for (let id in algorithms) {
			if (algorithms[id].toLowerCase() === algo.toLowerCase()) {
				return id
			}
		}
	} else if (typeof algo === 'number') {
		if (algorithms[algo])
			return algorithms.algo
	} else return algo
}

export default NiceHash</code></pre>
  </article>
</section>

    


  </div>

  <br class="clear">

  <footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a>
  </footer>

  <script src="scripts/linenumber.js"></script>
  <script src="scripts/pagelocation.js"></script>

  
  
</body>
</html>