Package com.quantfinlib.microstructure
MarketImpactModel (square-root law
+ Almgren-Chriss temporary/permanent decomposition),
AlmgrenChriss (closed-form optimal
execution trajectories on the cost/risk frontier),
QueueModel (fill probability from
queue position and latency advantage),
TransactionCostAnalyzer
(implementation shortfall, slippage vs VWAP, effective spread per fill),
TickSizeSchedule (banded price
grids) and Auction (call uncross).
Streaming, hot-lane (zero allocation per event):
SignalEngine — the unified
multi-symbol signal engine for equities and FX (imbalance, microprice,
volatility, liquidity, momentum, weighted composite) — built on
FlowSignals (Cont-Kukanov OFI,
queue and trade imbalance) with
CircuitBreakers (LULD bands and
limit states, market-wide halt levels) guarding the equity side.
Quant models feeding the execution algos
(execution.BenchmarkExecutor.MarketState):
VolumeCurve (dynamic intraday
volume prediction — learned profile + intraday rescale, the live VWAP
curve), QueuePositionEstimator
(L2 queue position via pro-rata cancel attribution),
HiddenLiquidityDetector
(lit-tape iceberg / hidden-size inference),
SpreadForecaster (time-of-day
spread baseline + mean-reverting deviation),
VolatilityCurve (intraday vol
seasonality; its regime() is the normalized volatility input the
benchmark executor documents),
TradeClassifier (Lee-Ready
aggressor inference for feeds without an aggressor flag) and
FillProbabilityModel
(touch × queue passive-fill probability). Their batch/ML siblings
live in ml (volatility forecasting, market-impact prediction,
intraday liquidity) and pricing.FairValueEngine (microprice
short-term alpha).
Adaptive layer on top of the models:
OnlineAlphaLearner (online
ridge-SGD from the SignalEngine ingredients to next-interval returns,
gated by a prequential out-of-sample IC so a learner that found noise
emits no signal),
LeadLagEstimator (streaming
cross-asset lead-lag correlation — EURUSD leads EURJPY, futures lead
cash — with a regression prediction at the best lag) and
DayTypeProfiles (per-day-type
seasonality: expiry days, half days and FX fixing days each learn their
own volume/vol/spread curves) and
EwmaCovariance (streaming
RiskMetrics-style covariance matrix — marginal basket risk for
execution.PortfolioExecutor, live min-variance hedge ratios),
KylesLambda (impact LEARNED from
the tape: streaming Δp-on-signed-flow regression, the live producer for
MarketState.impactBps),
JumpRobustVolatility (bipower
variation: a headline print is a jump, not a volatility regime) and
ClosingAuctionModel
(auction share + imbalance-tilted reserve — shipped as a
documented-contract structure, see its javadoc caveat),
HawkesIntensity (self-exciting
event intensity: activity breeds activity, with stability enforced via
the branching ratio) and
AlphaEnsemble (IC-weighted blend
of alpha components — per-component prequential trust, confidence-sized
output).
Flow toxicity, mean reversion, and bar-only liquidity:
Vpin (volume-synchronized
probability of informed trading — the market maker's when-to-widen
gauge, bucketed in VOLUME time),
OrnsteinUhlenbeck (the pairs
desk's engine: κ/θ/σ by exact AR(1) mapping, half-life, stationary
z-score — and it REFUSES a series with no in-sample mean reversion)
and LiquidityMeasures (Roll's
bounce-implied spread — NaN, not zero, when the signature is absent;
Corwin-Schultz high-low spread; Amihud illiquidity) for every market
where you have bars but no quotes. Regime and relationship tracking:
VarianceRatio (Lo-MacKinlay:
trending, mean-reverting or random walk — the question that comes
before every strategy choice) and
KalmanBeta (time-varying
hedge ratios by Kalman filter — a static OLS averages the drift
away; the filter is AT the current β and knows its own
uncertainty).
-
ClassDescriptionAlmgren-Chriss (2000) optimal execution: the trading trajectory that minimizes
E[cost] + λ·Var[cost]when liquidating X shares over a horizon, trading off temporary impact (fast execution is expensive) against price risk (slow execution is risky).The optimal schedule:holdings[j]is the position after interval j (holdings[0] = X, holdings[N] = 0);trades[j]is sold in interval j+1.IC-weighted alpha ensemble — the layer above the individual signals.A call auction (open/close/volatility uncross): orders accumulate without trading, then a single clearing price executes the maximum matchable volume — the mechanism behind exchange opens, the close every benchmark-tracking strategy trades, and LULD/volatility-halt reopenings.Auction outcome: clearing price, matched volume, and leftover imbalance.US-equities trading safeguards, styled after the SEC's Limit Up-Limit Down plan and the market-wide circuit-breaker rule (not certified implementations — the regulatory texts govern): LULD price bands (CircuitBreakers.luldBandPct(double, boolean, boolean),CircuitBreakers.Luld) — per-symbol bands around a reference price; quoting at a band edge enters a limit state, and a limit state that persists 15 seconds becomes a 5-minute trading pause; Market-wide circuit breakers (CircuitBreakers.MarketWide) — S&P 500 declines of 7% / 13% halt the market for 15 minutes (each at most once per day, and not after 15:25), and 20% halts for the day.MWCB halt decision.The LULD limit-state machine for one symbol: enters a limit state when the inside quote pins a band edge, converts to a 5-minute pause when the limit state persists 15 seconds, and exits the pause after it elapses.LULD per-symbol state.Market-wide circuit-breaker day state: feed it the S&P 500 decline from the prior close and the time of day; it applies the once-per-day and not-after-15:25 rules for Levels 1 and 2.Closing-auction participation model.Day-type-aware seasonality: not every trading day has the same shape.Streaming EWMA covariance matrix — the multi-asset risk picture that single-symbol volatility cannot see.A matched trade (fill) for TCA and venue analytics.Passive-fill probability for a limit order resting AWAY from the touch — the placement questionQueueModelalone can't answer.Streaming order-flow signals for short-horizon execution decisions: the three imbalances an execution engine reads before crossing a spread — cross-asset (equity ticks or raw FX rates; see the two onQuote entry points) — Order-flow imbalance (OFI) — Cont/Kukanov/Stoikov best-level formulation: a bid price/size increase or ask decrease is buying pressure; the mirror is selling pressure.Self-exciting (Hawkes) event intensity — the model behind the trader's observation that "activity breeds activity": one trade raises the probability of the next, so order flow arrives in bursts, not as a steady Poisson drizzle.Hidden-liquidity / iceberg detection from the lit tape.Jump-robust streaming volatility.TIME-VARYING regression by Kalman filter — the pairs desk's upgrade over a static OLS hedge ratio.Kyle's lambda — market impact LEARNED from the tape instead of assumed from a formula.Streaming cross-asset lead-lag estimation: does instrument A's return now predict instrument B's return a few intervals from now?Liquidity estimated from BARS ALONE — the estimators for every market where you have prices but no quotes: history before your tick capture started, less-developed markets, bonds marked once a day, or a 20-year backtest that would otherwise pretend spreads were zero.Temporary / permanent market impact models for large trades, parameterized by average daily volume (ADV) and daily volatility: Square-root law (empirical standard):impact = Y * sigma_daily * sqrt(Q / ADV). Almgren-Chriss style decomposition: linear temporary impact in participation rate and linear permanent impact in size, with the expected cost of an execution scheduleE[cost] = permanent/2 + temporary. All results in basis points of the arrival price.Online alpha-weight learning: upgradesSignalEngine.alpha(int)'s fixed composite weights to weights learned from realized returns — an online ridge regression (SGD with L2 shrinkage) from the four dimensionless signal ingredients (queue imbalance, trade imbalance, normalized OFI, momentum-Z) to the next-interval return.Ornstein-Uhlenbeck estimation — the mean-reversion engine under every pairs trade and basis position:dx = κ(θ − x)dt + σ dW.Queue positioning and priority analytics: how position in the price-time queue — and small latency differences in reaching it — translate into fill probability.Queue position estimation from L2 data — for when you don't have the L3 feed thatmarketdata.L3BookBuilderneeds to track position exactly.The unified streaming signal engine: one multi-symbol, hot-lane component that turns raw top-of-book quotes and trade prints into the five signal families a trading decision reads — for equities and FX alike (prices are doubles; equity integer ticks are exact in a double, FX rates feed in directly): Imbalance — order-flow imbalance (Cont-Kukanov-Stoikov, time-decayed), inside queue imbalance and signed trade-flow imbalance, via a per-symbolFlowSignals; Fair value — the size-weighted microprice (FairValueEngine.microprice); Volatility — a streaming EWMA realized-variance rate over irregular tick arrivals: per valid mid change,r² / dtenters a time-decayed average, andSignalEngine.volPerSqrtSecond(int)is its square root — multiply by√(seconds per year)to annualize externally; Liquidity — time-decayed EWMAs of the absolute spread (andSignalEngine.spreadBps(int)of mid), displayed top-of-book depth, and quote arrival intensity (from the decayed inter-quote gap); Momentum — two time-aware EMAs of the mid (decay by elapsed time, not by update count — constant-step EMAs likeindicators.StreamingIndicatorsmis-weight irregular tick arrivals), read as the normalized fast/slow gap(fast − slow)/mid.Half-lives (all in nanos) for the decayed estimators, plus the composite weights.Short-term spread prediction.Price-banded tick sizes — the MiFID II / ESMA RTS 11 regime where the minimum price increment depends on the instrument's price (and liquidity band), rather than being one flat number.Accumulates (floor price, tick) bands; floors may arrive in any order.Trade aggressor classification (Lee-Ready, 1991): the missing glue for feeds that print trades without saying who initiated.Transaction Cost Analysis: benchmarks matched trades against the arrival mid, the interval market VWAP, and the prevailing mid at each fill (effective spread).The Lo-MacKinlay VARIANCE RATIO test — the question that comes before every strategy choice: is this series trending, mean-reverting, or a random walk?Intraday volatility seasonality — the third leg of the seasonality trio besideVolumeCurveandSpreadForecaster: volatility is U-shaped through an equity day (wild open, quiet lunch, busy close) and session-humped through an FX day (London open, NY overlap), so "is the market volatile right now?"Dynamic intraday volume prediction — the model that makes a VWAP schedule live instead of historical.VPIN — Volume-synchronized Probability of INformed trading (Easley, López de Prado & O'Hara): the flow-toxicity gauge a market maker watches to decide when quoting is no longer a business.