Skip to content

Read the touch from a strategy

The best bid and ask a strategy callback receives follow the touch, which a venue's one-level top-of-book frames move between depth updates. This page is the working side of The touch and the book: where the values are in each binding, how to tell a touch move from a depth update, and how to replay a tape that carries tops.

Where the touch is

Every callback's context quotes the touch. The depth book is not what the quotes read.

Binding Best bid / ask, mid Stamps
Python ctx.best_bid, ctx.best_ask, ctx.mid_price ctx.last_touch_ns, ctx.last_update_ns
Node ctx.bestBid, ctx.bestAsk, ctx.midPrice ctx.lastTouchNs, ctx.lastUpdateNs (BigInt)
Codon ctx.best_bid(), ctx.best_ask(), ctx.mid_price() ctx.last_touch_ns(), ctx.last_update_ns()
C++ c.touchBid, c.touchAsk, c.touchMid() c.lastTouchNs, c.lastUpdateNs

last_update_ns is the exchange timestamp of the last trade, depth frame or bar. last_touch_ns is the exchange timestamp of the frame that last wrote the touch. A depth frame writes both; a top-of-book frame writes last_touch_ns only, and never fires on_book_update.

Tell a touch move from a depth update

The direct way is on_touch (onTouch in Node and embedded JavaScript, onSymbolTouch in C++). It fires when the touch changes, price or size on either side: on a top-of-book frame, and on a depth frame that moved it, right after on_book_update for that frame. A top that repeats the touch fires nothing; a depth frame that leaves the touch where it was fires on_book_update alone.

Inside the other callbacks the stamps answer the same question. Keep the last_update_ns you saw in your last book callback. On any later callback, ctx.last_touch_ns greater than that value means a top arrived after the last depth frame you were shown, and the quotes in ctx are that top's. The stamps are the venue's: Hyperliquid stamps in milliseconds, so a top in the same millisecond as the depth frame reads as no move, and a frame sent without a time is stamped 0. on_touch compares the quotes, so it does not miss those. The example replays a tape of one depth snapshot, three tops and a trade, and prints what each callback sees:

"""
Read the touch from a strategy: which stamp moved, and what it means.

Replays ``docs/examples/data/touch_tape``: one depth snapshot, three
one-level top-of-book frames, one trade, one symbol. The tape is synthetic,
written for this page; its shape is what a Hyperliquid recording with the
bbo channel on looks like between two depth snapshots.

A depth frame dispatches ``on_book_update`` and stamps both
``last_update_ns`` and ``last_touch_ns``. A top-of-book frame never reaches
``on_book_update``: it moves ``best_bid`` / ``best_ask`` / ``mid_price`` and
``last_touch_ns`` only, and fires ``on_touch``, which this strategy does not
override. The trade that follows is the first callback here to see what the
tops left behind, and its ``last_update_ns`` is the trade's own stamp. So "did the touch move since the last book I was shown" is
``ctx.last_touch_ns > <last_update_ns seen in on_book_update>``.

Usage:
    cd /path/to/lrvx
    PYTHONPATH=build/python python3 docs/examples/python_read_the_touch.py
"""

import os

import lrvx

TAPE = os.path.join(os.path.dirname(__file__), "data", "touch_tape")

T0 = 1_700_000_000_000_000_000
SECOND = 1_000_000_000


class TouchWatcher(lrvx.Strategy):
    def __init__(self, symbols):
        super().__init__(symbols)
        self.last_book_ns = 0
        self.seen = []

    def on_book_update(self, ctx):
        # A depth frame: the book and the touch were both written just now,
        # so the two stamps agree.
        self.last_book_ns = ctx.last_update_ns
        self.seen.append(("book", ctx.last_update_ns, ctx.last_touch_ns,
                          ctx.best_bid, ctx.best_ask))
        print(f"book   update={ctx.last_update_ns} touch={ctx.last_touch_ns} "
              f"bid={ctx.best_bid} ask={ctx.best_ask}")

    def on_trade(self, ctx, trade):
        # This strategy took no callback for the tops in between (it has no
        # on_touch). The context carries them:
        # the quotes are the last top's, last_touch_ns is its stamp, and
        # last_update_ns is this trade's.
        moved = ctx.last_touch_ns > self.last_book_ns
        self.seen.append(("trade", ctx.last_update_ns, ctx.last_touch_ns,
                          ctx.best_bid, ctx.best_ask, moved))
        print(f"trade  update={ctx.last_update_ns} touch={ctx.last_touch_ns} "
              f"bid={ctx.best_bid} ask={ctx.best_ask} "
              f"touch_moved_since_last_book={moved} mid={ctx.mid_price}")


