BitMEX / api-connectors

Libraries for connecting to the BitMEX API.

Home Page:https://www.bitmex.com/app/restAPI

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Nodejs websocket: orderBookL2 does not update after a few seconds

flolege opened this issue · comments

After some updates, orderBookL2 triggers the callback but does not update the data as far as I can see.

You can reproduce the issue with this code:

let oldBid = 0
let testCnt = 0

bitmex.addStream(bitmexInstrument, 'orderBookL2', function (data, symbol, tableName) {
    if (!data.length) return;

    let bestBid = 0
    let firstBidIndex = 0

    for (let index = 1; index < data.length; index++) {
        if(data[index].side === 'Sell') continue

        bestBid = data[index].price
        firstBidIndex = index
        break       
    }

    if(oldBid !== bestBid) {
        oldBid = bestBid
        console.log("Orderbook update - Best bid: " + bestBid)
    }  

    testCnt ++
    if(testCnt % 100 === 0) {
        console.log("Top Bid Log:")
        console.log(data[firstBidIndex])
        console.log(data[firstBidIndex+1])
        console.log(data[firstBidIndex+2])
    }
}); 

After some "Orderbook update - Best bid" logs, bestBid is not updated anymore.

You can check via the "Top Bid Log" that the 3 top bids stay the same forever.

Am I doing something wrong here, or does that method simply not work? I saw already many other similar issues here, with no feedback from Bitmex and no clear solution.

Please advice, it would be very much appreciated.

Ok I figured it out by myself. If someone struggles with the same problem, here a short description:

I expected the data object always comes sorted, but thats not true. It comes sorted by price descending the first time you subscribe to the stream. Then, any new level gets attached to the end of the array. So the solution is e.g. in my case to sort the array by price descending before you look into it.

I know its somehow documented in here but it works a bit differently (only data object is delivered, no action indicator etc)