Search code examples
kdb

Use KDB to Generate Best Bid Ask Order Table from Best Bid Ask Quote Table (nbbo)


Now i have the nbbo, which record the best bid ask quote information. I need to generate the corresponding order flow from this. The nbbo looks like:

date sym time bid bsize ask asize

2020.02.03 AAPL 0D04:00:00.020394647 299.29 1 1e+09 0
2020.02.03 AAPL 0D04:00:00.080067964 299.29 1 329 1
2020.02.03 AAPL 0D04:00:00.080068172 299.29 1 313 5
2020.02.03 AAPL 0D04:00:00.080132251 299.98 1 313 5
2020.02.03 AAPL 0D04:00:00.080132459 300 1 313 5

How can I implement this logic using KDB?

The logic i am considering about to use is as follows:

  • if the bid price is the same as the previous one, and the size increase, so there are buy order with size - prev size;
  • if the bid price is the same as the previous one, and the size decreae, so there are sell order with size - prev size;
  • if the ask price is the same as the previous one, and the size increase, so there are sell order with size - prev size;
  • if the ask price is the same as the previous one, and the size decrease, so there are buy order with size - prev size;
  • if the bid price is the higher as the previous one, so there are buy order with size;
  • if the bid price is the lower as the previous one, so there are sell order with prev size;
  • if the ask price is the higher as the previous one, so there are buy order with prev;
  • if the ask price is the lower as the previous one, so there are sell order with size;

Solution

  • You can do something like code snippet below.

    {
      q: flip `date`sym`time`bid`bsize`ask`asize! 
        (5#2020.02.03;5#`AAPL;
          0D04:00:00+til 5;
          299.29 299.29 299.29 299.98 300;
          1 5 3 1 1f; 
          1e09 329 313 313 313f;
          0 1 5 5 5f);
      q: update buy: 0f, sell: 0f from q;
      q: update buy: ?[(bid=prev bid)&bsize>prev bsize;bsize-prev[bsize];buy] from q;
      q: update sell: ?[(bid=prev bid)&bsize<prev bsize;prev[bsize]-bsize;sell] from q;
      q
    

    }`

    The two first clauses are there, rest is up to you. Some of the clauses could be combined, but I'd keep things simple and use separate update for each of them.