The support to this library is scheduled to be discontinued, and it will be offline within the next six months.
Please consider this offically supported Node.js library available at https://github.com/binance/binance-connector-node
This project forked from jaggedsoft/node-binance-api
Node Binance API is an asynchronous node.js library for the Binance API designed to be easy to use.
License: MIT License
The support to this library is scheduled to be discontinued, and it will be offline within the next six months.
Please consider this offically supported Node.js library available at https://github.com/binance/binance-connector-node
I'm using binance.websockets.trades
and I would like to cancel the streaming data or stop it completely, because I want to restart with new list in the nodejs socket.io
application.
Is there a way to stop the streaming or cancel it?
Hello. Thank you for library! I got small question regarding buy/sell api. So far I get unclear response. Do you know what might be the reason of it? :)
Here is the code:
BINANCE.buy("IOTAETH", 5, 0.00225758, {type:'LIMIT'}, (error, response) => {
console.log('Error:', error)
console.log("Limit Buy response:", response);
console.log("order id: " + response.orderId);
});
Here is the response:
Error: null
Limit Buy response: {}
order id: undefined
Hi,
On v0.3.7 i see below error on market order. market order has nothing to do with price?
BUY(LTCETH,0.01,0) { code: -1013, msg: 'Invalid price.' }
Thanks
Hi.
After making any request I get the following error in my browser:
Failed to load https://api.binance.com/api/v1/ticker/allPrices: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Is there any additional steps I have to take in order to make it work?
signedRequest(base+'v3/myTrades', {symbol:symbol, ...options}
is the '...' necessary?
signedRequest(base+endpoint, opt, function(error, response) {
if ( typeof response.msg !== 'undefined' && response.msg === 'Filter failure: MIN_NOTIONAL' ) {
console.error('Order quantity too small. See exchangeInfo() for minimum amounts');
}
if ( callback ) callback(error, response);
else console.log(side+'('+symbol+','+quantity+','+price+') ',response);
}, 'POST');
};
https://www.binance.com/restapipub.html#user-content-market-data-endpoints
in official webside, 'orderId' is not required.
if pass orderId = null,can cancel all open orders??
Name | Type | Mandatory | Description |
---|---|---|---|
symbol | STRING | YES | |
orderId | LONG | NO | |
origClientOrderId | STRING | NO | |
newClientOrderId | STRING | NO | Used to uniquely identify this cancel. Automatically generated by default. |
recvWindow | LONG | NO | |
timestamp | LONG | YES |
I'm trying to open a websocket with the following example from documentation:
binance.websockets.prevDay('BNBBTC', (error, response) => { console.log(response); });
However, I am getting a 400 response from the server. I noticed in Chrome dev tools that the request was "https://" and not "wss://". So, I tested it in Chrome Simple Websocket client. I changed the "https://" to "wss://" and it worked there but I don't know how to fix it in the program.
I think the "https://" protocol is being transformed in the request.js document. Am I doing something wrong?
One question: Is there any api call to get the list of all the currencies available? Thanks a lot
Hello,
First thank you for the nice API, I am using it to run a bot on Binance.
I am still testing it but I noticed that after a long time (+/- 24h) trades websockets are disconnecting, and at a point I am not recieving any information anymore, is this a normal behaviour and how can I avoid it?
Thank you
It seems that there is some limit of the number of open connections with different users.
Or am I doing something wrong?
In the documentation it only shows stop loss example for sell which is
binance.sell("ETHBTC", quantity, price, {stopPrice: stopPrice});
I'm assuming its same for buy, is that correct?
binance.buy("ETHBTC", quantity, price, {stopPrice: stopPrice});
also, another question, if I use binance.sell("ETHBTC", quantity, price, {stopPrice: stopPrice});
to create stop loss order, would it return order it? or do I have to call another method to retrieve order it?
{'symbol': 'ICXBTC', 'orderId': ********, 'clientOrderId': '****************', 'price': '0.00000000', 'origQty': '2.00000000', 'executedQty': '2.00000000', 'status': 'FILLED', 'timeInForce': 'GTC', 'type': 'MARKET', 'side': 'BUY', 'stopPrice': '0.00000000', 'icebergQty': '0.00000000', 'time': 1516988037639, 'isWorking': True}
In websocket, there is "maker" boolean in response message, what does it stand for? Is it BUY & SELL? If so, "true" is BUY or SELL?
Thanks.
Hello,
I am trying to call withdraw API. All the API key and secret is enabled and i call withdraw api like below:
binance.withdraw('ETH', gdaxAddress, 0.0205, false, function(response) {
console.log(response);
});
"Name" isn't a mandatory param. I still get following error response:
{ msg: 'Name is empty.', success: false }
What could be the issue.
Thanks
Aditya
Hello, first of all, thanks a lot for the great work :)
I'm trying to implement your work on browser side, and I managed to solve CORS problem using CORS Anywhere proxy, but still having an issue with websocket as getting following 400 error:
Request URL:https://stream.binance.com:9443/ws/btcusdt@ticker
Request Method:GET
Status Code:400
Remote Address:52.68.217.58:9443
Referrer Policy:no-referrer-when-downgrade
Response Headers
cache-control:no-cache, no-store, must-revalidate
content-length:0
date:Fri, 26 Jan 2018 04:02:33 GMT
expires:Thu, 01 Jan 1970 00:00:01 GMT
server:nginx
status:400
strict-transport-security:max-age=31536000; includeSubdomains
x-frame-options:SAMEORIGIN
x-nginx-pushstream-explain:Don't have at least one of the mandatory headers: Connection, Upgrade, Sec-WebSocket-Key and Sec-WebSocket-Version
Request Headers
:authority:stream.binance.com:9443
:method:GET
:path:/ws/btcusdt@ticker
:scheme:https
accept:/
accept-encoding:gzip, deflate, br
accept-language:en,ko;q=0.9,th;q=0.8,en-US;q=0.7
cache-control:no-cache
origin:http://evil.com/
pragma:no-cache
referer:http://localhost:3000/
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
I believe this part:
x-nginx-pushstream-explain:Don't have at least one of the mandatory headers: Connection, Upgrade, Sec-WebSocket-Key and Sec-WebSocket-Version
is the problem which I don't understand...maybe do you have any idea?
Thanks in advance!
Hello!
I'm trying to buy and sell assets with market orders but most of the time, it's not working and I get the error: "Account has insufficient balance for requested action.".
Even though I have enough balance to buy/sell. I even can perform the buy/sell on the website with the same amount.
What's the problem there?
Enhancement
Are there any plans for a WebSocket support
Hello,
I've just noticed that, after subscribing to the candlestick websocket (for example) for symbol 'BTCUSDT' the library seems to subscribe to a websocket for each letter.
In order words, when listing all websockets 60 seconds (with a timeout) after subscribing them, this is what is shown:
ws subscription:
binance.websockets.candlesticks(['BTCUSDT'], '1m', (candlestickData) => { });
ws listing after 60 seconds:
let endpoints = binance.websockets.subscriptions();
for ( let endpoint in endpoints ) {
console.log('' + endpoint);
}
console output:
btcusdt@kline_1m
b@kline_1m
t@kline_1m
c@kline_1m
u@kline_1m
s@kline_1m
d@kline_1m
(tested on 0.4.8)
On some Exchange APIs it's possible to atomically change an order. I.e..: withdraw/cancel an order + set a new one. Usescases: changed limit when it's clear it's not going to be filled, etc.
Thoughts?
Hi,
Is it possible to get account updates for multiple users in one socket/stream? I am a bit confused because they will have different API keys. If you can show me some example code, that would be great!
(I am writing a dashboard for a friend and me to manage our portfolios)
I am trying to consume binance rest apis in a small react app. Following is the issue that I face:
Failed to load https://api.binance.com/api/v1/ticker/allPrices: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please suggest. TIA
Problem:
Because of CORS and Binance's server config, a server is currently required for accessing any endpoint. While this makes total sense for signed endpoints, its a bit overkill for unsigned endpoints (allPrices, etc).
Solution:
I see that you guys are running on nginx. You can allow cross origin requests for specific endpoints:
location /api/v1/ticker/allPrices {
add_header 'Access-Control-Allow-Origin' '*';
}
This will allow people to contribute much simpler apps, widgets, etc. without having to spin up a server instance 🤘🏻
Why there is no package.json in this repository?
Errors that may occur making requests are not passed to callback functions.
This is a node anti-pattern and breaks automatic promisification of the functions.
binance.prices(function(ticker) {
// ...
})
binance.prices(function(err, ticker) {
// ...
})
Hi,
After upgrading from 0.3.0 to 0.3.6 or 0.3.7 the market order is failing with following error:
/home/ec2-user/etherlitecoinproject/node_modules/node-binance-api/node-binance-api.js:89
if ( response && response.statusCode !== 200 ) throw response;
[object Object]
Also updating in package.json to 0.3.0 and doing npm install doesn't move the core node-binance-api to 0.3.0 but keeps it at 0.3.7 and the error then changes to below:
BUY(LTCETH,0.01,0) { code: -1013, msg: 'Invalid price.' }
These are breaking changes as existing code stops working.
Some Binance endpoints provide a string instead of a number when being parsed back into JS, it could be helpful if this lib do the parsing before returning the data.
Could make the relevant changes if it's a hassle.
There is an error using the basic balance function. Thanks.
I am trying to request "all trades" but I cannot find a way to request all trades beside a "declared pair"
e.g. the following works (including the pair NEO-BTC)
binance.trades("NEOBTC", function(json) {
console.log("trade history",json);
});
but what about to request all the trade history? I have tried the following with no luck...
binance.trades({}, function(json) {
console.log("trade history",json);
});
is it a bug or am I missing something?
Hello,
I have been trying to fetch an orders status to look for the price and qty details from the fills. This as explained in the API docs can be fetch by using newOrderRespType ENUM.
newOrderRespType | ENUM | NO | Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
binance.orderStatus(_SYMBOL_, orderID, newOrderRespType.FULL, function(err, orderStatus, symbol) {
if(err)
logger.info(`ERROR: ${err.message}`);
else{
logger.info(symbol + " order status:" + JSON.stringify(orderStatus));
}
});
But i get ReferenceError: newOrderRespType is not defined.
Can someone tell how to fetch FULL orderStatus as explained in the API doc @ https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
So for the past 2 hours I've been getting a ton of websocket errors. (code 1006) After a bunch of digging I finally got on the binance telegram channel and found out it was actually Binance's apis that are down, not something else.
It'd be great if we could build a way to know that binance is down by spotting repeated websocket reconnect fails and repeated api calls with out a success response and then call an options.binanceDown() or something.
The big issue is that currently it is ONLY the API that is down, not the platform. (I tested executing a small trade)
This should be a major concern for anyone who is hoping to execute more than a few trades an hour and let their bot run over night.
My plan is to hook my bot up to twillio and fire off a slew of text messages and even calls so I can go cancel open orders manually if it goes down in the middle of the night.
I'm happy to hack something together, but would love other input if anyone has ideas.
code sample
binance.websockets.userData(balance_update, execution_update);
output sample
[SELL]SNTETH CANCELED price 0.00031126 quantity 40.00000000 type: STOP_LOSS_LIMIT status: CANCELED order id: 8233160 client id: opd9RzkTItwJfbGigWkDCn Reason: NONE
[SELL]SNTETH CANCELED price 0.00031126 quantity 40.00000000 type: STOP_LOSS_LIMIT status: CANCELED order id: 8233160 client id: opd9RzkTItwJfbGigWkDCn Reason: NONE
For some reason execution_update
is getting triggered twice by one order, try running it with console.log and place demo order on binance or by API code, execution_update
will throw double message
I have list of array, which I pass inside websocket callback, but that array gets updated outside websocket after sometime. But inside callback, it still has old array and its old values, does not syncs with outer array.
let testing = true;
global.testing = testing;
// live trading
binance.websockets.trades([‘ETHBTC’], (liveTrades) => {
if (testing)
console.log("testing = false"); // testing is always false, never gets true
else
console.log("testing = true");
});
testing = true;
When I place a New market order and get this order through the API it shows price 0. How do I know what price did the order bought?
I am using the chart method. Maybe I'm subscribing too many in one go so I need to throttle them somehow.
In any case do you might need to add some error handling when handling callback as its passing empty object to klineData function.
node_modules/node-binance-api/node-binance-api.js:395
for ( let tick of ticks ) {
^
TypeError: undefined is not a function
=======================================================
let getSymbolKlineSnapshot = function(symbol) {
publicRequest(base + 'v1/klines', { symbol:symbol, interval:interval }, function (error, data) {
klineData(symbol, interval, data);
//options.log('/klines at ' + info[symbol][interval].timestamp);
if ( typeof klineQueue[symbol][interval] !== 'undefined' ) {
for ( let kline of klineQueue[symbol][interval] )
klineHandler(symbol, kline, info[symbol][interval].timestamp);
delete klineQueue[symbol][interval];
}
if ( callback ) callback(symbol, interval, klineConcat(symbol, interval));
});
};
I've got an error and I don't now how to solve it... can anyone help?
Here my output:
/home/pi/node-binance-api/node-binance-api.js:26
const publicRequest = function(url, data, callback, method = "GET") {
^
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:414:25)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/home/pi/node-binance-api/examples/test.js:1:79)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
Here is a suggestion to ensure no depth update is missed (due to network interruptions, etc) by checking that each depth.U flag equals the previous depth.u+1.
depthCache: function depthCacheFunction(symbols, callback, limit = 500) {
for ( let symbol of symbols ) {
if ( typeof info[symbol] == "undefined" ) info[symbol] = {};
info[symbol].u = 0;
depthCache[symbol] = {bids: {}, asks: {}};
messageQueue[symbol] = [];
let reconnect = function() {
if ( options.reconnect ) depthCacheFunction(symbols, callback);
};
subscribe(symbol.toLowerCase()+"@depth", function(depth) {
if ( !info[symbol].u ) {
messageQueue[symbol].push(depth);
return;
}
if (depth.U <= (info[symbol].u+1)){ //it should normally be ==, but may be < for the first update when depth.U == json.lastUpdateId
depthHandler(depth);
info[symbol].u = depth.u;
if ( callback ) callback(symbol, depthCache[symbol]);
} else {
throw "ERROR: Skipped depth update!";
}
}, reconnect);
publicRequest(base+"v1/depth", {symbol:symbol, limit:limit}, function(json) {
info[symbol].u = json.lastUpdateId;
depthCache[symbol] = depthData(json);
for ( let depth of messageQueue[symbol] )
if ( depth.u > json.lastUpdateId ) {
if (depth.U <= (info[symbol].u+1)){ //it should normally be ==, but may be < for the first update when depth.U == json.lastUpdateId
depthHandler(depth);
info[symbol].u = depth.u;
} else {
throw "ERROR: Skipped depth update in messageQueue!";
}
}
delete messageQueue[symbol];
if ( callback ) callback(symbol, depthCache[symbol]);
});
}
},
Also removed the unnecessary check for firstUpdateId
every time depthHandler()
is called, the task is handled in depthCache()
where it is done only for initialization.
const depthHandler = function(depth) { // Used for websocket @depth
let symbol = depth.s, obj;
for ( obj of depth.b ) { //bids
depthCache[symbol].bids[obj[0]] = parseFloat(obj[1]);
if ( obj[1] == '0.00000000' ) {
delete depthCache[symbol].bids[obj[0]];
}
}
for ( obj of depth.a ) { //asks
depthCache[symbol].asks[obj[0]] = parseFloat(obj[1]);
if ( obj[1] == '0.00000000' ) {
delete depthCache[symbol].asks[obj[0]];
}
}
};
Please let me know what you think of these changes, and thank you for making this great API library available!
out of curiosity, why there are two repos for node? which one should we use? thanks.
https://github.com/binance-exchange/binance-api-node
https://github.com/binance-exchange/node-binance-api
I want to be able to get the current price & volume for each coin, once per minute. I'm using the binance.prices(function(ticker) {
to get back the current prices. I can then feed that into something like binance.websockets.candlesticks(['IOTABTC'], "1d", function(candlesticks) {
, and I'll get back all of the information I need.
But is there a way for me to disconnect from that websocket after that? In my code I've already stored the price to a database, and a minute later I'll call the same endpoint to repeat the process. But I don't want to kick off a new websocket every minute - I just want to close one after I get the info. from it.
It would be better if there was a non-websocket API to get the price/volume, but I don't see it.
There's no definition file written for this lib.
I'm writing my code using TypeScript and this could help a lot.
I could help by providing a .d.ts file for people like me which can be included in the npm package.
But the best approach would be to convert the current code to TypeScript (wouldn't be too hard, I could do that as well if I'd get an approval from you guys) and future maintenance to be written in TypeScript as well.
How can I set "newClientOrderId" when placing an order?
Also is there any WebSocket for new orders which are coming in (BUY, SELL)? Is https://github.com/jaggedsoft/node-binance-api/blob/master/examples/advanced.md#user-data-account-balance-updates-trade-updates-new-orders-filled-orders-cancelled-orders-via-websocket the link for the WebSocket for orders? would it have "newClientOrderId" id?
I want to track the orders with our system, so we can place it under right sell / buy user.
{ msg: 'The operation failed, please try again later.',
success: false,
id: 'de01da4a695745e7911789b06dac5c3e' }
sell and buy methods accepts a callback function. Do they get executed only once even in the case of a Partial Fill? Would they get executed again when the order gets completely filled later?
Is there a way (directly accessing the REST api?) to ensure callback gets executed only when the order has completely been filled?
I've been using the library for several weeks, especially the websockets calls. Suddenly this has started showing up the past couple days when calling some of them, like binance.websockets.candlesticks().
./node_modules/brotli/build/encode.js:3
1<process.argv.length?process.argv[1].replace(/\/g,"/"):"unknown-program");b.arguments=process.argv.slice(2);"undefined"!==typeof module&&(module.exports=b);process.on("uncaughtException",function(a){if(!(a instanceof y))throw a;});b.inspect=function(){return"[Emscripten Module object]"}}else if(x)b.print||(b.print=print),"undefined"!=typeof printErr&&(b.printErr=printErr),b.read="undefined"!=typeof read?read:function(){throw"no read() available (jsc?)";},b.readBinary=function(a){if("function"===
^Error: unexpected server response (504)
at ClientRequest._req.on (./node_modules/ws/lib/WebSocket.js:653:21)
at ClientRequest.emit (events.js:160:13)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:548:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:115:23)
at TLSSocket.socketOnData (_http_client.js:439:20)
at TLSSocket.emit (events.js:160:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at TLSSocket.Readable.push (_stream_readable.js:213:10)
at TLSWrap.onread (net.js:599:20)
From the binance-official-api-docs:
HTTP 504 return code is used when the API successfully sent the message but not get a response within the timeout period. It is important to NOT treat this as a failure; the execution status is UNKNOWN and could have been a success.
It looks like it might be a ws/brotli library issue though... Is the best solution here to catch the error and just retry calling the websocket (e.g. on failure, re-run binance.websockets.candlesticks())? Or is this something the api should attempt to catch and do the retry itself?
When I make a BTCUSDT trade, the price always returns as 0.00000000.
For example, if I were to make a market buy of 0.00003400, the execution_update ws function would return:
BTCUSDT SELL MARKET ORDER #xxxxxxx (NEW)
..price: 0.00000000, quantity: 0.00003400
Any help would greatly be appreciated!
Thanks!
I need to create order inside the ticker, but when I use normal create order with async/await
it does not work, do you know why its not working? have you tried it?
export const cancelSellStopOrder = async (id, coin, callback) => {
return await binance.cancel(coin.symbol, coin.stopId); // hold the script until callback is returned!
}
Error below:
node_modules/node-binance-api/node-binance-api.js:315
if ( typeof data.bids !== 'undefined' ) {
^
TypeError: Cannot read property 'bids' of undefined
at depthData (/Volumes/DATA/www/storm-alert/node_modules/node-binance-api/node-binance-api.js:315:19)
at /Volumes/DATA/www/storm-alert/node_modules/node-binance-api/node-binance-api.js:497:39
at Request._callback (/Volumes/DATA/www/storm-alert/node_modules/node-binance-api/node-binance-api.js:45:12)
at self.callback (/Volumes/DATA/www/storm-alert/node_modules/request/request.js:186:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestError (/Volumes/DATA/www/storm-alert/node_modules/request/request.js:878:8)
at emitOne (events.js:101:20)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.