Skip to content
This repository was archived by the owner on Oct 30, 2023. It is now read-only.

Commit 73f5656

Browse files
author
Jon Eyrick
authored
Many improvements
2 parents 9dea9e7 + e9c60ef commit 73f5656

5 files changed

Lines changed: 147 additions & 14 deletions

File tree

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,12 @@ binance.prices((error, ticker) => {
125125
#### Getting list of current balances
126126
```javascript
127127
binance.balance((error, balances) => {
128+
if ( error ) return console.error(error);
128129
console.log("balances()", balances);
129130
console.log("ETH balance: ", balances.ETH.available);
130131
});
132+
// If you have problems with this function,
133+
// see Troubleshooting at the bottom of this page.
131134
```
132135
<details>
133136
<summary>View Response</summary>
@@ -1637,6 +1640,17 @@ binance.options({
16371640
});
16381641
```
16391642

1643+
Problems getting your balance? Wrap the entry point of your application in useServerTime:
1644+
```js
1645+
binance.useServerTime(function() {
1646+
binance.balance((error, balances) => {
1647+
if ( error ) return console.error(error);
1648+
console.log("balances()", balances);
1649+
console.log("BNB balance: ", balances.BNB.available);
1650+
});
1651+
});
1652+
```
1653+
16401654
[![Views](http://hits.dwyl.io/jaggedsoft/node-binance-api.svg)](http://hits.dwyl.io/jaggedsoft/node-binance-api)
16411655

16421656
Thank you to all contributors: dmzoneill, dmitriz, keith1024, usama33, yanislk, learnathoner, vaielab, nickreese, Tuitio, grandmore, itnok, CollinEstes, sethyx, mstijak, MadDeveloper, balthazar, bitoiu, matthewwoop, robaleman, hems and others!

examples/subscribe-to-all.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const Binance = require('node-binance-api');
2+
const binance = new Binance().options('options.json');
3+
global.ticker = {};
4+
5+
// Get all symbols
6+
binance.prevDay(false, (error, prevDay) => {
7+
if ( error ) return console.log(error.body);
8+
let markets = [];
9+
for ( let obj of prevDay ) {
10+
let symbol = obj.symbol;
11+
12+
// Filter BTC & USDT markets only (example)
13+
if ( !symbol.endsWith('BTC') && !symbol.endsWith('USDT') ) continue;
14+
15+
console.log(`${symbol} price: ${obj.lastPrice} volume: ${obj.volume} change: ${obj.priceChangePercent}%`);
16+
global.ticker[symbol] = obj.lastPrice;
17+
markets.push(symbol);
18+
}
19+
20+
// Subscribe to trades endpoint for all markets
21+
binance.websockets.trades(markets, (trades) => {
22+
let { e: eventType, E: eventTime, s: symbol, p: price, q: quantity, m: maker, a: tradeId } = trades;
23+
console.log(`${symbol} price: ${price}`);
24+
global.ticker[symbol] = price;
25+
});
26+
27+
// You can use global.ticker anywhere in your program now
28+
setInterval(() => {
29+
console.log("*** Price of BTC: " + global.ticker.BTCUSDT);
30+
}, 3000);
31+
});

node-binance-api.js

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -313,14 +313,14 @@ let api = function Binance() {
313313
*/
314314
const handleSocketClose = function (reconnect, code, reason) {
315315
delete Binance.subscriptions[this.endpoint];
316-
if (Object.keys(Binance.subscriptions).length === 0) {
316+
if ( Binance.subscriptions && Object.keys(Binance.subscriptions).length === 0 ) {
317317
clearInterval(Binance.socketHeartbeatInterval);
318318
}
319319
Binance.options.log('WebSocket closed: ' + this.endpoint +
320320
(code ? ' (' + code + ')' : '') +
321321
(reason ? ' ' + reason : ''));
322-
if (Binance.options.reconnect && this.reconnect && reconnect) {
323-
if (parseInt(this.endpoint.length, 10) === 60) Binance.options.log('Account data WebSocket reconnecting...');
322+
if ( Binance.options.reconnect && this.reconnect && reconnect) {
323+
if ( this.endpoint && parseInt(this.endpoint.length, 10) === 60) Binance.options.log('Account data WebSocket reconnecting...');
324324
else Binance.options.log('WebSocket reconnecting: ' + this.endpoint + '...');
325325
try {
326326
reconnect();
@@ -336,7 +336,6 @@ let api = function Binance() {
336336
* @return {undefined}
337337
*/
338338
const handleSocketError = function (error) {
339-
340339
/* Errors ultimately result in a `close` event.
341340
see: https://github.com/websockets/ws/blob/828194044bf247af852b31c49e2800d557fedeff/lib/websocket.js#L126 */
342341
Binance.options.log('WebSocket error: ' + this.endpoint +
@@ -814,26 +813,26 @@ let api = function Binance() {
814813

815814
/**
816815
* rounds number with given step
817-
* @param {float} number - quantity to round
816+
* @param {float} qty - quantity to round
818817
* @param {float} stepSize - stepSize as specified by exchangeInfo
819818
* @return {float} - number
820819
*/
821-
roundStep: function (number, stepSize) {
820+
roundStep: function (qty, stepSize) {
822821
const precision = stepSize.toString().split('.')[1].length || 0;
823-
return (((number / stepSize) | 0) * stepSize).toFixed(precision);
822+
return (((qty / stepSize) | 0) * stepSize).toFixed(precision);
824823
},
825-
824+
826825
/**
827826
* rounds price to required precision
828-
* @param {float} number - price to round
827+
* @param {float} price - price to round
829828
* @param {float} tickSize - tickSize as specified by exchangeInfo
830829
* @return {float} - number
831830
*/
832-
roundTicks: function (number, tickSize) {
831+
roundTicks: function (price, tickSize) {
833832
const formatter = new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 8 });
834833
const precision = formatter.format(tickSize).split('.')[1].length || 0;
835-
if ( typeof number === 'string' ) number = parseFloat(number);
836-
return number.toFixed(precision);
834+
if ( typeof price === 'string' ) price = parseFloat(price);
835+
return price.toFixed(precision);
837836
},
838837

839838
/**
@@ -1703,7 +1702,7 @@ let api = function Binance() {
17031702
let context = Binance.depthCacheContext[symbol];
17041703
context.endpointId = endpointId;
17051704
}
1706-
}
1705+
};
17071706

17081707
let handleDepthStreamData = function (depth) {
17091708
let symbol = depth.s;
@@ -1788,6 +1787,29 @@ let api = function Binance() {
17881787
return subscription.endpoint;
17891788
},
17901789

1790+
/**
1791+
* Websocket staggered depth cache
1792+
* @param {array/string} symbols - an array of symbols to query
1793+
* @param {function} callback - callback function
1794+
* @param {int} limit - the number of entries
1795+
* @param {int} stagger - ms between each depth cache
1796+
* @return {Promise} the websocket endpoint
1797+
*/
1798+
depthCacheStaggered: function(symbols, callback, limit=100, stagger=200) {
1799+
if (!Array.isArray(symbols)) symbols = [symbols];
1800+
let chain = null;
1801+
1802+
symbols.forEach(symbol => {
1803+
let promise = () => new Promise(resolve => {
1804+
this.depthCache(symbol, callback, limit);
1805+
setTimeout(resolve, stagger);
1806+
});
1807+
chain = chain ? chain.then(promise) : promise();
1808+
});
1809+
1810+
return chain;
1811+
},
1812+
17911813
/**
17921814
* Websocket aggregated trades
17931815
* @param {array/string} symbols - an array or string of symbols to query

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "node-binance-api",
3-
"version": "0.8.3",
3+
"version": "0.8.4",
44
"description": "Binance API for node https://github.com/jaggedsoft/node-binance-api",
55
"main": "node-binance-api.js",
66
"dependencies": {

test.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1124,6 +1124,72 @@ describe('Websockets array depthcache', function () {
11241124
});
11251125
});
11261126

1127+
describe('Staggered websockets symbol depthcache', function () {
1128+
let symbol;
1129+
let bids;
1130+
let asks;
1131+
let cnt = 0;
1132+
beforeEach(function (done) {
1133+
this.timeout(TIMEOUT);
1134+
binance.websockets.depthCacheStaggered('BNBBTC', (a_symbol, a_depth) => {
1135+
cnt++;
1136+
if (cnt > 1) return;
1137+
stopSockets(true);
1138+
symbol = a_symbol;
1139+
bids = a_depth.bids;
1140+
asks = a_depth.asks;
1141+
done();
1142+
});
1143+
});
1144+
1145+
bids = binance.sortBids(bids);
1146+
asks = binance.sortAsks(asks);
1147+
1148+
it('check result of depth cache', function () {
1149+
assert(typeof (bids) === 'object', WARN_SHOULD_BE_OBJ);
1150+
assert(typeof (asks) === 'object', WARN_SHOULD_BE_OBJ);
1151+
assert(typeof (symbol) === 'string', WARN_SHOULD_BE_OBJ);
1152+
assert(bids !== null, WARN_SHOULD_BE_NOT_NULL);
1153+
assert(asks !== null, WARN_SHOULD_BE_NOT_NULL);
1154+
assert(symbol !== null, WARN_SHOULD_BE_NOT_NULL);
1155+
assert(Object.keys(asks).length !== 0, 'should not be 0');
1156+
assert(Object.keys(bids).length !== 0, 'should not be 0');
1157+
});
1158+
});
1159+
1160+
describe('Staggered Websockets array depthcache', function () {
1161+
let symbol;
1162+
let bids;
1163+
let asks;
1164+
let cnt = 0;
1165+
beforeEach(function (done) {
1166+
this.timeout(TIMEOUT);
1167+
binance.websockets.depthCacheStaggered(['BNBBTC', 'TRXBTC'], (a_symbol, a_depth) => {
1168+
cnt++;
1169+
if (cnt > 1) return;
1170+
stopSockets();
1171+
symbol = a_symbol;
1172+
bids = a_depth.bids;
1173+
asks = a_depth.asks;
1174+
done();
1175+
});
1176+
});
1177+
1178+
bids = binance.sortBids(bids);
1179+
asks = binance.sortAsks(asks);
1180+
1181+
it('check result of symbols array depth cache', function () {
1182+
assert(typeof (bids) === 'object', WARN_SHOULD_BE_OBJ);
1183+
assert(typeof (asks) === 'object', WARN_SHOULD_BE_OBJ);
1184+
assert(typeof (symbol) === 'string', WARN_SHOULD_BE_OBJ);
1185+
assert(bids !== null, WARN_SHOULD_BE_NOT_NULL);
1186+
assert(asks !== null, WARN_SHOULD_BE_NOT_NULL);
1187+
assert(symbol !== null, WARN_SHOULD_BE_NOT_NULL);
1188+
assert(Object.keys(asks).length !== 0, 'should not be 0');
1189+
assert(Object.keys(bids).length !== 0, 'should not be 0');
1190+
});
1191+
});
1192+
11271193
describe('Websockets prevDay', function () {
11281194
let response;
11291195
let cnt = 0;

0 commit comments

Comments
 (0)