Unable to recreate order book with l2 data
Closed this issue · 0 comments
benjamin-wilson commented
I am trying to recreate the coinbase pro orderbook however it doesn't seem to be reflecting what I see though the coinbase pro UI and the longer the code runs the wider the spread gets, indicating something isn't right.
this.coinbasePro.ws.on(WebSocketEvent.ON_OPEN, async () => {
await this.coinbasePro.ws.subscribe([
{
name: WebSocketChannelName.LEVEL2,
product_ids: ['BTC-USD']
}
]);
});
this.coinbasePro.ws.connect({ debug: false });
this.coinbaseOrderBook$ = new Observable((subscriber) => {
this.coinbasePro.ws.on(WebSocketEvent.ON_MESSAGE_L2SNAPSHOT, async snapshot => {
let asks = {};
let bids = {};
snapshot.asks.forEach(([price, amount]) => (asks[price] = parseFloat(amount)));
snapshot.bids.forEach(([price, amount]) => (bids[price] = parseFloat(amount)));
this.coinbasePro.ws.on(WebSocketEvent.ON_MESSAGE_L2UPDATE, async (snapshotUpdate) => {
snapshotUpdate.changes.forEach(([action, price, amount]) => {
const obj = action == 'buy' ? bids : asks;
if (amount != '0.00000000') {
obj[price] = parseFloat(amount);
}
else {
// Sometimes data doesn't exist... I don't think this should happen?
if (obj[price] != null) {
delete obj[price];
}
}
});
subscriber.next({ bids, asks });
});
});
});
I also noticed the snapshotUpdate.changes length is always 1 whereas the coinbase pro GUI has variable length, not sure if that has anything to do with it.
Often changes come through with the amount '0.00000000' indicating they need to be deleted from the order book but they don't exist. It feels like there is missing data somewhere.