Closed alteredorange closed 6 years ago
Your confusion is understandable, I normally use websockets.depthCache()
, so haven't noticed until now that the library actually doesn't implement the Partial Book Depth Streams (<symbol>@depth<levels>
) yet. The most likely reason is that it is a stream that wasn't available initially. Will look into this as soon as possible.
If you use websockets.depthCache()
in the meantime you can do this:
binance.websockets.depthCache('BNBBTC', (symbol, depth) => {
// The optional second parameter `limit` passed to the `sort*` functions
// lets you limit how much of the array is sorted, or in other words, just
// gives you back the N best asks/bids, where N = `limit`.
const bestAsk = binance.array(binance.sortAsks(depth.asks, 1))[0];
const bestBid = binance.array(binance.sortBids(depth.bids, 1))[0];
});
Edit:
Just for completeness. The reason websockets.depth()
is confusing to use, is because that actually only returns the latest diffs of the market depth, so on its own you have absolutely no way of knowing whether the price you just got is the best or worst, or anywhere in between. It's used to maintain a local order book, which is what depthCache()
does for you.
I agree with keith, I have never actually used depth by itself, since depthCache is much easier
Here is a complete example
binance.websockets.depthCache(["BTCUSDT"], function(symbol, depth) {
let max = 10; // Only show the 10 best bids / asks (optional)
let bids = binance.sortBids(depth.bids, max);
let asks = binance.sortAsks(depth.asks, max);
console.log(binance.reverse(asks)); // print asks
console.log("ask: ", binance.first(asks));
console.log("bid: ", binance.first(bids));
console.log(bids); // print bids
});
This will make it look just like the website
Ah, you see, jagged knows the fancy functions like binance.first()
👍
Good to know, thanks for the help! The only downside with depthcache is that it only updates once per second, while the other one seems more real-time (and since I'm trying to only grab the best/first bid/ask, cache is overkill.
binance.websockets.depth("BTCUSDT", (depth) => {
const symbol = depth.s;
console.log(symbol+" bid: ", depth.b[0]);
console.log(symbol+" ask: ", depth.a[0]);
//console.log(symbol+" bids", binance.array(depth.b));
//console.log(symbol+" asks", binance.array(depth.a));
});
Unfortunately it appears .depth() websockets are also only updated once per second.
This is user error more than anything, but I can't figure out how to get the current market depth from the streaming websocket. If i do the "Maintain Market Depth Cache Locally via WebSocket" I can get the best bid and best ask, but when I use the code below I only get an [object, object]. How do I pull out the best bid and best ask?
Thanks for the help!
Get Market Depth via WebSocket