def main() -> None:
    registry = lrvx.SymbolRegistry()
    sym = registry.add_symbol("sim", "BTCUSDT", tick_size=0.01)
    runner = lrvx.BacktestRunner(registry, fee_rate=0.0, initial_capital=10_000.0)
    strategy = TouchWatcher([sym])
    runner.set_strategy(strategy)
    runner.run_tape(TAPE)

    # Pinned: the page describes exactly this behaviour.
    assert strategy.seen == [
        ("book", T0, T0, 100.0, 101.0),
        ("trade", T0 + 4 * SECOND, T0 + 3 * SECOND, 100.4, 100.6, True),
    ], strategy.seen

    # The pull-side context after the run says the same.
    ctx = strategy.ctx(sym)
    assert (ctx.best_bid, ctx.best_ask, ctx.mid_price) == (100.4, 100.6, 100.5), ctx
    assert ctx.last_touch_ns == T0 + 3 * SECOND
    assert ctx.last_update_ns == T0 + 4 * SECOND
    print("ok")


if __name__ == "__main__":
    main()

The tape under docs/examples/data/touch_tape is synthetic, written for this page. Its shape is what a Hyperliquid recording with the bbo channel on looks like between two depth snapshots.

Mark against the touch

mid() on the C++ context is the depth book's mid and last moved on a depth frame. touchMid() also moves on top-of-book frames, so between depth frames it is the fresher mark. A strategy that quotes off the mid wants the second one, and the same bookkeeping as above to know whether it moved:

#include "lrvx/strategy/strategy.h"

using namespace lrvx;

class QuoteOffTheTouch : public lrvx::Strategy
{
 public:
  using Strategy::Strategy;

 protected:
  void onSymbolBook(SymbolContext& c, const BookUpdateEvent&) override
  {
    // A depth frame: the book and the touch were both written just now.
    _lastBookNs = c.lastUpdateNs;
  }

  void onSymbolTrade(SymbolContext& c, const TradeEvent& ev) override
  {
    // c.mid() last moved on a depth frame. c.touchMid() also moves on
    // TOP_OF_BOOK frames, which the depth book ignores.
    auto mark = c.touchMid();
    if (!mark)
    {
      return;  // one side of the touch is empty
    }
    // A top arrived after the last depth frame this strategy was shown.
    const bool touchMoved = c.lastTouchNs > _lastBookNs;
    if (touchMoved && c.position.raw() == 0)
    {
      emitLimitBuy(ev.trade.symbol, *mark, lrvx::Quantity::fromDouble(0.01));
    }
  }

 private:
  int64_t _lastBookNs{0};
};

In Python, Node and Codon the context's mid already is the touch mid, so the comparison is the only extra step. A strategy that should requote on the move itself, not on its next trade, does the same work in onSymbolTouch and needs no stamp bookkeeping.

Replay a tape that carries tops

Nothing special: BacktestRunner.run_tape delivers a top the way live did. The strategy's touch and last_touch_ns move, on_touch fires if the touch changed, and the simulated venue moves its own touch while keeping the depth from the last snapshot, so a market order fills at the touch the strategy saw rather than at the stale depth frame.

Record tops

A recording made through the Hyperliquid connector with subscribeBbo on (the default), through Bybit or Bitget with their subscribeBbo on (off by default), or through a binding-side feed that calls on_book_top (the ccxt adapter's bbo stream does), carries tops as frame type 6; so does a DataWriter given update_type=2. EventTypeStatsAggregator counts them in its book_tops column, and metadata.json says has_book_tops. Custom recorder hooks in Python and Node receive snapshots and deltas through their bool-shaped book callback and tops through on_book_top, one (price, qty) or None per side (onBookTop in Node, one { price, qty } or null per side); a hook that does not define it skips tops. A C recorder hook receives the byte 2.

See also