diff --git a/.eslintrc.json b/.eslintrc.json index 0c9820d..9483d30 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -6,7 +6,7 @@ }, "parserOptions": { "sourceType": "module", - "ecmaVersion": 9 + "ecmaVersion": 10 }, "rules": { "curly": "error", diff --git a/README.md b/README.md index 47a4a94..f32a4e6 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,8 @@ npm install poloniex-node-api ### PublicClient ```javascript -const Poloniex = require('poloniex-node-api'); -const publicClient = new Poloniex.PublicClient(); +const { PublicClient } = require('poloniex-node-api'); +const publicClient = new PublicClient(); ``` - [`getTickers`](https://docs.poloniex.com/?shell#returnticker) @@ -116,6 +116,8 @@ try { - `cb` ```javascript +const _method = 'getLoanOrders'; +const options = { currency: 'BTC' }; const callback = (error, data) => { if (error) { console.error(error); @@ -123,26 +125,7 @@ const callback = (error, data) => { console.log(data); } }; -publicClient.cb('getLoanOrders', callback, { currency: 'BTC' }); -``` - -- `request` - -```javascript -publicClient - .request({ - method: 'GET', - qs: { - command: 'return24hVolume', - }, - url: 'https://poloniex.com/public', - }) - .then(data => { - console.log(data); - }) - .catch(error => { - console.error(error); - }); +publicClient.cb({ _method, ...options }, callback); ``` ### AuthenticatedClient @@ -150,70 +133,69 @@ publicClient ```javascript const key = 'poloniexapikey'; const secret = 'poloniexapisecret'; -const Poloniex = require('poloniex-node-api'); -const AuthenticatedClient = new Poloniex.AuthenticatedClient({ key, secret }); +const { AuthenticatedClient } = require('poloniex-node-api'); +const authClient = new AuthenticatedClient({ key, secret }); ``` - [`getBalances`](https://docs.poloniex.com/?shell#returnbalances) ```javascript -const balances = await AuthenticatedClient.getBalances(); +const balances = await authClient.getBalances(); ``` - [`getCompleteBalances`](https://docs.poloniex.com/?shell#returncompletebalances) ```javascript const account = 'all'; -const balances = await AuthenticatedClient.getCompleteBalances({ account }); +const balances = await authClient.getCompleteBalances({ account }); ``` - [`getDepositAddresses`](https://docs.poloniex.com/?shell#returndepositaddresses) ```javascript -const addresses = await AuthenticatedClient.getDepositAddresses(); +const addresses = await authClient.getDepositAddresses(); ``` - [`getNewAddress`](https://docs.poloniex.com/?shell#generatenewaddress) ```javascript -const addresses = await AuthenticatedClient.getNewAddress({ currency: 'ZEC' }); +const addresses = await authClient.getNewAddress({ currency: 'ZEC' }); ``` - [`getDepositsWithdrawals`](https://docs.poloniex.com/?shell#returndepositswithdrawals) ```javascript -const deposits_withdrawals = await AuthenticatedClient.getDepositsWithdrawals({ - start: 1539954535, - end: 1540314535, -}); +const start = 1539954535; +const end = 1540314535; +const result = await authClient.getDepositsWithdrawals({ start, end }); ``` - [`getOpenOrders`](https://docs.poloniex.com/?shell#returnopenorders) ```javascript const currencyPair = 'BTC_DASH'; -const orders = await AuthenticatedClient.getOpenOrders({ currencyPair }); +const orders = await authClient.getOpenOrders({ currencyPair }); ``` - [`getHistoryTrades`](https://docs.poloniex.com/?shell#returntradehistory-private) ```javascript const currencyPair = 'BTC_ETC'; -const trades = await AuthenticatedClient.getHistoryTrades({ currencyPair }); +const trades = await authClient.getHistoryTrades({ currencyPair }); ``` - [`getOrderTrades`](https://docs.poloniex.com/?shell#returntradehistory-private) ```javascript const orderNumber = 96238912842; -const trades = await AuthenticatedClient.getOrderTrades({ orderNumber }); +const trades = await authClient.getOrderTrades({ orderNumber }); ``` - [`getOrderStatus`](https://docs.poloniex.com/?shell#returnorderstatus) ```javascript const orderNumber = 96238912842; -const trades = await AuthenticatedClient.getOrderStatus({ orderNumber }); +const trades = await authClient.getOrderStatus({ orderNumber }); ``` - [`buy`](https://docs.poloniex.com/?shell#buy) @@ -222,7 +204,7 @@ const trades = await AuthenticatedClient.getOrderStatus({ orderNumber }); const currencyPair = 'BTC_ETH'; const rate = 0.01; const amount = 1; -const order = await AuthenticatedClient.buy({ currencyPair, rate, amount }); +const order = await authClient.buy({ currencyPair, rate, amount }); ``` - [`sell`](https://docs.poloniex.com/?shell#sell) @@ -231,21 +213,21 @@ const order = await AuthenticatedClient.buy({ currencyPair, rate, amount }); const currencyPair = 'BTC_ETH'; const rate = 10; const amount = 1; -const order = await AuthenticatedClient.sell({ currencyPair, rate, amount }); +const order = await authClient.sell({ currencyPair, rate, amount }); ``` - [`cancelOrder`](https://docs.poloniex.com/?shell#cancelorder) ```javascript const orderNumber = 514845991795; -const order = await AuthenticatedClient.cancelOrder({ orderNumber }); +const order = await authClient.cancelOrder({ orderNumber }); ``` - [`cancelAllOrders`](https://docs.poloniex.com/?shell#cancelallorders) ```javascript const currencyPair = 'BTC_ETH'; -const orders = await AuthenticatedClient.cancelAllOrders({ currencyPair }); +const orders = await authClient.cancelAllOrders({ currencyPair }); ``` - [`moveOrder`](https://docs.poloniex.com/?shell#moveorder) @@ -253,7 +235,7 @@ const orders = await AuthenticatedClient.cancelAllOrders({ currencyPair }); ```javascript const orderNumber = 514851026755; const rate = 0.00015; -const result = await AuthenticatedClient.moveOrder({ rate, orderNumber }); +const result = await authClient.moveOrder({ rate, orderNumber }); ``` - [`withdraw`](https://docs.poloniex.com/?shell#withdraw) @@ -263,7 +245,7 @@ const currency = 'EOS'; const amount = 1000; const address = 'eos-address'; const paymentId = 1234567890; -const result = await AuthenticatedClient.withdraw({ +const result = await authClient.withdraw({ currency, amount, address, @@ -274,7 +256,7 @@ const result = await AuthenticatedClient.withdraw({ - [`getFeeInfo`](https://docs.poloniex.com/?shell#returnfeeinfo) ```javascript -const fees = await AuthenticatedClient.getFeeInfo(); +const fees = await authClient.getFeeInfo(); ``` - [`getAvailableAccountBalances`](https://docs.poloniex.com/?shell#returnavailableaccountbalances) @@ -307,7 +289,7 @@ const transfer = AuthenticatedClient.transferBalance({ - [`getMarginAccountSummary`](https://docs.poloniex.com/?shell#returnmarginaccountsummary) ```javascript -const summary = await AuthenticatedClient.getMarginAccountSummary(); +const summary = await authClient.getMarginAccountSummary(); ``` - [`marginBuy`](https://docs.poloniex.com/?shell#marginbuy) @@ -317,7 +299,7 @@ const currencyPair = 'BTC_ETH'; const rate = 0.01; const amount = 1; const lendingRate = 0.01; -const order = await AuthenticatedClient.marginBuy({ +const order = await authClient.marginBuy({ currencyPair, rate, amount, @@ -332,7 +314,7 @@ const currencyPair = 'BTC_ETH'; const rate = 10; const amount = 1; const lendingRate = 0.015; -const order = await AuthenticatedClient.marginSell({ +const order = await authClient.marginSell({ currencyPair, rate, amount, @@ -344,16 +326,14 @@ const order = await AuthenticatedClient.marginSell({ ```javascript const currencyPair = 'BTC_ETH'; -const position = await AuthenticatedClient.getMarginPosition({ currencyPair }); +const position = await authClient.getMarginPosition({ currencyPair }); ``` - [`closeMarginPosition`](https://docs.poloniex.com/?shell#closemarginposition) ```javascript const currencyPair = 'BTC_ETH'; -const position = await AuthenticatedClient.closeMarginPosition({ - currencyPair, -}); +const position = await authClient.closeMarginPosition({ currencyPair }); ``` - [`createLoanOffer`](https://docs.poloniex.com/?shell#createloanoffer) @@ -364,7 +344,7 @@ const amount = 0.1; const duration = 2; const autoRenew = 0; const lendingRate = 0.015; -const offer = await AuthenticatedClient.createLoanOffer({ +const offer = await authClient.createLoanOffer({ currency, amount, duration, @@ -377,19 +357,19 @@ const offer = await AuthenticatedClient.createLoanOffer({ ```javascript const orderNumber = 1002013188; -const offer = await AuthenticatedClient.cancelLoanOffer({ orderNumber }); +const offer = await authClient.cancelLoanOffer({ orderNumber }); ``` - [`getOpenLoanOffers`](https://docs.poloniex.com/?shell#returnopenloanoffers) ```javascript -const offers = await AuthenticatedClient.getOpenLoanOffers(); +const offers = await authClient.getOpenLoanOffers(); ``` - [`getActiveLoans`](https://docs.poloniex.com/#returnactiveloans) ```javascript -const loans = await AuthenticatedClient.getActiveLoans(); +const loans = await authClient.getActiveLoans(); ``` - [`getLendingHistory`](https://docs.poloniex.com/#returnlendinghistory) @@ -398,24 +378,14 @@ const loans = await AuthenticatedClient.getActiveLoans(); const start = 1483228800; const end = 1483315200; const limits = 100; -const history = await AuthenticatedClient.getLendingHistory({ - start, - end, - limits, -}); +const history = await authClient.getLendingHistory({ start, end, limits }); ``` - [`toggleAutoRenew`](https://docs.poloniex.com/#toggleautorenew) ```javascript const orderNumber = 1002013188; -const result = await AuthenticatedClient.toggleAutoRenew({ orderNumber }); -``` - -- `post` - -```javascript -AuthenticatedClient.post({ command: 'returnCompleteBalances' }); +const result = await authClient.toggleAutoRenew({ orderNumber }); ``` ### WebsocketClient @@ -424,8 +394,8 @@ AuthenticatedClient.post({ command: 'returnCompleteBalances' }); const key = 'poloniexapikey'; const secret = 'poloniexapisecret'; const channels = [1000, 'BTC_DOGE']; -const Poloniex = require('poloniex-node-api'); -const websocket = new Poloniex.WebsocketClient({ key, secret, channels }); +const { WebsocketClient } = require('poloniex-node-api'); +const websocket = new WebsocketClient({ key, secret, channels }); websocket.on('open', () => { console.log('open'); }); @@ -464,16 +434,6 @@ websocket.subscribe(1003); websocket.unsubscribe('BTC_ZEC'); ``` -### SignRequest - -```javascript -const Poloniex = require('poloniex-node-api'); -const auth = { key: 'apikey', secret: 'apisecret' }; -const data = { form: { command: 'returnBalances', nonce: 154264078495300 } }; -const { key, sign } = Poloniex.SignRequest(auth, data); -console.log(sign); -``` - ### Test ```bash diff --git a/index.d.ts b/index.d.ts index e8ae0e3..8120932 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,6 +1,6 @@ import { EventEmitter } from 'events'; -declare module 'poloniex' { +declare module 'poloniex-node-api' { export type callback = (error: any, data: T) => void; export type TickerInfo = { @@ -109,6 +109,10 @@ declare module 'poloniex' { } & getOptions; }; + export type CBOptions = { + _method: string; + }; + export type CurrencyPairFilter = { currencyPair?: string; }; @@ -599,7 +603,7 @@ declare module 'poloniex' { request(options: requestOptions): Promise; - cb(method: string, callback: callback, options?: any); + cb(options: CBOptions, callback: callback); getTickers(): Promise; @@ -616,7 +620,7 @@ declare module 'poloniex' { getLoanOrders(options: CurrencyFilter): Promise; } - export class AuthenticatedClient { + export class AuthenticatedClient extends PublicClient { constructor(options: AuthenticatedClientOptions); post(options: getOptions): Promise; diff --git a/index.js b/index.js index a19fccf..c3e4622 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,5 @@ module.exports = { AuthenticatedClient: require('./lib/authenticated.js'), PublicClient: require('./lib/public.js'), - SignRequest: require('./lib/signer.js'), WebsocketClient: require('./lib/websocket.js'), }; diff --git a/lib/authenticated.js b/lib/authenticated.js index 818fc1c..dd45116 100644 --- a/lib/authenticated.js +++ b/lib/authenticated.js @@ -11,8 +11,8 @@ class AuthenticatedClient extends PublicClient { * @param {string} [options.currencyPair] - If `currencyPair` is provided then it will be used in all future requests that require `currencyPair` but it is omitted (not applied to requests where `currencyPair` is optional). * @throws Will throw an error if incomplete authentication credentials are provided. * @example - * const Poloniex = require('poloniex-node-api'); - * const AuthenticatedClient = new Poloniex.AuthenticatedClient({ + * const { AuthenticatedClient } = require('poloniex-node-api'); + * const authClient = new AuthenticatedClient({ * key: 'my-api-key', * secret: 'my-api-secret', * }); @@ -30,7 +30,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} options * @param {string} options.command * @example - * AuthenticatedClient.post({ + * authClient.post({ * command: 'generateNewAddress', * currency: 'ETH', * }) @@ -42,23 +42,21 @@ class AuthenticatedClient extends PublicClient { * }); * @description Make `POST` request. */ - post(options) { - const { command } = options; + post({ ...form } = {}) { + const { command } = form; this._requireProperties(command); + form.nonce = this._nonce(); const auth = { key: this.key, secret: this.secret }; - const reqOptions = { form: this._removeUndefined(options), method: 'POST' }; - reqOptions.timeout = this.timeout; - reqOptions.form.nonce = this._nonce(); + const reqOptions = { form, method: 'POST', timeout: this.timeout }; reqOptions.url = this.api_uri + '/tradingApi'; reqOptions.headers = SignRequest(auth, reqOptions); - return this.request(reqOptions); } /** * @example - * const balances = AuthenticatedClient.getBalances(); + * const balances = authClient.getBalances(); * @see {@link https://docs.poloniex.com/?shell#returnbalances|returnBalances} * @description Get all of your balances available for trade after having deducted all open orders. */ @@ -70,7 +68,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} [options] * @param {string} [options.account] - Set the `account` parameter to "all" to include your margin and lending accounts. * @example - * const balances = AuthenticatedClient.getCompleteBalances({ account: 'all' }); + * const balances = authClient.getCompleteBalances({ account: 'all' }); * @see {@link https://docs.poloniex.com/?shell#returncompletebalances|returnCompleteBalances} * @description Get all of your balances, including available balance, balance on orders, and the estimated BTC value of your balance. */ @@ -80,7 +78,7 @@ class AuthenticatedClient extends PublicClient { /** * @example - * const addresses = AuthenticatedClient.getDepositAddresses(); + * const addresses = authClient.getDepositAddresses(); * @see {@link https://docs.poloniex.com/?shell#returndepositaddresses|returnDepositAddresses} * @description Get all of your deposit addresses. */ @@ -92,7 +90,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} options * @param {string} options.currency - The currency to use for the deposit address. * @example - * const addresses = AuthenticatedClient.getNewAddress({ currency: 'BTC' }); + * const addresses = authClient.getNewAddress({ currency: 'BTC' }); * @see {@link https://docs.poloniex.com/?shell#generatenewaddress|generateNewAddress} * @description Generate a new deposit address. */ @@ -107,7 +105,7 @@ class AuthenticatedClient extends PublicClient { * @param {number} options.start - The start date of the range window in UNIX timestamp format. * @param {number} options.end - The end date of the range window in UNIX timestamp format. * @example - * const deposits = AuthenticatedClient.getDepositsWithdrawals({ + * const deposits = authClient.getDepositsWithdrawals({ * start: 1539952118, * end: 1540318271, * }); @@ -124,7 +122,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} [options] * @param {string} [options.currencyPair='all'] - The major and minor currency that define this market. * @example - * const orders = AuthenticatedClient.getOpenOrders(); + * const orders = authClient.getOpenOrders(); * @description Get your open orders for a given market. * @see {@link https://docs.poloniex.com/?shell#returnopenorders|returnOpenOrders} */ @@ -139,7 +137,7 @@ class AuthenticatedClient extends PublicClient { * @param {number} [options.end] - The end date of the range window in UNIX timestamp format. * @param {number} [options.limit] - You may optionally limit the number of entries returned using the "limit" parameter, up to a maximum of 10,000. If the "limit" parameter is not specified, no more than 500 entries will be returned. * @example - * const trades = AuthenticatedClient.getHistoryTrades(); + * const trades = authClient.getHistoryTrades(); * @description Get your trade history for a given market. * @see {@link https://docs.poloniex.com/?shell#returntradehistory-private|returnTradeHistory} */ @@ -157,7 +155,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} options * @param {number} options.orderNumber - The order number whose trades you wish to query. * @example - * const trades = AuthenticatedClient.getOrderTrades({ orderNumber: 96238912841 }); + * const trades = authClient.getOrderTrades({ orderNumber: 96238912841 }); * @description Get all trades involving a given order. * @see {@link https://docs.poloniex.com/?shell#returntradehistory-private|returnOrderTrades} */ @@ -171,7 +169,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} options * @param {string} options.orderNumber - The identifier of the order to return. * @example - * const trades = AuthenticatedClient.getOrderStatus({ orderNumber: 9623891284 }); + * const trades = authClient.getOrderStatus({ orderNumber: 9623891284 }); * @description Get the status of a given order. * @see {@link https://docs.poloniex.com/?shell#returnorderstatus|returnOrderStatus} */ @@ -193,7 +191,7 @@ class AuthenticatedClient extends PublicClient { * const currencyPair = 'BTC_ETH'; * const rate = 0.01; * const amount = 1; - * const order = AuthenticatedClient.buy({ currencyPair, rate, amount }); + * const order = authClient.buy({ currencyPair, rate, amount }); * @description Places a limit buy order. * @see {@link https://docs.poloniex.com/?shell#buy|buy} */ @@ -230,7 +228,7 @@ class AuthenticatedClient extends PublicClient { * const currencyPair = 'BTC_ETH'; * const rate = 0.01; * const amount = 1; - * const order = AuthenticatedClient.sell({ currencyPair, rate, amount }); + * const order = authClient.sell({ currencyPair, rate, amount }); * @description Places a limit sell order. * @see {@link https://docs.poloniex.com/?shell#sell|sell} */ @@ -259,7 +257,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} options * @param {string} options.orderNumber - The identity number of the order to be canceled. * @example - * const order = AuthenticatedClient.cancelOrder({ orderNumber: 514845991795 }); + * const order = authClient.cancelOrder({ orderNumber: 514845991795 }); * @description Cancel an order you have placed in a given market. * @see {@link https://docs.poloniex.com/?shell#cancelorder|cancelOrder} */ @@ -273,7 +271,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} [options] * @param {string} [options.currencyPair] - The base and quote currency that define a market. * @example - * const order = AuthenticatedClient.cancelAllOrders({ currencyPair: 'BTC_ETH' }); + * const order = authClient.cancelAllOrders({ currencyPair: 'BTC_ETH' }); * @description Cancel all open orders in a given market or, if no market is provided, all open orders in all markets. * @see {@link https://docs.poloniex.com/?shell#cancelallorders|cancelAllOrders} */ @@ -289,7 +287,7 @@ class AuthenticatedClient extends PublicClient { * @param {number} [options.postOnly] - Set to `1` if you want this buy order to only be placed if no portion of it fills immediately. * @param {number} [options.immediateOrCancel] - Set to `1` if this order can be partially or completely filled, but any portion of the order that cannot be filled immediately will be canceled. * @example - * const order = AuthenticatedClient.moveOrder({ + * const order = authClient.moveOrder({ * orderNumber: 514851026755, * rate: 0.00015, * }); @@ -317,7 +315,7 @@ class AuthenticatedClient extends PublicClient { * @param {string|number} [options.paymentId] - For withdrawals which support payment IDs. * @param {string} [options.currencyToWithdrawAs] - Set to `USDTTRON` and set `currency` to `USDT` to withdraw `USDT-TRON`. * @example - * const withdraw = AuthenticatedClient.withdraw({ + * const withdraw = authClient.withdraw({ * currency: 'ETH', * amount: 2, * address: '0x84a90e21d9d02e30ddcea56d618aa75ba90331ff', @@ -346,7 +344,7 @@ class AuthenticatedClient extends PublicClient { /** * @example - * const fees = AuthenticatedClient.getFeeInfo(); + * const fees = authClient.getFeeInfo(); * @see {@link https://docs.poloniex.com/?shell#returnfeeinfo|returnFeeInfo} * @description Get your current trading fees and trailing 30-day volume in BTC. */ @@ -358,7 +356,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} [options] * @param {string} [options.account] - `exchange`, `margin` or `lending`. * @example - * const balances = AuthenticatedClient.getAvailableAccountBalances({ + * const balances = authClient.getAvailableAccountBalances({ * account: 'exchange', * }); * @see {@link https://docs.poloniex.com/?shell#returnavailableaccountbalances|returnAvailableAccountBalances} @@ -370,7 +368,7 @@ class AuthenticatedClient extends PublicClient { /** * @example - * const balances = AuthenticatedClient.getTradableBalances(); + * const balances = authClient.getTradableBalances(); * @see {@link https://docs.poloniex.com/?shell#returntradablebalances|returnTradableBalances} * @description Get your current tradable balances for each currency in each market for which margin trading is enabled. */ @@ -385,7 +383,7 @@ class AuthenticatedClient extends PublicClient { * @param {string} options.fromAccount - The account from which this value should be moved. * @param {string} options.toAccount - The account to which this value should be moved. * @example - * const transfer = AuthenticatedClient.transferBalance({ + * const transfer = authClient.transferBalance({ * currency: 'ETH', * amount: 10, * fromAccount: 'lending', @@ -408,7 +406,7 @@ class AuthenticatedClient extends PublicClient { /** * @example - * const summary = AuthenticatedClient.getMarginAccountSummary(); + * const summary = authClient.getMarginAccountSummary(); * @see {@link https://docs.poloniex.com/?shell#returnmarginaccountsummary|returnMarginAccountSummary} * @description Get a summary of your entire margin account. */ @@ -426,7 +424,7 @@ class AuthenticatedClient extends PublicClient { * const currencyPair = 'BTC_ETH'; * const rate = 0.01; * const amount = 1; - * const order = AuthenticatedClient.marginBuy({ currencyPair, rate, amount }); + * const order = authClient.marginBuy({ currencyPair, rate, amount }); * @description Place a margin buy order in a given market. * @see {@link https://docs.poloniex.com/?shell#marginbuy|marginBuy} */ @@ -457,7 +455,7 @@ class AuthenticatedClient extends PublicClient { * const currencyPair = 'BTC_ETH'; * const rate = 0.001; * const amount = 2; - * const order = AuthenticatedClient.marginSell({ currencyPair, rate, amount }); + * const order = authClient.marginSell({ currencyPair, rate, amount }); * @description Place a margin sell order in a given market. * @see {@link https://docs.poloniex.com/?shell#marginsell|marginSell} */ @@ -482,7 +480,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} [options] * @param {string} [options.currencyPair='all'] - The major and minor currency that define this market. * @example - * const position = AuthenticatedClient.getMarginPosition(); + * const position = authClient.getMarginPosition(); * @description Get information about your margin position in a given market. * @see {@link https://docs.poloniex.com/?shell#getmarginposition|getMarginPosition} */ @@ -495,7 +493,7 @@ class AuthenticatedClient extends PublicClient { * @param {string} [options.currencyPair] - The major and minor currency that define this market. * @example * const currencyPair = 'BTC_ETH'; - * const position = AuthenticatedClient.closeMarginPosition({ currencyPair }); + * const position = authClient.closeMarginPosition({ currencyPair }); * @description Close your margin position in a given market using a market order. * @see {@link https://docs.poloniex.com/?shell#closemarginposition|closeMarginPosition} */ @@ -516,7 +514,7 @@ class AuthenticatedClient extends PublicClient { * const duration = 2; * const autoRenew = 0; * const lendingRate = 0.015; - * const offer = await AuthenticatedClient.createLoanOffer({ + * const offer = await authClient.createLoanOffer({ * currency, * amount, * duration, @@ -544,7 +542,7 @@ class AuthenticatedClient extends PublicClient { * @param {string} options.orderNumber - The identification number of the offer to be canceled. * @example * const orderNumber = 1002013188; - * const offer = await AuthenticatedClient.cancelLoanOffer({ orderNumber }); + * const offer = await authClient.cancelLoanOffer({ orderNumber }); * @description Cancel a loan offer. * @see {@link https://docs.poloniex.com/?shell#cancelloanoffer|cancelLoanOffer} */ @@ -556,7 +554,7 @@ class AuthenticatedClient extends PublicClient { /** * @example - * const offers = AuthenticatedClient.getOpenLoanOffers(); + * const offers = authClient.getOpenLoanOffers(); * @see {@link https://docs.poloniex.com/?shell#returnopenloanoffers|returnOpenLoanOffers} * @description Get your open loan offers for each currency. */ @@ -566,7 +564,7 @@ class AuthenticatedClient extends PublicClient { /** * @example - * const loans = await AuthenticatedClient.getActiveLoans(); + * const loans = await authClient.getActiveLoans(); * @description Get your active loans for each currency. * @see {@link https://docs.poloniex.com/#returnactiveloans|returnActiveLoans} */ @@ -580,7 +578,7 @@ class AuthenticatedClient extends PublicClient { * @param {number} [options.end] - The date in Unix timestamp format of the end of the window. * @param {number} [options.limit] - `limit` may also be specified to limit the number of rows returned. * @example - * const history = await AuthenticatedClient.getLendingHistory(); + * const history = await authClient.getLendingHistory(); * @description Get your lending history. * @see {@link https://docs.poloniex.com/#returnlendinghistory|returnLendingHistory} */ @@ -592,7 +590,7 @@ class AuthenticatedClient extends PublicClient { * @param {Object} options * @param {number} options.orderNumber - The identifier of the order you want to toggle. * @example - * const result = AuthenticatedClient.toggleAutoRenew({ orderNumber: 1002013188 }); + * const result = authClient.toggleAutoRenew({ orderNumber: 1002013188 }); * @description Toggle the autoRenew setting on an active loan * @see {@link https://docs.poloniex.com/#toggleautorenew|toggleAutoRenew} */ @@ -605,14 +603,14 @@ class AuthenticatedClient extends PublicClient { /** * @private * @example - * const nonce = AuthenticatedClient._nonce(); + * const nonce = authClient._nonce(); * @description Get new nonce. */ _nonce() { if (typeof this.nonce === 'function') { return this.nonce(); } - return !this.nonce ? (this.nonce = Date.now()) : ++this.nonce; + return (this.nonce = Date.now()); } } diff --git a/lib/public.js b/lib/public.js index 66432d7..33b3287 100644 --- a/lib/public.js +++ b/lib/public.js @@ -1,4 +1,4 @@ -const request = require('request-promise'); +const request = require('request-promise-native'); const { EXCHANGE_API_URL, DEFAULT_TIMEOUT, @@ -7,6 +7,12 @@ const { HEADERS, } = require('./utilities'); +/** + * @callback Callback + * @param error + * @param data + */ + class PublicClient { /** * @param {Object} [options={}] @@ -14,8 +20,9 @@ class PublicClient { * @param {string} [options.api_uri] - Overrides the default apiuri, if provided. * @param {number} [options.timeout] - Overrides the default timeout, if provided. * @example - * const Poloniex = require('poloniex-node-api'); - * const publicClient = new Poloniex.PublicClient({ currencyPair: 'BTC_ETH' }); + * const { PublicClient } = require('poloniex-node-api'); + * const currencyPair = 'BTC_DASH'; + * const publicClient = new PublicClient({ currencyPair }); * @description Create PublicClient. */ constructor({ currencyPair, api_uri, timeout } = {}) { @@ -40,19 +47,19 @@ class PublicClient { * @throws Will throw an error if `options.command` is undefined. * @description Make `GET` request. */ - get(options) { - const { command } = options; + get({ ...qs } = {}) { + const { command } = qs; this._requireProperties(command); - const reqOptions = { qs: this._removeUndefined(options), method: 'GET' }; - reqOptions.timeout = this.timeout; + const reqOptions = { qs, method: 'GET', timeout: this.timeout }; reqOptions.url = this.api_uri + '/public'; return this.request(reqOptions); } /** - * @param {Object} [options] + * @private + * @param {Object} options * @example * publicClient * .request({ @@ -85,16 +92,30 @@ class PublicClient { resolve(data); } }) - .catch(error => reject(error)); + .catch(error => reject(error.error || error)); }); } - cb(method, callback, options) { + /** + * @param {Object} options + * @param {string} options._method - Class method to call. + * @param {...*} [options.methodOptions] + * @param {Callback} callback + * @example + * publicClient.cb( + * { _method: 'getLoanOrders', currency: 'BTC' }, + * (error, data) => { + * if (error) { + * console.error(error); + * } else { + * console.log(data); + * } + * } + * ); + */ + cb({ _method, ...options } = {}, callback) { try { - this[method] - .call(this, options) - .then(data => callback(null, data)) - .catch(error => callback(error)); + this[_method].call(this, options).then(data => callback(null, data)); } catch (error) { callback(error); } @@ -121,14 +142,11 @@ class PublicClient { } /** - * @param {Object} [options] + * @param {Object} [options={}] * @param {string} [options.currencyPair='all'] - A pair like `BTC_ETH` or `all`. * @param {number} [options.depth] - Max depth is `100`. * @example - * const book = await publicClient.getOrderBook({ - * depth: 25, - * currencyPair: 'USDT_ZEC', - * }); + * const books = await publicClient.getOrderBook(); * @see {@link https://docs.poloniex.com/?shell#returnorderbook|returnOrderBook} * @description Get the order book for a given market. */ @@ -137,16 +155,12 @@ class PublicClient { } /** - * @param {Object} [options] + * @param {Object} [options={}] * @param {string} [options.currencyPair] - If `currencyPair` is not provided then the default currencyPair will be used. * @param {number} [options.start] - UNIX timestamp. * @param {number} [options.end] - UNIX timestamp. * @example - * const history = await publicClient.getTradeHistory({ - * currencyPair: 'USDT_ZEC', - * start: 1410158328, - * end: 1410488343, - * }); + * const history = await publicClient.getTradeHistory(); * @see {@link https://docs.poloniex.com/?shell#returntradehistory-public|returnTradeHistory} * @description Get the past 200 trades for a given market, or up to 1,000 trades between a range `start` and `end`. */ @@ -160,7 +174,7 @@ class PublicClient { } /** - * @param {Object} options + * @param {Object} options={} * @param {string} [options.currencyPair] - If `currencyPair` is not provided then the default currencyPair will be used. * @param {number} options.period - Candlestick period in seconds. Valid values are 300, 900, 1800, 7200, 14400, and 86400. * @param {number} options.start - UNIX timestamp. @@ -201,7 +215,7 @@ class PublicClient { * @param {Object} options * @param {string} options.currency * @example - * const loans = publicClient.getLoanOrders({ currency: 'BTC' }); + * const loans = await publicClient.getLoanOrders({ currency: 'BTC' }); * @see {@link https://docs.poloniex.com/?shell#returnloanorders|returnLoanOrders} * @description Get the list of loan offers and demands for a given currency. */ @@ -226,16 +240,6 @@ class PublicClient { } } } - - _removeUndefined(object) { - let newObject = object; - for (let key of Object.keys(object)) { - if (object[key] === undefined) { - delete newObject[key]; - } - } - return newObject; - } } module.exports = PublicClient; diff --git a/lib/signer.js b/lib/signer.js index 161ccda..75dfb14 100644 --- a/lib/signer.js +++ b/lib/signer.js @@ -2,31 +2,26 @@ const crypto = require('crypto'); const querystring = require('querystring'); /** + * @private * @description SignRequest. * @param {Object} auth * @param {string} auth.key - The API key. * @param {string} auth.secret - The API secret. - * @param {Object} [options={}] - Data to sign. + * @param {Object} options + * @param {Object} options.form - The form to sign. * @example - * const signature = Poloniex.SignRequest( - * { key: 'my-api-key', secret: 'my-api-secret' }, - * { form: { command: 'returnBalances', nonce: 154264078495300 } } - * ); + * const auth = { key: 'my-api-key', secret: 'my-api-secret' }; + * const data = { form: { command: 'returnBalances', nonce: 154264078495300 } }; + * const signature = SignRequest(auth, data); * @returns {Object} The object containg the key and the signature. */ -const SignRequest = (auth, options = {}) => { - let form = ''; - if (options.qs && Object.keys(options.qs).length) { - form = '?' + querystring.stringify(options.qs); - } else if (options.form) { - form = querystring.stringify(options.form); - } - +const SignRequest = (auth, options) => { + const data = querystring.stringify(options.form); return { key: auth.key, sign: crypto .createHmac('sha512', auth.secret) - .update(form) + .update(data) .digest('hex'), }; }; diff --git a/lib/websocket.js b/lib/websocket.js index ea5fdf2..570c950 100644 --- a/lib/websocket.js +++ b/lib/websocket.js @@ -298,7 +298,7 @@ class WebsocketClient extends EventEmitter { if (typeof this.nonce === 'function') { return this.nonce(); } - return !this.nonce ? (this.nonce = Date.now()) : ++this.nonce; + return (this.nonce = Date.now()); } } diff --git a/package-lock.json b/package-lock.json index afda963..2a949e2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,22 +1,22 @@ { "name": "poloniex-node-api", - "version": "0.3.6", + "version": "0.4.0", "lockfileVersion": 1, "requires": true, "dependencies": { "@babel/code-frame": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", - "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.5.5.tgz", + "integrity": "sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==", "dev": true, "requires": { "@babel/highlight": "^7.0.0" } }, "@babel/highlight": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", - "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.5.0.tgz", + "integrity": "sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ==", "dev": true, "requires": { "chalk": "^2.0.0", @@ -31,9 +31,9 @@ "dev": true }, "acorn": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz", - "integrity": "sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.2.1.tgz", + "integrity": "sha512-JD0xT5FCRDNyjDda3Lrg/IxFscp9q4tiYtxE1/nOzlKCk7hIRuYjhq1kCNkbPjMRMZuFq20HNQn1I9k8Oj0E+Q==", "dev": true }, "acorn-jsx": { @@ -43,9 +43,9 @@ "dev": true }, "ajv": { - "version": "6.10.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.0.tgz", - "integrity": "sha512-nffhOpkymDECQyR0mnsUtoCE8RlX38G0rYP+wgLWFyZuUyuuojSSvi/+euOiQBIn63whYwYVIIH1TvE3tu4OEg==", + "version": "6.10.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.2.tgz", + "integrity": "sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw==", "requires": { "fast-deep-equal": "^2.0.1", "fast-json-stable-stringify": "^2.0.0", @@ -151,7 +151,8 @@ "bluebird": { "version": "3.5.5", "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.5.tgz", - "integrity": "sha512-5am6HnnfN+urzt4yfg7IgTbotDjIT/u8AJpEt0sIU9FtXfVeezXAPKswrG+xKUCOYAINpSdgZVDU6QFh+cuH3w==" + "integrity": "sha512-5am6HnnfN+urzt4yfg7IgTbotDjIT/u8AJpEt0sIU9FtXfVeezXAPKswrG+xKUCOYAINpSdgZVDU6QFh+cuH3w==", + "dev": true }, "brace-expansion": { "version": "1.1.11", @@ -193,14 +194,6 @@ "dev": true, "requires": { "lodash": "^4.17.14" - }, - "dependencies": { - "lodash": { - "version": "4.17.15", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", - "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", - "dev": true - } } }, "chai": { @@ -508,10 +501,13 @@ } }, "eslint-utils": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.3.1.tgz", - "integrity": "sha512-Z7YjnIldX+2XMcjr7ZkgEsOj/bREONV60qYeB/bjMAqqqZ4zxKyWX+BOUkdmRmA9riiIPVvo5x86m5elviOk0Q==", - "dev": true + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.0.tgz", + "integrity": "sha512-7ehnzPaP5IIEh1r1tkjuIrxqhNkzUJa9z3R92tLJdZIVdWaczEhr3EbhGtsMrVxi1KeR8qA7Off6SWc5WNQqyQ==", + "dev": true, + "requires": { + "eslint-visitor-keys": "^1.0.0" + } }, "eslint-visitor-keys": { "version": "1.0.0", @@ -587,9 +583,9 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" }, "external-editor": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.0.3.tgz", - "integrity": "sha512-bn71H9+qWoOQKyZDo25mOMVpSmXROAsTJVVVYzrrtol3d4y+AsKjf4Iwl2Q+IuT0kFSQ1qo166UuIwqYq7mGnA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", "dev": true, "requires": { "chardet": "^0.7.0", @@ -885,9 +881,9 @@ "dev": true }, "inquirer": { - "version": "6.4.1", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.4.1.tgz", - "integrity": "sha512-/Jw+qPZx4EDYsaT6uz7F4GJRNFMRdKNeUZw3ZnKV8lyuUgz/YWRCSUAJMZSVhSq4Ec0R2oYnyi6b3d4JXcL5Nw==", + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.5.0.tgz", + "integrity": "sha512-scfHejeG/lVZSpvCXpsB4j/wQNPM5JC8kiElOI0OUTwmc1RTpXr4H32/HOlQHcZiYl2z2VElwuCVDRG8vFmbnA==", "dev": true, "requires": { "ansi-escapes": "^3.2.0", @@ -896,7 +892,7 @@ "cli-width": "^2.0.0", "external-editor": "^3.0.3", "figures": "^2.0.0", - "lodash": "^4.17.11", + "lodash": "^4.17.12", "mute-stream": "0.0.7", "run-async": "^2.2.0", "rxjs": "^6.4.0", @@ -1661,17 +1657,6 @@ "uuid": "^3.3.2" } }, - "request-promise": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/request-promise/-/request-promise-4.2.4.tgz", - "integrity": "sha512-8wgMrvE546PzbR5WbYxUQogUnUDfM0S7QIFZMID+J73vdFARkFy+HElj4T+MWYhpXwlLp0EQ8Zoj8xUA0he4Vg==", - "requires": { - "bluebird": "^3.5.0", - "request-promise-core": "1.1.2", - "stealthy-require": "^1.1.1", - "tough-cookie": "^2.3.3" - } - }, "request-promise-core": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.2.tgz", @@ -1680,6 +1665,16 @@ "lodash": "^4.17.11" } }, + "request-promise-native": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.7.tgz", + "integrity": "sha512-rIMnbBdgNViL37nZ1b3L/VfPOpSi0TqVDQPAvO6U14lMzOLrt5nilxCQqtDKhZeDiW0/hkCXGoQjhgJd/tCh6w==", + "requires": { + "request-promise-core": "1.1.2", + "stealthy-require": "^1.1.1", + "tough-cookie": "^2.3.3" + } + }, "require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -1699,14 +1694,6 @@ "dev": true, "requires": { "lodash": "^4.17.14" - }, - "dependencies": { - "lodash": { - "version": "4.17.15", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", - "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", - "dev": true - } } }, "resolve-from": { @@ -1874,13 +1861,13 @@ } }, "table": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/table/-/table-5.4.1.tgz", - "integrity": "sha512-E6CK1/pZe2N75rGZQotFOdmzWQ1AILtgYbMAbAjvms0S1l5IDB47zG3nCnFGB/w+7nB3vKofbLXCH7HPBo864w==", + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.4.tgz", + "integrity": "sha512-IIfEAUx5QlODLblLrGTTLJA7Tk0iLSGBvgY8essPRVNGHAzThujww1YqHLs6h3HfTg55h++RzLHH5Xw/rfv+mg==", "dev": true, "requires": { - "ajv": "^6.9.1", - "lodash": "^4.17.11", + "ajv": "^6.10.2", + "lodash": "^4.17.14", "slice-ansi": "^2.1.0", "string-width": "^3.0.0" }, diff --git a/package.json b/package.json index 7aeb105..80d3636 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "poloniex-node-api", - "version": "0.3.6", + "version": "0.4.0", "description": "Poloniex Node.js API", "main": "index.js", "directories": { @@ -36,7 +36,7 @@ "homepage": "https://github.com/vansergen/poloniex-node-api#readme", "dependencies": { "request": "^2.88.0", - "request-promise": "^4.2.4", + "request-promise-native": "^1.0.7", "ws": "^7.1.1" }, "devDependencies": { diff --git a/tests/public.spec.js b/tests/public.spec.js index ec41351..d5c1262 100644 --- a/tests/public.spec.js +++ b/tests/public.spec.js @@ -35,9 +35,7 @@ suite('PublicClient', () => { .request({ method: 'GET', url: EXCHANGE_API_URL + '/public' }) .then(() => assert.fail('Should have thrown an error')) .catch(error => { - assert.deepEqual(error.message, '400 - {"error":"some error"}'); - assert.deepEqual(error.statusCode, 400); - assert.deepEqual(error.error, data); + assert.deepEqual(error, data); done(); }); }); @@ -45,6 +43,7 @@ suite('PublicClient', () => { test('.cb()', () => { const response = { response: 1 }; const options = { method: 'GET', url: EXCHANGE_API_URL + '/public' }; + const _method = 'request'; nock(EXCHANGE_API_URL) .get('/public') .times(2) @@ -59,7 +58,7 @@ suite('PublicClient', () => { resolve(data); } }; - publicClient.cb('request', callback, options); + publicClient.cb({ _method, ...options }, callback); }); const preq = publicClient diff --git a/tests/signer.spec.js b/tests/signer.spec.js index 6726f69..b8b7d9b 100644 --- a/tests/signer.spec.js +++ b/tests/signer.spec.js @@ -1,8 +1,6 @@ const assert = require('assert'); -const Poloniex = require('../index.js'); - -const signer = Poloniex.SignRequest; +const signer = require('../lib/signer.js'); suite('SignRequest', () => { test('correct signature', () => {