UndercuttingActivitySignal builds five-minute undercutting features from observed
NBBO/trade events, or accepts equivalent enriched intervals, and returns a Python
integer: -1 short, 0 neutral, 1 long. These are desired stances. Sizing,
orders, positions and broker execution are outside the instrument. All feature
construction, calibration and decisions run in C++ through nanobind.
Research and adaptations
Barardehi, Dixon and Liu, Detecting Informed Trading Risk from Undercutting Activity, first published June 1, 2026, Journal of Finance 81(4), 2109–2164, Sections II.B–D and III and footnote 21, motivates the unsigned risk measure. Unexpectedly low QID indicates higher informed trading risk. The denominator is the prior standard deviation of raw QID, not residuals. Footnote 21 uses treated-day/control-day observations for intraday normalization. Our preceding-quarter, five-minute, past-only calibration is a causal extension of that event study.
The Internet Appendix and replication archive were requested during implementation; both returned HTTP 403. The supplement's cluster and side-matching implementation could not be verified. The two explicit variants below therefore remain methodological sensitivity choices, not claimed replications of unpublished details.
The directional composition is experimental. Its hypothesis is that persistent flow is more informative when liquidity suppliers retreat, and more reversible when they compete unusually actively. The paper does not establish this trading rule. This repository has no chronological market-data profitability evaluation for this instrument.
Features and decision rule
For each completed interval, pool both quote sides:
I = bid_improvements + ask_improvements
D = bid_deteriorations + ask_deteriorations
qid = (I - D) / (I + D)
spread = spread_time_integral / valid_quote_duration_ns
expected_qid = intercept + slope * log(spread)
risk = -(qid - expected_qid) / prior_raw_qid_sample_std
flow = (buy_volume - sell_volume) / (buy_volume + sell_volume)
r = midpoint_end / midpoint_start - 1
Relative spread is (ask - bid) / midpoint, in ratio units, not basis points or
percentage points. Its integral has units ratio × nanoseconds. Average first,
then take the logarithm. Sizes never contribute to revision counts. Every bid
increase and ask decrease contributes one improvement, whatever its distance.
With valid risk, midpoint endpoints, classified volume and fraction, a neutral
instrument requires abs(flow) >= entry_flow and flow * r > 0. It enters
sign(flow) when risk >= continuation_entry, or -sign(flow) when
risk <= reversal_entry. Otherwise it stays neutral.
Continuation holds only while risk > continuation_exit; reversal holds only
while risk < reversal_exit. Both require valid directional data, the original
dominant flow sign, and abs(flow) >= exit_flow. Return alignment is an entry
condition; a valid but flat/opposing return alone does not exit a held stance.
Entry age is zero on decision k, one on k+1, two on k+2, and exits on k+3
by default: fifteen minutes after entry availability with punctual five-minute
clock decisions. Exits consume a decision; they cannot re-enter until a later
interval. Between decisions, including while accumulating an invalid interval,
the previous stance is returned. A session reset explicitly clears the stance.
Tick API and ordering
import rtta
s = rtta.UndercuttingActivitySignal(symbol="AAPL")
t = 1775000000000000000 # integer epoch nanoseconds
assert type(s.update_quote(t, 100.00, 100.02, 200, 100)) is int
s.update_trade(t + 1, 100.02, 50)
s.advance(t + 2, 1, 100.00, 100.03) # state-only; returns None
stance = s.last() # always int
stance = s.advance_time(((t // 300_000_000_000) + 1) * 300_000_000_000)
d = s.diagnostics # independent, read-only snapshot
The common event API is
update(timestamp_ns, event_type=0, value1=0, value2=0, bid_size=1,
ask_size=1, valid=True, sequence=-1). advance(...) has identical arguments and
returns None. Convenience methods are update_quote(timestamp_ns, bid, ask,
bid_size=1, ask_size=1, valid=True, sequence=-1) and
update_trade(timestamp_ns, price, volume, valid=True, sequence=-1).
| Event type | Meaning of values |
|---|---|
0 |
Clock/watermark; values ignored |
1 |
NBBO bid and ask; sizes must be positive |
2 |
Eligible trade price and volume |
3 |
Explicit feed gap; values ignored |
Timestamps are nonnegative signed 64-bit integer nanoseconds, with room
reserved at the maximum for calendar calculations. Decreasing timestamps raise
ValueError. Equal timestamps retain caller order. Floats are rejected, including
in native batch timestamp columns. Supply causal SIP or actual arrival timestamps,
not a participant-time resorting of already observed messages. One instance owns
one symbol; upstream adapters must route and filter events correctly.
Intervals are UTC epoch-aligned, half-open [start, end). The previous valid
quote is integrated over elapsed time, splitting at every boundary before
applying a new event. The start midpoint is the carried quote (or the first quote
observed exactly at start); the end midpoint is the last valid quote before end.
A late first quote leaves the start midpoint unavailable. A quote exactly at end
contributes revisions to the next interval. Its midpoint cannot change the
published preceding interval.
A deterioration is assigned to the interval containing the quote transition,
even if the candidate trade is in the preceding interval. Valid quotes, classifier
state and unexpired candidates carry across ordinary interval and UTC midnight
boundaries. No delayed matching rewrites published features. advance_time(t)
(or update(t)/advance(t)) closes every elapsed interval using only observed
state. Actual availability is t, not the nominal boundary, when the clock is
late. last_interval and diagnostics retain the most recent completed interval;
advance at each boundary to record every decision separately. There is no
unbounded completed-interval archive in the instrument.
Matching, classification and bad data
strict_later=True requires trade_time < quote_time <= trade_time + match_window_ns.
Set match_window_ns=1_000_000 for the one-millisecond sensitivity; default is
10,000,000. strict_later=False also allows an already observed trade with the
same timestamp; an unobserved later trade is never used.
side_first(default): a classified sell can match its first bid deterioration; a classified buy can match its first ask deterioration. Opposite-side deteriorations do not consume that candidate. Unknown trades do not match.global_first: any eligible trade, including unknown direction, can match the first subsequent quote event that deteriorates either side. If both sides deteriorate in that event, each contributes one count.
For either variant, a side transition counts at most once. All eligible clustered candidates matched by that first event are consumed together; none can attribute another deterioration. Candidates at equal timestamps remain pending in strict mode. Candidates expire when their age exceeds the configured window. Candidate memory is proportional to eligible trades in that window; each is inserted and removed once.
The classifier shares the existing native SpreadFeatures causal midpoint rule:
price above/below the last valid observed midpoint is buy/sell, including trades
inside the spread. A midpoint trade uses the price change from the preceding
eligible trade. A flat midpoint trade or a trade without a valid NBBO is unknown;
zero ticks do not inherit a nonzero sign. No future quote is consulted. Unknown
volume is retained in the classified-fraction denominator.
Locked/crossed books, nonpositive or nonfinite prices or sizes, and valid=False
quotes invalidate the book and that interval. Explicit gaps do the same. A quote
is fresh through age stale_quote_ns; beyond it integration stops, the interval
is invalid, and candidates/classifier state are cleared. Recovery establishes a
new baseline without counting revisions across the unknown segment. This is
conservative: any detected invalid segment invalidates its interval even if
coverage later exceeds the threshold. Trades with invalid price/volume or
valid=False invalidate the interval; any usable positive volume becomes unknown.
Optional nonnegative sequence IDs are monotone per quote/trade stream. A
repeat of the last accepted ID is ignored after advancing the clock; it neither
adds volume nor refreshes a quote. Lower IDs raise. Unnumbered events (-1) are
all observed; identical prints may be distinct trades. Equal-price/size quotes
add no revisions. Sequence jumps do not automatically imply missing data: call
event type 3 when the adapter knows there was a gap.
reset_session(timestamp_ns) drops partial features, quotes, candidate/classifier
state, duplicate IDs and the stance, retaining quarterly training and calibration.
Advance to the known session close first to publish the closing interval. Reset
at the next open to avoid synthesizing overnight decisions. The open establishes
the interval clock even before the first tick; initial watermarks also allow later
aggregate ingestion. reset() additionally
clears all training, snapshots, ingestion mode and ordering history. Sessions,
exchange holidays, early closes, corrections and condition eligibility are adapter
responsibilities, reflected in filter_policy.
Equivalent enriched intervals
update_interval(record) accepts an UndercuttingActivityInterval, a mapping,
or an object with all the following attributes. update(interval) and
advance(interval) accept the typed interval. advance_interval(record) is the
state-only variant. last_interval from a tick instance is directly ingestible by
an identically configured aggregate instance. Mixing tick and aggregate modes
requires a full reset().
| Required fields | Type / meaning |
|---|---|
interval_start_ns, interval_end_ns, available_ns |
Integers; one aligned full interval, availability at or after end |
bid_improvements, ask_improvements |
Separate nonnegative integer revision counts |
bid_deteriorations, ask_deteriorations |
Separate nonnegative integer trade-attributed revision counts |
spread_time_integral |
Relative spread × ns; NaN means unavailable |
valid_quote_duration_ns |
Integer known-quote duration, between zero and interval length |
buy_volume, sell_volume, unknown_volume |
Finite nonnegative eligible volume |
midpoint_start, midpoint_end |
Positive boundary midpoints, or NaN when unavailable |
valid |
Explicit validity flag |
symbol, policy_id |
Exact matches for the receiving instance |
Structural errors, missing fields, overlapping/published intervals, decreasing
availability, symbol/policy mismatches and floating-point integer fields raise.
Missing statistics expressed as NaN yield unready neutral decisions. Ordinary
OHLCV is rejected; candle direction cannot reconstruct these statistics.
Skipped aggregate intervals become invalid decisions with the new observation's
actual availability; aggregate watermarks also seal elapsed missing intervals.
Use reset_session to avoid treating scheduled overnight closures as missing
intraday data. Supplying a matching policy identifier is an explicit assertion
that the upstream builder used the same semantics; the instrument cannot audit
unseen raw events.
Calibration and defaults
OLS uses completed observations in the immediately preceding UTC calendar
quarter, independently per instance/symbol, at the same interval frequency and
feature filter policy. It uses numerically centered online moments and the raw
QID sample standard deviation (ddof=1). Only feature-valid observations
available by the next quarter boundary train that next quarter. Risk feature
filters are activity, quote validity, coverage and spread; volume/return/entry
filters do not select the QID regression sample. No winsorization is applied.
Coefficients freeze for the scoring quarter. An absent preceding quarter does
not fall back to an older calibration.
| Parameter | Default |
|---|---|
interval_ns |
300_000_000_000 (must divide a UTC day) |
match_window_ns |
10_000_000 |
matching, strict_later |
"side_first", True |
stale_quote_ns |
60_000_000_000 |
min_calibration_observations |
30 (minimum configurable value: 3) |
min_revisions |
20 |
min_quote_coverage |
0.80 |
min_classified_fraction, min_classified_volume |
0.50, 1.0 |
entry_flow, exit_flow |
0.20, 0.10 |
continuation_entry, reversal_entry |
1.0, -1.0 |
continuation_exit, reversal_exit |
0.25, -0.25 |
max_holding_intervals |
3 |
variance_epsilon |
1e-12 (minimum variance, for both QID and log spread) |
symbol, filter_policy |
"", "valid_nbbo_v1" |
These thresholds, staleness and matching choices are research parameters. QID,
spread or calibration unavailability, zero activity, insufficient observations,
singular log-spread design or negligible QID variance produce integer 0 and
NaN risk, never a fabricated neutral risk value.
External fits use load_calibration(UndercuttingActivityCalibration(...)) before
the target quarter's first decision. Required snapshot fields are symbol,
scoring_quarter_start_ns, training_start_ns, training_end_ns,
training_cutoff_ns, available_ns, observations, intercept, slope,
qid_std, log_spread_variance, interval_ns, and policy_id. Training bounds
must exactly describe the preceding quarter (exclusive end). Cutoff means latest
training-observation availability and must be after training start and no later
than training end. Snapshot availability must be at or after cutoff and no later
than scoring-quarter start. Counts, finite coefficients, nondegenerate variances,
symbol, frequency and s.policy_id are validated. One future snapshot may be
staged; replacement for the same quarter is rejected. As with any supplied fit,
this validates metadata, not the truth of the external training claims.
calibration returns the active read-only snapshot. diagnostics exposes QID,
expected QID, risk, flow, midpoint return, relative spread, coverage, classified
fraction, all counts and volumes, interval/availability timestamps, calibration
cutoff/count, regime, entry age, signal, decision count, reason, risk_ready, and
ready. Readiness indicates usable data/calibration, not that entry thresholds
are met. Snapshot reads do not mutate state.
Batch, replay and execution example
# C-contiguous 1-D columns: timestamps AND event types must be np.int64.
# Both value columns must share np.float64 or np.float32 dtype.
stances = s.batch(timestamp_ns, event_type, value1, value2) # np.int64 array
# Each of these consumes state, like repeated update/advance calls:
stances = s.replay_update_outputs(timestamp_ns, event_type, value1, value2)
checksum = s.replay_update(timestamp_ns, event_type, value1, value2) # float sum
checksum = s.replay_advance(timestamp_ns, event_type, value1, value2)
Use separate/reset instances to compare paths. Record batches accept tick tuples,
mappings, attribute records, or fully enriched intervals. Tick record keys match
update; optional fields carry sizes/validity/sequence IDs. Four-column arrays
use the default positive sizes and no sequence IDs; use rich records for those
fields. DataFrame batches preserve integral columns without a mixed-row float
conversion. Aggregate record batches and both checksum replay methods use the
same native interval transition. Replay checksums follow RTTA's float convention;
all stances, including batch/output replay elements, are integers.
The massive-speedup example merges ordered SIP feeds and maintains independent symbol state across sessions and quarters. It simulates punctual clock events, configurable market-order latency, later ask/bid fills, fees and adverse slippage. Pending orders contain only submission/due timestamps and target shares, never future prices. Equal-time sequence comparability, condition allowlists, full fills, no depth constraint, no endogenous impact and available borrow are explicit assumptions. Unfilled close orders carry to a later observed quote; open positions are reported. The output is execution plumbing and cash flow, not a profitability claim.
The demo consumes StockQuoteDatabase and StockTradeDatabase through their
iterator interfaces, feeding each record into the incremental quote/trade API.
Use --symbol AAPL, --symbols AAPL MSFT, or --symbols-file symbols.txt.
As in the other trading examples, the CLI is long-only unless --allow-short
is set. JSON-lines output includes readiness reasons, named buy/sell fills,
daily and final execution summaries, and realized P&L with fees booked when paid.
--quiet suppresses individual decisions and fills. Include the preceding
calendar quarter in --start-date/--stop-date for automatic calibration.
See validation and latency measurements for reproducible checks and measured limitations.
