2

hi is it possible to keep an up to date copy of the order book in an array from the level 2 web socket feed similar to how it is on the website or in the first message returned as snapshot

enter image description here

snapshot returned from level 2 update as type="snapshot"

enter image description here

this is what i am trying to recreate using the type="l2update"

enter image description here

the question is how do i use the l2updade to keep an accurate copy of the order book or at least get the top level ask and bid from the web socket instead of poling the "getProductOrderBook"

const websocket = new CoinbasePro.WebsocketClient(
  ["BTC-EUR"],
  "wss://ws-feed.pro.coinbase.com",
   null,
  { channels: [
    {
      "name": "level2"
    }
  ]
});


websocket.on('message', data => {

var bids = [];
var asks = [];
var x= 0;
var x2 = 0;

  if(data.changes[0][0] == "buy"){
      if(x <= 100){
        bids[x] = parseFloat(data.changes[0][1]);
        x++;
      }else{
        x = 0;
        bids[x] = parseFloat(data.changes[0][1]);
        x++;
      }
    }

    if(data.changes[0][0] == "sell"){
      if(x2 <= 100){
        asks[x2] = parseFloat(data.changes[0][1]);
        x2++;
      }else{
        x2 = 0;
        asks[x2] = parseFloat(data.changes[0][1]);
        x2++;
      }
    }
    console.log(data);
});
1
  • 1
    Hi, could you please give some feedback about my answer? Commented Jul 4, 2020 at 12:50

1 Answer 1

1

To do it directly in the array is useless complicated. I would do it in an object and would convert the object to an array when required. Something like (I assume product_id is always BTC-EUR):

let asks;
let bids;

websocket.on("message", data => {
  if(data.type == "snapshot") {
    asks = {};
    bids = {};

    data.asks.forEach(([price, amount]) => (asks[price] = parseFloat(amount)));
    data.bids.forEach(([price, amount]) => (bids[price] = parseFloat(amount)));

    return;
  }

  if(data.type == "l2update") data.changes.forEach(change => {
    const [action, price, amount] = change;
    const obj = action == "buy" ? bids : asks;
    const parsed = parseFloat(amount);

    if(parsed) obj[price] = parsed;
    else delete obj[price];
  });
});

Than you can always get the arrays with (or vice versa, didn't tested):

Object.entries(asks).map(([pr, am]) => [parseFloat(pr), am]).sort((a, b) => a[0] - b[0]);
Object.entries(bids).map(([pr, am]) => [parseFloat(pr), am]).sort((a, b) => b[0] - a[0]);

Hope this helps.

1
  • This was helpful Commented Nov 1, 2021 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.