Act VI · Market Microstructure
Part 36 of 43The Limit Order Book
With a bid at 100.00 for five hundred and an offer at 100.01 for one hundred, where is fair value?
Not at the midpoint. The thin side is more likely to be consumed first, so the next move is probably up, and the part turns that into numbers on a real order book. Queues are modelled as they are: orders arrive, cancel and trade at rates that depend on the state of the book, and events cause further events, a self-exciting process with most of its activity endogenous. Order-flow imbalance explains short-horizon price changes almost linearly. The microprice corrects the midpoint for the state of the queues. A network is trained on the book and compared with the linear model, a simulator of the book is fitted, and an order is placed in its queue to see what a place in line is worth.
What you need. Parts 5 and 35.
What you will be able to do
Undergraduate
- Read a limit order book: levels, queues, market and limit orders, price-time priority.
Master's
- Compute order-flow imbalance and regress price changes on it; estimate the probability the next move is up from queue sizes.
- Fit a Hawkes process to order arrivals and interpret its branching ratio; fit and simulate a queue-reactive model.
PhD
- Prove the microprice theorem for a finite-state Markov book (the adjustment as the solution of a Poisson equation) and test its Markov assumption on data.
Industry
- Score a short-horizon signal against the spread and fees it must pay; value queue position.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 12 min · Master's 45 min · PhD 59 min · Industry 17 min.
- 0Where is fair value?Undergraduate3 min
- 1The bookUndergraduate4 min
- 2Queues and the next tickMaster's4 min
- 3Events that cause eventsMaster's5 min
- 4Order-flow imbalanceMaster's4 min
- 5The micropriceMaster's5 min
- 6Deep order booksPhD6 min
- 7A book of our ownMaster's5 min
- 8Trading in the queueMaster's5 min
- 9Rule 36: score the book against the spreadIndustry5 min
- For the researcher: the microprice theoremPhD8 min
- Recap, desk questions, problemsAll tracks5 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Reading · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Where is fair value?Undergraduate3 min
The limit order book: displayed queues of resting bids and offers on many electronic venues, and what they can tell us about subsequent prices. Matching rules, hidden liquidity and the chosen observation clock matter.
A stipulated interview book. Five hundred shares bid at a hundred dollars, one hundred offered at a hundred and one cent. Calculate three different objects. The quote midpoint is a hundred and half a cent. The opposite-size weighted midpoint is a hundred point zero zero eight three. Under independent, equal-variance, driftless Brownian queues and a half-cent mid move at depletion, the expected next midpoint is about a hundred point zero zero eight seven. These are conditional model summaries. None alone identifies fundamental value or an executable price. Later we test a many-move estimator on Bitcoin.
Three measurements from this narrow sample. The observed next-move up frequency rises from 16 to 86 percent across imbalance buckets. The fitted many-move adjustment reaches 25 ticks, while a horizon-specific table reduces mean ten-second squared error by 4 percent on two held-out days. Same-interval order-flow imbalance accounts for 45 percent of variance in this displayed ten-second regression; this is association, not a causal price response or a forecast. Direction accuracy conditional on a nonzero future move is 84 percent for the network and 87 for the linear rule. These scores do not include flat targets and do not measure net trading profit.
Why it matters, even to a slow investor. Every strategy in this series trades through a book: the monthly factor portfolios still buy at the offer and sell at the bid, and Part thirty-one's costs were the book's prices. The fastest desks live in it, earning or losing fractions of a tick millions of times a day. And it is where models meet reality fastest: a fair price, a forecast or a simulator can be tested on millions of observations within days. That makes the book a laboratory for honest research, and this part uses it as one.
Where this sits. Part thirty-five asked who trades with whom. This part opens the mechanism they trade through: the order book, with its queues, ticks and cancellations. It builds the House's order-book simulator, which execution in Part thirty-seven and market making in Part thirty-eight will use.
Twenty years of the field. Fabrizio Lillo and Doyne Farmer found that order signs have long memory in 2004; Rama Cont and co-authors modelled queues in 2010; and the self-exciting arrivals of orders were found to be close to critical. Then the order-flow imbalance, the queue-reactive model, and Sasha Stoikov's microprice. And deep learning: DeepLOB, universal features, generative models of the book, and a benchmark that tested how well any of it generalises.
The plan: the book itself, measured on Bitcoin's perpetual future; queues and the next tick, in a model and in the data; the clustering of events and the memory of order signs; order-flow imbalance; the microprice, fitted and tested; deep models of the book, and a generative book of the House's own with a scorecard; trading in the queue; and the microprice theorem, proved.
In the House, the data desk gains the best quotes on a hundred-millisecond grid, and the research desk an order-book simulator: the laboratory in which the next two parts will trade.
1The bookUndergraduate4 min
A displayed limit order book collects standing bids and offers. We use a price-time-priority example, while actual venue matching, hidden orders and order types can differ. The public feed in this part contains best prices and sizes, not every order or every depth level.
The rules. A limit order rests at a price until it is filled or cancelled: its owner supplies liquidity. A market order trades now against the best resting orders, and pays the spread. Priority: best price first, and at the same price, first come first served. So a place in the queue is an asset. And the tick, the smallest price step: on Bitcoin's perpetual future, ten cents, about four hundredths of a basis point.
The picture. Offers above, bids below, each price with the size waiting there. The gap between the best bid and the best offer is the spread; on a liquid market it is usually one tick, so the price cannot get any closer, and the action is in the sizes of the two best queues.
Four useful mechanisms. A displayed limit order can add size at a price. A cancellation can remove resting size. An aggressive order trades against resting liquidity. Depletion can move the best quote, but so can a new limit order inside a wider spread. The hundred-millisecond snapshots combine these events; their net size change does not identify each underlying message.
Four public archive days in May twenty twenty-three. The displayed hours count hundred-millisecond grid positions after the first available quote, including carried-forward observations; they are not an audit of uninterrupted message coverage. The initial archive day is partial. The one-tick spread dominates this sample, with weekday update rate about 133 per second. May sixteenth and seventeenth fit the models; the twentieth and twenty-first form a short weekend test. Carry-forward values, gaps and that weekday-to-weekend shift matter.
One minute of it. The best bid and offer, ten cents apart, step together. Below, the two best queues, the bid up and the offer down. Watch a queue drain toward zero just before the price steps through it. That race is the whole game of this part.
Activity through a day. Even on a Saturday the book updates dozens of times a second at every hour, peaking around 18:00 UTC. Crypto never closes, but it does sleep a little.
Order types depend on venue rules. A marketable limit order can immediately take liquidity; a nonmarketable remainder may rest subject to its instructions. A market order accepts available prices without a limit-price guarantee. Post-only instructions prevent taking, often by rejection or venue-specific repricing. Immediate-or-cancel allows partial execution and cancels the remainder. Icebergs display a portion of hidden reserve, with replenishment priority defined by the venue. A stop may trigger a market or a limit order according to its type. These instructions can affect price dynamics, but the best-quote feed does not identify each hidden instruction.
Why the tick matters. When the tick is wide compared with the spread traders would accept and with the price's moves, the spread sits at one tick, the queues are long, and the price moves rarely, one tick at a time: priority is everything. When the tick is tiny, the price moves many ticks at once and traders compete on price. The American half-cent tick of Part thirty-five was aimed at the first kind of market. Bitcoin's perpetual is both at once: a one-tick spread, like the first, but when its mid changes between two snapshots a tenth of a second apart, the median jump is 8 ticks. Mathieu Rosenbaum and Khalil Dayri measured tick size by exactly this behaviour of the price, and by that measure the tick here is small. Chapter five shows why that matters.
Assume deterministic fluid rates: five bitcoin ahead, aggressive trades at point two bitcoin a second and cancellations from ahead at point one. Your own one-bitcoin order is not cancelled. Compute the time to reach the front and then the total fill time. This is stipulated fluid arithmetic, not the expected hitting time of a random queue.
2Queues and the next tickMaster's4 min
With a one-tick spread, the price moves when one of the two best queues runs out. So the next move is a race between the queues. Rama Cont and Adrien de Larrard turned that race into a formula.
The race. Two best queues, bid and offer. Each grows with new orders and shrinks with cancellations and trades, a birth-death process in Rama Cont, Sasha Stoikov and Rishi Talreja's model; with balanced rates, a random walk, and in the limit a Brownian motion. The price ticks up when the offer runs out first.
A picture makes the stipulated diffusion solvable. Plot bid and offer queue sizes as one point in a quadrant, with equal coordinate scales. The yellow line is a fixed Euler illustration of independent driftless Brownian queues. Its last discrete segment is interpolated to the first boundary crossing. Reaching the floor depletes the offer; reaching the wall depletes the bid. For the specified equal-variance diffusion, the bounded harmonic exit probability depends on the starting angle, not on distance from the origin.
A particular diffusion approximation. For two independent, driftless Brownian queues with equal variance rates, the bounded harmonic solution in a quadrant is linear in the polar angle. It equals one on the offer-depletion boundary and zero on the bid-depletion boundary. The starting angle is the arctangent of offer size over bid size. Hence the up probability is one minus two over pi times that angle. This formula is scale invariant. Unequal volatilities, correlation, drift or queue-dependent rates generally change it; it is not the general solution of every Poisson queue model.
Distinguish the models. Independent Poisson additions and removals define a birth-death queue model. A balanced heavy-traffic limit with equal variance rates leads to the simple Brownian quadrant formula just shown. A chosen regeneration rule redraws queues after depletion; reset laws can depend on direction, and can create serial dependence. Driftless diffusive prices require the relevant balance, regeneration and moment conditions. Poisson arrivals alone do not make the price an independent symmetric random walk.
Against the data, on the two test days. The probability that the next move is up, by imbalance: from 16 percent when the bid is tiny to 86 percent when the offer is. The model has the right shape and the right center, but it is too steep at the edges: real markets are less certain than the random-walk race. A straight line, probability equals imbalance, lies in between.
Possible reasons the observed curve differs from the simple diffusion formula. Size-dependent refill and removal rates can alter depletion probabilities. Hidden liquidity and aggregation can make displayed queues an incomplete state. Recent flow and unobserved information may also matter. This comparison does not identify which mechanism caused the discrepancy, and a short offer does not establish informed selling or illegal intent.
A richer baseline. Huang, Lehalle and Rosenbaum let event intensities depend on queue state. Our simplified grid implementation counts net size increases and decreases per occupied state; it does not recover separate message-level addition, trade and cancellation intensities. It produces a Markov model of the full simulated queue state. A coarser summary, such as ten imbalance buckets, need not itself be Markov. We retain its scorecard instead of treating a fitted rate as validation.
Take independent driftless Brownian queues with equal variance rates. The bid starts at nine lots and the offer at three. Calculate the displayed up probability and compare it with bid size divided by total size. Then double both queue sizes. Explain which quantities remain the same and what the probability formula does not say about waiting time.
3Events that cause eventsMaster's5 min
Orders do not arrive like raindrops. They come in bursts, and buy orders follow buy orders for minutes on end. Two facts, measured, and what they imply.
A positive linear exponential Hawkes model. Its conditional intensity is a positive background rate plus decaying contributions from past events. With nonnegative alpha and positive beta, the kernel integral n is alpha over beta. In the model's Poisson-cluster representation it is the expected number of direct offspring. For a stationary version with n below one, the mean rate is mu over one minus n and the latent offspring share is n. A fitted branching ratio is not an observed causal fraction of traders reacting to one another.
The fitted hour contains 22,930 distinct rounded-millisecond arrival times after deduplication. Its estimated branching ratio is 0.68, a model parameter rather than an identified reaction fraction. The in-sample log likelihood exceeds the Poisson fit by 1,548; the Hawkes model also has more parameters. The displayed rescaled-gap KS statistic is descriptive. The same events estimate the parameters and test the fit, and the gaps may remain dependent. No calibrated goodness-of-fit p-value or causal attribution follows from this statistic alone.
Three distinct claims. Hardiman, Bercot and Bouchaud estimated high branching ratios under long-memory Hawkes specifications on index futures. The estimate depends on kernel, sample window and background specification. Near one, the stationary positive cluster model has large average families and strong amplification. This interpretation is conditional on the model. Certain nearly unstable heavy-tailed Hawkes models, under specified time, intensity and price scaling, have rough-volatility limits. A single exponential-kernel fit to this hour does not establish that limit or explain all daily volatility.
The cluster calculation within the stipulated positive linear model. Background immigrants arrive at rate mu. Each event has expected n direct children, the integral of the kernel. When n is below one, the expected family size including the immigrant is the geometric sum, one over one minus n. At n equal to one the mean diverges; above one a finite stationary mean is unavailable. Multiplying family size by immigration rate gives mu over one minus n. The latent genealogy is a representation of the model, not a recovered family tree for the observed trades.
A finite-sample sign-memory diagnostic. Plot buy-sell sign autocorrelation against event lag on logarithmic axes. A line fitted to the positive correlations at selected lags has exponent about 0.85. No interval is computed, and choosing positive values affects the fit. A true asymptotic power law with exponent between zero and one has nonsummable correlations; this finite window alone does not prove asymptotic long memory or identify order splitting.
One mechanism for persistent signs. A large parent order can be split into many same-side child orders. In the particular splitting model, a parent-size tail exponent between one and two leads to a sign-correlation exponent alpha minus one. Other scheduling, participation and dependence assumptions can change that mapping. Persistent order signs can coexist with weak return predictability if impact and liquidity adapt. This is a model reconciliation, not evidence that prices are exactly unpredictable or that splitting uniquely caused the observed autocorrelation.
A signature diagnostic in explicit units. The code averages squared mid increments at each sampling step and divides by the number of hundred-millisecond grid steps, not by seconds. The vertical unit is squared dollars per hundred milliseconds; multiply by ten for squared dollars per second. It is a second moment rather than a demeaned variance. The largest sampled value is about 31 percent above the shortest-step value. Such horizon dependence is consistent with serial dependence and aggregation effects, but it does not identify their cause. Transaction-price bid-ask bounce and quote-mid dynamics are different objects.
A possible quote-refill mechanism. Start with a one-tick spread. If only the best offer disappears and the next offer is one tick higher, the midpoint rises half a tick and the spread widens. If a new bid then joins inside that gap, the midpoint rises another half tick while the spread narrows. This stipulated two-step sequence creates same-direction midpoint moves. Other quote sequences need not do so. The illustration neither estimates its frequency nor proves that it caused the measured signature curve.
Within a stationary positive linear Hawkes model, let immigration be two events per second. Compute expected family size including the immigrant and mean event rate when branching is point six eight and point nine five. State what happens to the finite stationary mean at one. Explain why the model offspring fraction is not an observed causal trader-reaction fraction.
4Order-flow imbalanceMaster's4 min
Part thirty-five measured the price of trades. But trades are a minority of book events: adds and cancellations move the queues too. Rama Cont, Arseniy Kukanov and Sasha Stoikov asked what single number about the queues explains price changes best.
The definition. At the best bid, count size added, or the whole new queue if the bid rose, less size removed, or the whole old queue if it fell. The same at the best offer. Their difference, summed over an interval, is the order-flow imbalance: net buying pressure at the top of the book, from additions, cancellations and trades alike.
Two aligned minutes from the snapshots. The top plot shows net best-quote order-flow imbalance, with positive and negative pressure. The bottom plot is the mid change in the same interval. Their comovement is descriptive; this two-minute illustration does not compare forecasts, establish causation or measure the explanatory power of trades alone.
By hand, three snapshots. Five bitcoin bid at a hundred, four offered at a hundred and ten cents. Then two are added to the bid and one is cancelled from the offer: three of buying pressure, with no trade at all. Then the offer is taken, the price rises a tick, and a new bid of two appears at the old offer: the vanished offer counts minus three on the ask side, and the new bid counts in full, five more. Eight bitcoin of net pressure, and the mid rose ten cents. Trades alone would have missed the cancellation.
Separate contemporaneous fit from prediction. Each day is refitted on its own same-interval mid changes and imbalance. Mean reported R squared is about 42 percent at ten seconds and 42 at a minute. Calling the weekend a test day elsewhere does not make these daily regressions held-out forecasts. The response and the explanatory variable share quote events, so both are endogenous. Different samples, units and targets prevent interpreting the comparison with Part thirty-five as a controlled doubling of explanatory power. No causal effect or robust inference is established here.
A descriptive depth comparison. Each point pairs a half-hour regression slope with average displayed depth from that interval. The stored pooled log-log slope is -1.17. The original routine floors nonpositive slopes before taking logs, so this is not an unrestricted log-law estimate. The plot also has its own positive display floor. The minus-one benchmark comes from a stipulated constant-depth model in which a queue's worth of imbalance moves the mid half a tick. Neither the scatter nor its unreported uncertainty identifies a causal response to removing liquidity.
Keep the benchmark's units explicit. With average queue q in base units and tick delta in dollars, the stylised coefficient is delta over twice q, dollars per base unit. Part thirty-five's signed-trade regressions use a different flow definition and sometimes different normalization. Including additions and cancellations can change the shape of a descriptive relation. These separate regressions do not prove that queue refill caused trade-impact concavity or that contemporaneous linearity predicts the next interval.
Where it goes next. Ke Xu, Martin Gould and Sam Howison showed that the same imbalance at deeper levels of the book adds information, especially when the best queues are thin. Petter Kolm, Jeremy Turiel and Nicholas Westray fed order-flow imbalances, rather than raw prices and sizes, to deep networks, and reported better short-horizon forecasts: the input mattered more than the architecture. And a caution: everything in this chapter explains the price change in the same interval. Predicting the next one is Chapter six's much harder problem.
Two refinements. Rama Cont, Mihai Cucuringu and Chao Zhang combined the imbalances of the first ten levels through their first principal component: one integrated number that explains more than the best level alone. And across stocks: once a stock's own integrated imbalance is known, other stocks' imbalances add little to its price change in the same interval, but they do help forecast the next ones. Our feed carries only the best quotes, so this part measures the best-level version; the deeper ones need the full depth stream.
Use the stipulated constant-depth relation: the tick is ten cents, average best queue is eight bitcoin and OFI is plus twelve bitcoin. Calculate the implied mid change in dollars and ticks. Then double depth holding flow fixed. State the coefficient units and why arithmetic under this assumption is not an empirical causal effect.
5The micropriceMaster's5 min
The answer to the pause. Ten cents over twice eight, times twelve: about 7.5 cents, three-quarters of a tick. Twelve bitcoin of net buying is one and a half queues' worth, and the stylised model moves the mid half a tick per queue.
Chapter five. Back to the interview question: fair value, given the two best queues. In twenty eighteen Sasha Stoikov gave an answer with a definition, a theorem and an estimator. We fit it on two days of Bitcoin's book and test it on two others.
Three candidates. The mid ignores the queues. The weighted mid leans toward the side with the smaller queue, the side likely to be eaten first: with the offer nearly gone it sits almost on the offer. Stoikov's microprice is the expected mid, not at the next move, but after many future mid changes, given the imbalance and the spread now.
The weighted midpoint is not automatically a martingale. In this stipulated sequence it first leans toward a thin offer. After a price move and queue refill it can move back relative to the new midpoint. A drawn path alone does not prove a nonzero conditional expectation; the model's transition law is needed. The weighted formula generally fails the state-adjusted martingale equation. Nor does predictability of a constructed mid estimate establish an executable arbitrage once spreads, fees and risk are included.
A fitted finite-state estimator. Ten imbalance buckets and one- or two-tick spreads define twenty nominal states. Count transitions between adjacent retained snapshots, separating zero and nonzero mid changes. Concatenating days can put endpoints next to each other, so a grid lag need not equal elapsed time at a boundary. The first-step inverse gives a first-move reward and post-move operator. Empty count rows are normalized to zero, so stochasticity and support must be checked rather than assumed. Mirroring enforces antisymmetry. It does not prove irreducibility, mixing or Markov sufficiency of the real state. The theorem and the fitted estimator are separate claims.
Adjustments fitted on the two training-day arrays, displaying the one-tick-spread states. Opposite-size weighting is bounded by half a tick. The many-move fitted adjustment reaches about 25 ticks in the extreme bucket. The one-second fitted mean adjustment there has magnitude 6 ticks. The one-minute table has magnitude 18 ticks there, with a different shape across middle buckets. These are in-sample conditional-mean summaries, not bounds on possible market moves. Day boundaries can enter the concatenated horizon targets.
Held-out forecast errors on the two weekend days. Each column reports mean squared error as a percentage of the no-adjustment midpoint forecast, normalized to one hundred on the same eligible observations. The weighted midpoint offers a small improvement. The many-move estimator is up to 406 percent worse at one second, and remains worse at one minute. A separate conditional-mean table is fitted for each horizon. It reduces ten-second error by 3 to 5 percent on these two days, while its one-second result differs by day. No uncertainty interval or net execution test is supplied, and two days do not establish general superiority.
A conditional-mean diagnostic, not a complete martingale certification. In the extreme displayed bucket the mid's next nominal second averages 3 ticks in the direction of imbalance. The fitted microprice changes in the opposite direction, consistent with overshooting. A martingale relative to the full information set must have zero conditional increments for every suitable event; selected bucket means with no robust uncertainty establish neither a universal rejection nor acceptance. The day concatenation can compress boundary time, and overlapping increments are dependent.
A practical model boundary. Ten cents near twenty-seven thousand dollars is about four hundredths of a basis point, and a one-tick spread alone does not imply a large-tick regime. Conditional on a nonzero adjacent change in the concatenated training arrays, median absolute midpoint movement is 8 ticks. Most unchanged observations are excluded from that median. Depth, past flow and aggregation may make imbalance and spread insufficient. The later conditional-history diagnostic supports that concern without an uncertainty-calibrated universal Markov test or an identified causal explanation of overshoot.
Return to a conditional model example. In the hundred-dollar interview book, bid size is five-sixths of displayed size. Mapping that bucket to our fitted large-tick simulator gives an adjustment of 0.29 of a tick. The simulator was calibrated to Bitcoin queue rates; transferring its dimensionless adjustment to a one-cent stock is an illustrative rescaling, not a stock valuation. It gives roughly a hundred dollars and eight-tenths of a cent. The weighted midpoint and first-depletion Brownian expectation are different constructions. Real quotes require venue, horizon and cost validation.
Possible research uses. A validated state signal can inform a maker's quote center, but reduced adverse selection must be tested rather than assumed. An executor can compare a horizon-specific forecast with spread, fees, fill risk and latency. A quote midpoint already removes mechanical transaction-price bid-ask alternation. Replacing it with a microprice need not reduce forecast error or slippage noise. This sample's overshoot is precisely why the benchmark matters.
On the same stipulated held-out observations, midpoint mean squared error is point six zero squared dollars, a many-move estimate scores three, and a horizon-specific table scores point five seven. Normalize midpoint error to one hundred. Calculate the percentage increase for the many-move estimator and percentage reduction for the table. Does either establish net trading profit?
6Deep order booksPhD6 min
The order book is a large, structured, fast-arriving stream of numbers: exactly what deep learning is supposed to be good at. Since twenty seventeen, dozens of papers have fed it to networks. What did they find, and what do we find?
Three results the field builds on. DeepLOB, by Zihao Zhang, Stefan Zohren and Stephen Roberts: convolutions over ten levels of prices and sizes, then a recurrent network, predicting whether a smoothed mid will rise, fall or stay. Justin Sirignano and Rama Cont trained one network on hundreds of American stocks together. It beat models fitted stock by stock, even on stocks it never saw: the mechanics of price formation look universal. And the input matters: the same networks do better when fed order-flow imbalances than raw book levels.
What DeepLOB sees, and how. The last hundred book events, each with ten levels of price and size on both sides: four thousand numbers. The first convolutions pair each level's price with its size, then each bid with its ask, then summarise the levels: the structure of a book built into the filters. Then parallel filters of different widths for different time scales, and a recurrent layer that carries memory across the window. The output is down, flat or up.
What Sirignano and Cont found, in more detail, because it is the strongest positive result. Universality: one model for all stocks beat a model per stock, even on stocks it had never seen. Stationarity: trained on earlier years, it kept its accuracy on later months without refitting. And path-dependence: longer histories of the book improved the forecast. Price formation has memory, which a model of the current state alone cannot capture. The research chapter meets the same fact from the other side.
Then the benchmark. Most papers report on one public data set, ten days of five Finnish stocks from twenty ten. Matteo Prata and colleagues reran fifteen published models in one open framework. On data the models had not been tuned on, every one of them did markedly worse; most had overfitted the benchmark. Part twenty-six's lesson, at the speed of milliseconds.
Specify the exact label before comparing models. The displayed equation is a future-average-versus-current-mid variant. Common FI-twenty-ten and DeepLOB definitions instead compare backward and forward average mids. Their normalization and window conventions must be stated. The threshold determines the flat class and the class base rates, changing a constant-class benchmark. Smoothing and overlapping windows alter noise, dependence and the prediction target; they are not universally easier in every information set. Label accuracy does not become an executable return. Our restored baseline uses a plain future mid change in ticks.
The comparison we actually run. Every nominal second, thirty inputs: ten lagged OFIs divided by current depth, ten mid changes, and ten imbalances. No spread feature enters this implementation. The target is a plain one- or ten-second mid change in ticks. The first two archive days train; the weekend days test. Linear fits use all training observations. The network fits the first eighty percent, validates on the last twenty, and averages three fixed seeds. Horizon labels can overlap the validation boundary; there is no purged split. Training scores therefore use unequal fitting samples and the setup is a small baseline, not a replication of DeepLOB.
Direction scores on nonzero future moves. At one second, imbalance alone scores 87 percent, the thirty-input linear fit 87, and the network 84. At ten seconds, the linear fit scores 73 and the network 72. These particular network specifications do not win this direction comparison. The best displayed ten-second R squared is 3.7 percent. Accuracy is conditional on excluding flat targets, whereas R squared uses all targets. Neither statistic is a net-profit measure, and no robust comparison interval is estimated.
Interpret each statistic by its conditioning. About 88 percent of future one-second targets are zero. The large-realized-move bin has 86 percent sign accuracy, but future move size is unavailable at decision time: this is retrospective stratification, not a tradable filter. Selecting forecast magnitude above one tick gives signed mid-to-mid gain of 1.5 ticks per selected observation. It omits executable entry and exit prices, inventory, overlap, latency and fees; one basis point is about 27 ticks. Choosing among thresholds using these test scores would reuse the test sample. Test accuracy 87 percent exceeds training accuracy 81; a quieter weekend is one possible distribution change, not an identified explanation for the difference.
Three bounded conclusions. In this short sample, simple book features and a linear baseline perform well on the chosen direction metric. That does not prove additional network capacity only fits noise. Large multi-stock studies offer evidence for other architectures and data scales; their results do not guarantee a deep-model win in every market. Report the label definition, nonzero conditioning, base rates, fitting split, all-target error and executable costs. A smoothed benchmark label, an accurate sign and a profitable strategy are different claims.
A model gets eighty of one hundred nonzero future signs correct, with flat targets excluded. Its selected gross mid-to-mid gain is one and a half ticks. Assume a one-tick spread at entry and exit and a three-tick fee per side. Compute conditional accuracy and net gain for immediate market entry and exit. Explain why flat-target conditioning and a fee-free mid markout answer different questions.
7A book of our ownMaster's5 min
A forecast estimates a future statistic; a simulator must generate whole paths and respond to modeled actions. The previous cost calculation also showed that a direction score cannot certify profitable execution. We now examine a particular queue simulator and the behaviors it can and cannot reproduce under its assumptions.
Why simulate, and what replay can do. Historical replay can approximate queueing and adverse selection for a negligible order, as our later exercise does. Its central limitation is that the historical market cannot react to the added order. A responsive simulator can study counterfactual actions and stresses under its own assumptions. A policy tuned to that simulator can exploit its errors. Validation must cover both ordinary stylised facts and the response to interventions; neither is guaranteed by a visually plausible price path.
Four families. Statistical models, the queue-reactive model and Hawkes-driven books: rates read from data, interpretable and fast. Agent-based markets such as ABIDES, where simulated traders with strategies meet in a matching engine. Deep generative books: a conditional adversarial network of order flow, and Peer Nagy and colleagues' generator, which writes the message stream token by token, the way a language model writes text. And how to judge any of them: Svitlana Vyetrenko and colleagues proposed scoring a simulator on a list of the real book's stylised facts. We do that next.
A specified zero-intelligence baseline. Orders arrive and cancel under exogenous Poisson assumptions, without strategic decision rules. Define mu as market-order volume per time, alpha as limit-order volume per price per time, delta as cancellation rate per resting order and sigma as individual order size. Mu over alpha has price units; delta times sigma over mu is dimensionless. The continuum model therefore permits the displayed spread scale times an unspecified dimensionless function, with convention-dependent constants absorbed into it. Dimensional analysis does not determine that function or cover arbitrary finite-tick and placement rules. Farmer, Patelli and Zovko report supporting cross-stock spread evidence in their setting. Residual discrepancies do not separately identify strategy or information.
Our simplified queue model uses a chosen size unit of 1.9 bitcoin: one quarter of the median displayed size, not an estimate of typical individual order size. At each discretized queue size, count net upward and downward size changes per grid step. The plotted rates are their nominal per-second conversion. This discards message type, multi-unit jumps and within-step activity. The empirical refill distribution puts 49 percent at one unit, with median 2. Matching these summaries does not reproduce the full original message process.
An hour of the simulated mid, from the fitted rates alone. It wanders like a price, one half-tick at a time, ending 0.75 dollars from where it began. It looks plausible. The question is whether it is plausible in the ways that matter.
A scorecard of particular summary statistics. The simulated median queue is about 5 chosen units. The model has 7.6 mid moves per minute against 43 in the training day. Inter-move waiting-time coefficient of variation is 1.5 against 2.8; a Poisson event clock has coefficient one, but this ratio is not a general burstiness multiplier. Move-sign lag-one correlation has magnitude 0.00, versus signed data value 0.59. Ten-second kurtosis is 5.6 versus 35. These discrepancies reject several practical uses of this particular baseline, without proving that every Markov model has thin tails.
Diagnose this implementation, not all Markov models. Current full queues determine its transition probabilities. A Markov state can still produce serial dependence; including exponential-Hawkes intensity would also give finite-dimensional self-excitation. Our state omits those intensity and history variables. One-unit steps and a chosen refill rule restrict depletion and price dynamics relative to multi-unit real events. History variables, jump sizes and spread states are candidate model extensions, whose benefits require new validation. None is fitted here, and an enlarged state is not automatically sufficient.
Three rules for anyone who builds a market simulator. Match the facts, not only the likelihood: a model can fit each step and still miss the shape of a day. Check that it reacts: when an algorithm trades in it, the simulated price must respond as a real one would, which is Part thirty-seven's subject. And test out of sample, on another day and another regime.
Consider a full-state Markov chain with queue sizes one and one, or ten and ten. Both have imbalance one half. The next step removes one bid unit with probability point two and otherwise does nothing. Bid depletion moves the mid down half a tick. Compare the next-step price-move probability from the two states. Explain why projection onto imbalance alone need not remain Markov.
8Trading in the queueMaster's5 min
A back-of-queue fill can be adverse news, but its sign is conditional on order and market state. In this approximate replay, the average signed one-second markout at the back is -14.7 ticks. That is a sample statistic under a specified fill model, not a universal property of passive trading.
Price-time priority. At one price, orders fill in the order they arrived: the queue is a line, and a place in it is an asset. Ciamac Moallemi and Kai Yuan valued it: the front fills sooner, on smaller and less informed trades, so its value can be a large fraction of the spread. And being filled is news. It is Part thirty-five's Glosten and Milgrom from the other chair: the trader who hits your order may know something.
The replay assumptions. Every thirty seconds at a one-tick spread, a negligible order joins the best bid or ask, at the back or hypothetically at the front; it expires after one minute if unfilled. Replay orders overlap and never affect the tape. At-price aggressive volume must strictly exceed the queue ahead to fill; through-price trades also fill. Net cancellations reduce ahead size pro rata, while displayed-size clipping and vanished-level conventions approximate priority. Signed markout is future mid less execution price for buys, reversed for sells, in ticks. It already includes the entry half-spread. Fees, rebates, hidden liquidity, latency and executable liquidation are excluded, and the execution-time mid need not be exactly half a tick away.
Approximate fill outcomes. The back fill rate is 82 percent within a minute, with median filled wait 3.2 seconds. Its signed one-second markout is -14.7 ticks. The reported naive standard error is 0.4; overlapping replay orders and market dependence prevent treating it as a robust interval. Front markout is -1.6 ticks, on a different set of fills. Different conditional fill populations and assumed priority both contribute. This comparison does not isolate a causal or executable value of queue position.
Stratify the model's outcomes by displayed queue size. Back-of-queue signed mean markouts range from -13 to -28 ticks across the displayed groups. Queue depletion and price continuation can create this selection; the replay does not identify informed orders. The front means range from -11 to 6 ticks, with different conditional filled sets. A positive group mean is not net profit or proof that the queue behind causally protected the order. Group boundaries use this sample's quantiles and can share exact endpoint observations.
A partial per-submission accounting convention. Give unfilled orders zero value and multiply back fill probability by the conditional signed one-second markout: -12.1 ticks per submission. The same front calculation gives -1.5. Their difference is 10.6 ticks in this replay. This compares an explicit gross mark-to-mid functional; it is not a causal queue-priority price or net strategy profit. It omits unfilled opportunity costs, inventory, fees, rebates, cancellation decisions and liquidation. The entry half-spread is already inside each markout and must not be added again.
Read the two conditional samples carefully. Some fills are followed by adverse movement, but a fill need not imply that price traded through the order or that the counterparty was informed. In this replay, missed orders have a mean signed away-move of 98 ticks over the waiting window. Filled and missed orders are selected differently, not matched counterfactual outcomes. Copeland and Galai model a resting limit quote as an option offered to the market, with stale-price risk under their assumptions. Real cancellations, changing spreads and inventory also matter; this analogy does not make every limit order an unpriced free option.
The race behind the markouts. When the value moves, every resting quote on the wrong side is suddenly mispriced. Its owner tries to cancel it, and the time that takes is how long the free option stays open. Someone else tries to take it first, in the same microseconds. In a continuous book the race is won by speed, and, as Part thirty-five showed, the expected loss is built into every spread.
Possible maker controls. A validated signal can guide cancellation, but an overshooting or delayed estimate can remove favorable fills as well as adverse ones. The replay order here does not dynamically cancel. Queue placement, entry time and price selection affect fill probability and selection. A full realized-profit account needs trading cash flows, inventory marks, fees or rebates and eventual liquidation, plus latency and control costs where relevant. A single post-fill markout is one component of that account, not the account itself.
A stipulated replay fills eighty percent of submissions. Conditional signed markout is minus two ticks and already includes the entry half-spread. A rebate adds one tenth of a tick per fill. Give unfilled orders zero. Calculate the contribution per submission without adding half-spread again, and identify the inventory, liquidation and opportunity terms still absent.
9Rule 36: score the book against the spreadIndustry5 min
A separate state-signal illustration before the proposed research rule. A thin bid and full offer imply low bid-size imbalance. Many fitted queue models then lean below the midpoint, although the amount depends on calibration and horizon. That state can motivate quote review. The snapshots do not show that a usable warning arrived before a fill, that cancellation would succeed, or that centering quotes on this estimator improves net performance. An observed adverse fill does not prove an informed counterparty.
Chapter nine. The House's thirty-sixth rule is about the book. Every signal from it is small, fast and fragile, and a simulator of it can be wrong in ways that look like profit. So the rule says what each must show.
The first sheet. A book that sits at one tick nearly all the time and updates a hundred times a second. Queues that predict the next tick. Trade arrivals that excite each other, and signs with long memory. Order-flow imbalance that explains much of the price change, with an impact close to one over depth. A microprice that overshoots on a small-tick book, and a plain table that does its job. A network that does not beat a linear rule. A simulator with tails far too thin. And passive fills that lose, badly at the back of the queue.
Limits that travel with the figures. One venue, one perpetual and four dates, including a partial initial archive and a weekend test. Carried quotes count as grid observations, and day concatenations can compress gaps. Best-quote snapshots do not identify all messages, deeper liquidity, hidden size or exact queue priority. Coarse fitted states need not be Markov. Forecast splits, overlapping labels, descriptive regressions and naive standard errors limit inference. Fees, latency, market reaction and executable liquidation are not modeled. These are measurements and model diagnostics, with no newly registered trading strategy.
Chapter four's definition in one expression. For the bid, the new size if the bid rose or stayed, less the old size if it fell or stayed; for the ask, the mirror image, subtracted. Every term is a whole queue or nothing, which is why it captures additions and cancellations without seeing a single order.
Read the estimator precisely. Invert one minus the no-move operator to obtain the first-move reward and post-move operator. The stored fit sums the initial term and four hundred subsequent powers, four hundred and one terms in all. Its convergence diagnostic compares that result with the first two hundred and one terms. A tiny numerical tail difference is an algebraic diagnostic; it does not certify support, stochasticity or the real market's Markov hypothesis.
The simulator updates each full queue by at most one chosen unit per grid step, using state-dependent probabilities estimated from net changes. On depletion the mid moves half a tick and the queues reset using the empirical refill distribution. That full-state process is Markov by construction. Ten imbalance buckets are a projection and need not preserve the Markov property. The scorecard tests this implementation rather than proving that all Markov books share its failures.
And Chapter eight's replay. A trade at our price larger than the queue ahead fills us, as does any trade through our price. Otherwise the trades eat the queue ahead, net cancellations are taken in proportion, and if the level vanishes we are alone at the front.
And Chapter five's humble winner. For every snapshot with a usable spread, take the state and the mid's change over the horizon; mirror the data so the table is antisymmetric; and average by state. No chain, no limit, no theorem: an honest conditional mean, fitted for the horizon at which it will be used.
The tools and a proposed research rule. Public loaders, book features, finite-state adjustments, memory diagnostics and a simplified queue simulator with fill replay. These are research components, not a deployed surveillance or trading system. Proposed Rule thirty-six: compare held-out forecasts with simple baselines, state the target and clock, account for executable costs, and ship a simulator with checks of both distributions and action responses. Report signed fill markouts at several horizons beside the replay assumptions. Passing one diagnostic does not constitute trading approval.
The rule against three cases. A paper with eighty-five percent accuracy on the benchmark: ask for another market and another year, the linear baseline, and the profit after the spread. An execution algorithm tuned in a simulator: ask for the scorecard, and whether the price reacts to the algorithm's own orders. A maker proud of a high fill rate: ask for the markouts. At the back of the queue, a high fill rate measures how often you were picked off.
Under a stipulated immediate round trip, gross mid-to-mid gain is one and a half ticks. Entry and exit each pay half a tick of spread and three ticks of fees. Calculate break-even gross gain and the current shortfall. Explain why even an eighty-seven-percent conditional sign score does not supply an executable profit certificate.
For the researcher: the microprice theoremPhD8 min
For the researcher. Separate a mathematical theorem for a specified Markov-additive process from an estimator fitted to a coarse book summary. We prove the centered finite-state result, including the correct spectral bound and normalization. Then we inspect algebraic and empirical diagnostics. A Markov queue simulator is not proof that the bucketed state satisfies the theorem.
The hypotheses of a model theorem. A finite state describes the chosen process, with integrable first-move rewards. The joint state and price are Markov additive: translation of the price level does not alter the transition and increment law. A mirror involution reverses increments and preserves transition probabilities. It is a sufficient centering condition. The no-move operator has spectral radius below one; the post-move operator is stochastic, irreducible and aperiodic on the actual state support. These are hypotheses to verify, not consequences of labeling a grid with imbalance buckets.
Lemma one, the first move. Let g one of x be the expected first change of the mid from state x. Condition on the first step: the mid moves now, with expected change R, or the chain moves to another state without a change, with probability Q, and starts again. By hypothesis three, Q's spectral radius is below one, so one minus Q is invertible: its inverse is the sum over all the steps spent waiting.
Lemma two, the later moves. The same summation gives the law of the state just after the first change: B, one minus Q inverse, times T. Its rows sum to one, so B is a stochastic matrix. By the strong Markov property at each change, the next change depends on the past only through the state there. So the expected mid after n changes is the mid plus the first n terms of the series.
The centered convergence argument. A finite irreducible aperiodic stochastic B has a unique stationary distribution pi, and its powers tend to the all-rows stationary matrix. Mirroring makes the first-move reward antisymmetric and pi symmetric, so pi times g one is zero. Symmetry is sufficient, not necessary: an unmirrored chain can also have zero stationary reward. Let A be B minus its stationary projection. For any rho strictly above A's spectral radius and below one, a finite constant bounds the norm of A to the k by C rho to the k. Using exactly the second eigenvalue modulus can fail for Jordan blocks; diagonalizability supplies that stronger bound. The centered Neumann series therefore converges to the fundamental matrix applied to g one, with stationary mean zero.
The conclusion under the stated hypotheses and integrability. The expected midpoint after n future moves converges to the current midpoint plus the centered state adjustment g. The inverse of identity minus B plus the stationary projection gives that adjustment. At move times, expected next price is the current midpoint plus g one plus B g, equal to midpoint plus g by the Poisson equation. This proves a martingale in the model's move-time filtration. It does not identify fundamental economic value, a tradable execution price or a physical-clock result without the corresponding stopping and timing conditions.
The normalization is essential. A state-adjusted price is a move-time martingale exactly when f equals g one plus B f, under the model and integrability conditions. Any two solutions differ by a harmonic vector. For a finite irreducible stochastic chain, the maximum principle makes every harmonic vector constant. Thus solutions are unique up to an additive constant. Stationary mean zero fixes it; under a valid mirror symmetry, requiring antisymmetry also fixes it. The weighted midpoint solves this equation only for particular transition laws, rather than being universally excluded.
What nonzero stationary reward does. This particular unmirrored fit has stationary reward 0.03 ticks per move. If that reward is nonzero, the expected n-move sum contains n times the stationary reward plus a bounded centered correction, so the uncentered limit cannot exist. The stored partial sums are -0.5, 2.2 and 11.3 ticks after ten, one hundred and four hundred moves. Removing mirror augmentation does not logically require nonzero drift. An asymmetric chain with zero stationary reward can still satisfy the centered theorem.
An algebra check for the fitted operator. The largest eigenvalue is numerically one; the next modulus is 0.67. The retained nominal state counts are all positive in this restored fit, though some two-tick states are sparsely observed. Mirroring yields a stationary reward near floating-point zero. The finite series agrees with the closed form at the displayed residual, and the sampled norms decay. This supports numerical consistency of these stored quantities. It does not independently verify irreducibility, all transition probabilities, sampling uncertainty or the Markov sufficiency of market observations.
An eigenmode interpretation. A component aligned with an eigenvector of eigenvalue lambda is multiplied by lambda at each move. A general lean is a sum of modes and may have nonnormal or Jordan effects. For the dominant displayed positive mode, modulus 0.67 gives a magnitude half-life of 1.7 moves and a scalar geometric multiplier near three. The simulator's projected operator has a different spectrum; resetting full queues does not prove every imbalance bucket immediately forgets. One over one minus lambda is a mode-specific multiplier, not a universal multiplier of the entire first-move vector.
A simulated diagnostic, with separate fit and evaluation runs. The full queue process is Markov by construction, while the fitted imbalance/spread projection can retain omitted-state dependence. Its extreme one-second midpoint mean is about 0.16 tick. The microprice's largest displayed absolute mean is 0.015 tick; small plotted means do not certify an exact martingale. No robust uncertainty calculation or full conditional test is made. This is evidence about this simulator and this projection, not a setting in which every theorem hypothesis is automatically true.
A finite-horizon comparison. Regress the mean future mid change across buckets on the fitted adjustment, using the displayed weighting convention. The simulator coefficient approaches roughly 1.15 over the sampled horizons; four fixed evaluation runs give a descriptive spread, not a universal limit proof. Bucket coarseness and omitted queue scale are possible discrepancies. The Bitcoin coefficient peaks at 0.46 and later declines. This is an aggregate regression coefficient, not the fraction of every individual state's lean realized, nor proof about an infinite-horizon limit. Day concatenation and dependence also affect interpretation.
A necessary implication of the proposed observed state. Under the stated Markov-additive law, the next sign distribution conditional on the post-move state cannot additionally depend on the previous sign. The code compares conditional mean next signs only in states with more than twenty observations of both previous directions, then takes a count-weighted signed average. Opposite differences can cancel. The recorded averages are -0.05 in simulation and 0.46 for Bitcoin. With no robust interval and dependence across moves, they are diagnostics of omitted history. A small aggregate gap does not prove Markovity, and a large gap does not isolate its causal source.
Where this sits. Marco Avellaneda, Josh Reed and Sasha Stoikov derived the probability of an up-move from the two best queues, with hidden liquidity: the one-step version. Martin Gould and Julius Bonart tested queue imbalance across Nasdaq stocks, and found it strong for large-tick stocks and weak for small-tick ones: the same boundary. And Stoikov's paper gives the definition, the estimator and the convergence condition proved here.
Three research directions with precise limits. Find a manageable state whose forecasts and conditional diagnostics remain stable across markets and regimes; approximate sufficiency must be tested. Exponential Hawkes kernels admit finite-dimensional intensity states, while general history kernels may need an infinite-dimensional state or an approximation. Computable price adjustments and error bounds depend on the specified model, so there is no universal impossibility claim. Multi-venue queues add routing, latency and cross-venue dependence. A consolidated-price model must state those mechanics and a target horizon before any theorem or forecast claim.
Two mirror states have post-move persistence p. From the bid-heavy state the next midpoint change is plus one tick with probability q and minus one otherwise, with the mirror reward in the other state. Normalize the adjustment to stationary mean zero. Solve the displayed Poisson equation, evaluate p and q at three-quarters, and discuss the limit as p approaches one with q fixed. These are full-tick model increments, not the half-tick increments of every earlier example.
Recap, desk questions, problemsAll tracks5 min
The first six conclusions. Displayed queues describe a venue's best prices under its matching rules. Imbalance is associated with the next-move sign. A fitted Hawkes model represents clustering but does not identify causal trader reactions, and finite-window sign correlations need cautious extrapolation. Same-interval OFI is descriptive. The state-adjusted martingale theorem has explicit centering, mixing and integrability assumptions. On these Bitcoin dates the fitted many-move adjustment overshoots, while horizon-specific tables offer modest held-out error reductions.
The remaining conclusions. This short network comparison does not beat the linear sign baseline, and its accuracy excludes flat targets. The simulator matches some summaries and misses others; full-state Markovity need not survive bucketing. The fill replay has adverse signed averages under explicit queue assumptions, without net-profit or causal priority-value certification. Proposed Rule thirty-six asks for baselines, costs and simulator response checks. The theorem is a model result; numerical and conditional diagnostics must be interpreted separately.
Three research habits. State and examine the model hypotheses separately from a proof: centering, support, mixing and the observation clock all matter. Conditional diagnostics can reveal omitted history without certifying full Markovity. Preserve simple baselines and the exact target definition; a linear direction score, a horizon table and a many-move state correction answer different questions. Report both gross diagnostics and executable costs, fill selection and inventory consequences. A high accuracy, high fill rate or convergent matrix series is not by itself a profitable strategy.
Six desk questions. What is order-flow imbalance? The net change of the best queues, from every kind of event. Why does queue imbalance predict the next tick? The short queue empties first. What is the microprice, and when can you trust it? On large-tick books, and after testing.
Why is the weighted mid not a fair price? Its changes are predictable. Why is a fill at the back of the queue bad news? It comes just before the price goes through. And how would you score a simulator? On stylised facts, out of sample, and on how it reacts to your own orders. Full solutions are in the notes.
The first five quantitative pauses. The fluid queue takes sixteen point six seven seconds to reach the front and five more to fill, twenty-one point six seven in total. The Brownian up probability is point seven nine five two, versus imbalance point seven five, with unchanged probabilities after proportional rescaling. Hawkes family sizes are three point one two five and twenty, giving rates six point two five and forty per second under stationarity. The stipulated OFI relation gives seven and a half cents, or three-quarters of a tick, halved by twice the depth. Normalized errors are one hundred, five hundred and ninety-five: four hundred percent worse is not five hundred percent worse.
The remaining five. Eighty-percent conditional sign accuracy can coexist with minus five and a half ticks after the stipulated immediate round-trip costs. Two full queue states with equal imbalance have different depletion probabilities, so the projection can lose the Markov property. The replay contribution including rebate is minus one point five two ticks per submission, with entry spread already counted. The proposed cost budget needs seven gross ticks to break even. Finally, the antisymmetric two-state reward is an eigenvector with eigenvalue two p minus one; summing its geometric series gives one tick at p and q equal to three-quarters. With q fixed above one half, the adjustment diverges as persistence approaches one; at one, irreducibility and the centered-limit argument fail.
Twelve fully worked problems, with six basic, four advanced and two qualifying problems. The first six cover deterministic queue time, diffusion depletion probability, stationary Hawkes arithmetic, sign-sum variance, stipulated OFI impact and the interview midpoint. The advanced set covers conditional accuracy and net costs, loss of Markov sufficiency after projection, partial replay accounting and a counterexample to guaranteed cancellation benefits. The qualifying set proves the centered finite-chain microprice theorem and solves the symmetric two-state model, including its boundary cases. Complete English and Chinese solutions are in the notes.
Where this comes back. Part thirty-seven measures the impact of large orders and schedules them. Part thirty-eight makes markets with the microprice, inventory and queue position. Part thirty-nine meets a book with no queues at all, the automated market maker. And Part forty-two puts learning agents into simulated markets like this one.
The principal textbooks and papers behind this part are listed separately so each title remains readable. The displayed measurements come from the nine restored original computations on frozen public archives or their stipulated simulations. Chosen arithmetic examples are labeled as such. No new market trial, sealed strategy outcome or deployment approval is part of this visual review.
The House can now read the book: its queues, its flow, its fair price where one exists, and the cost of waiting in line. Next, Part thirty-seven: market impact and execution. How much a large order moves the price, why the cost grows like a square root, and how to schedule a trade so that it costs the least.
Where it goes next. A model of the book prices a large order: Part 37. A place in the queue is the market maker's asset: Part 38.
Key results
The part's results in one place, for revision.
Try it
Lab 36 · The next tick from the queues, and clustered order flow
Two queues sit at the best bid and ask; the price ticks up when the ask empties first. Simulate that race from every starting pair, compare with the closed form and with the naive imbalance, then simulate a self-exciting order flow and recover its branching ratio by maximum likelihood.
python -m videos.quant.labs 36
needs numpy, scipy, matplotlib, numba · download lab36.py ·
source on GitHubbid 9, ask 3 P(up) simulated 0.793 formula 0.795 imbalance 0.750
bid 6, ask 6 P(up) simulated 0.509 formula 0.500 imbalance 0.500
bid 3, ask 9 P(up) simulated 0.198 formula 0.205 imbalance 0.250
bid 12, ask 2 P(up) simulated 0.896 formula 0.895 imbalance 0.857
bid 5, ask 4 P(up) simulated 0.574 formula 0.570 imbalance 0.556
Hawkes flow: true branching 0.70 fitted 0.704; rate 3.40/s (theory mu / (1 - n) = 3.33)
The imbalance is the right direction and the wrong number. And seven orders in ten are reactions to earlier orders: the flow's clock is not Poisson.
The code (75 lines; it asserts its own result)
"""Lab 36: which queue empties first, and orders that arrive in clusters."""
import numpy as np
from videos.quant import labs
from explainer.quant.house import sim
TITLE = "The next tick from the queues, and clustered order flow"
GOAL = ("Two queues sit at the best bid and ask; the price ticks up when the ask empties first. Simulate that "
"race from every starting pair, compare with the closed form and with the naive imbalance, then simulate "
"a self-exciting order flow and recover its branching ratio by maximum likelihood.")
TASKS = [
"Let the bid queue shrink faster than the ask (a seller is working an order). How does the picture tilt?",
"Raise the branching ratio to 0.95. What happens to the event rate and to the fit's uncertainty?",
"Turn the up-probability into a microprice: mid + (2u - 1) x half a tick. When is it far from the weighted mid?",
]
def depletion_prob(bid, ask, n_paths, rng, max_steps=40000):
"""P(the ask queue empties before the bid): each step one queue, chosen at random, moves by +-1.
The race has no finite expected length (a driftless walk in a quadrant), so it is cut at ``max_steps``; the
few undecided paths are left out."""
b = np.full(n_paths, bid)
a = np.full(n_paths, ask)
ups = downs = 0
for _ in range(max_steps):
which = rng.random(b.size) < 0.5
step = np.where(rng.random(b.size) < 0.5, 1, -1)
b = b + np.where(which, step, 0)
a = a + np.where(which, 0, step)
ups += int(np.sum(a == 0))
downs += int(np.sum(b == 0))
live = (a > 0) & (b > 0)
b, a = b[live], a[live]
if b.size == 0:
break
return ups / (ups + downs)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
pairs = [(9, 3), (6, 6), (3, 9), (12, 2), (5, 4)]
worst = 0.0
sim_u, th_u, imb = [], [], []
for bid, ask in pairs:
u = depletion_prob(bid, ask, 6000, rng)
theory = 1 - 2 / np.pi * np.arctan(ask / bid) # harmonic in the quadrant: Brownian queues
sim_u.append(u), th_u.append(theory), imb.append(bid / (bid + ask))
worst = max(worst, abs(u - theory))
lab.row(f"bid {bid:>2}, ask {ask:>2}", f"P(up) simulated {u:.3f} formula {theory:.3f} imbalance {bid / (bid + ask):.3f}")
events = sim.hawkes_thinning(1.0, 1.4, 2.0, 2000.0, seed=seed)
fit = sim.hawkes_fit(events, 2000.0)
lab.row("Hawkes flow: true branching 0.70", f"fitted {fit['branching']:.3f}; rate {len(events) / 2000:.2f}/s "
f"(theory mu / (1 - n) = {1 / 0.3:.2f})")
lab.note = ("The imbalance is the right direction and the wrong number. And seven orders in ten are "
"reactions to earlier orders: the flow's clock is not Poisson.")
assert worst < 0.03 and abs(fit["branching"] - 0.7) < 0.05 and abs(len(events) / 2000 - 1 / 0.3) < 0.4
fig, ax = labs.figure(2, size=(11, 4.2))
I = np.linspace(0.02, 0.98, 200)
ax[0].plot(I, 1 - 2 / np.pi * np.arctan((1 - I) / I), color=labs.P, label="1 - (2/pi) atan(ask/bid)")
ax[0].plot(I, I, color=labs.MUTED, ls="--", label="imbalance itself")
ax[0].plot(imb, sim_u, "o", color=labs.SPOT, label="simulated queues")
ax[0].set(title="Probability the next tick is up", xlabel="imbalance: bid / (bid + ask)")
ax[0].legend(fontsize=8)
window = events[events < 60]
grid = np.linspace(0, 60, 1500)
ax[1].plot(grid, sim.hawkes_intensity(window, 1.0, 1.4, 2.0, grid), color=labs.OPTION, lw=0.9)
ax[1].plot(window, np.zeros_like(window), "|", color=labs.SPOT, ms=10)
ax[1].axhline(1.0, color=labs.MUTED, ls=":", lw=1)
ax[1].set(title="A minute of self-exciting order flow: intensity and events", xlabel="seconds", ylabel="events per second")
lab.fig = fig
return lab
Now change it
- Let the bid queue shrink faster than the ask (a seller is working an order). How does the picture tilt?
- Raise the branching ratio to 0.95. What happens to the event rate and to the fit's uncertainty?
- Turn the up-probability into a microprice: mid + (2u - 1) x half a tick. When is it far from the weighted mid?
Problems, with solutions
Try each problem before opening its solution; the last two of each set are at qualifying-exam level.
Problems, with worked solutions
Worked problems: six basic
-
Fluid queue time. A queue of 5 BTC ahead; trades 0.2 BTC/s, cancels 0.1 BTC/s from ahead. Time to the front, and to fill 1 BTC.
Solution
Five BTC are ahead. Trades consume 0.2 BTC/s and cancellations remove 0.1 BTC/s from ahead. Your one-BTC order is never cancelled. Assume fixed fluid rates, no new priority ahead and enough available trading volume. Ahead size is
max(5-0.3t,0), reaching zero at5/0.3=16.6667 s. Your own quantity then fills only through trades, taking1/0.2=5 s, so total full-fill time is 21.6667 s. Cancellations of other orders do not execute yours. This is deterministic arithmetic, not the expected hitting time of a stochastic queue. -
Queue-depletion probability. Queues of 9 and 3: the up-tick probability under Cont–de Larrard and under "probability = imbalance".
Solution
Independent driftless Brownian queues have equal variance rates and start at bid 9, ask 3. In polar angle
theta=atan(3/9), the bounded harmonic exit probability isu=1-2 theta/pi, with boundary values one at ask depletion and zero at bid depletion. Thusu=0.7951672. The imbalance heuristic is9/(9+3)=0.75; they are different models. Multiplying both queues by the same positive constant leaves both probabilities unchanged. Brownian scaling multiplies the depletion-time distribution by the square of that constant; no finite expected depletion time is asserted. Unequal variances, correlation or drift change the simple angle formula. -
Stationary Hawkes arithmetic. Hawkes: background 2/s, branching 0.68, then 0.95. Mean rates; the share of events that are endogenous.
Solution
In a positive linear Hawkes cluster model, immigration is 2/s and branching is
n<1. Expected generation sizes are1,n,n^2,..., so expected total family size is1/(1-n). Atn=0.68, this is 3.125 and mean rate is 6.25/s. Atn=0.95, family size is 20 and rate 40/s. Latent offspring shares are 68% and 95% in this model, not identified causal trader-reaction fractions. At one the expected family size diverges and no finite positive stationary mean follows; above one the stationary-mean formula is invalid. -
Variance of persistent signs. Signs with ACF \(\propto \ell^{-0.85}\): why the variance of the sum of \(n\) signs grows faster than \(n\).
Solution
Suppose stationary centered unit-variance signs have covariance
C(l) ~ c l^(-gamma), withc>0and0<gamma<1. Expanding the square givesVar(S_n)=n+2 sum(l=1..n-1)(n-l)C(l). Riemann-sum asymptotics givesum(n-l)l^(-gamma) ~ n^(2-gamma)/[(1-gamma)(2-gamma)]. HenceVar(S_n) ~ 2c n^(2-gamma)/[(1-gamma)(2-gamma)], dominatingn. Atgamma=0.85, the exponent is 1.15. A finite fitted ACF slope does not prove these asymptotic assumptions. Translating sign-sum growth into price behavior needs an impact/liquidity model; it does not follow from this identity alone. -
Stipulated OFI impact. OFI of \(+12\) BTC against queues of 8 BTC, tick $0.10: the mid move under the stylised model.
Solution
Under the chosen constant-depth relation,
Delta m = delta E/(2 qbar), with tick$0.10, average queue 8 BTC and best-quote OFI+12 BTC. The slope is$0.00625/BTC, yielding +$0.075 = +0.75 tick. With depth 16 BTC, the same OFI gives$0.0375 = 0.375 tick. Units cancel BTC. This is a consequence of the stipulated model, not a fitted causal response to a counterfactual order. -
Interview book. Bid \\(100.00 for 500 shares; ask \\)100.01 for 100: mid, weighted mid, and expected next mid under independent, equal-variance, driftless Brownian queues and half-tick mid moves.
Solution
Bid is
$100.00for 500 shares, ask$100.01for 100. The mid is $100.005. Opposite-size weighting gives(500*100.01+100*100)/600 = $100.0083333, toward the thin offer. Under the Brownian assumptions in problem 2,p_up=1-(2/pi)atan(1/5)=0.8743341; if first depletion changes the midpoint by exactly plus/minus half a cent, expected next midpoint is100.005+0.005(2p_up-1) = $100.0087433. A many-move adjustment needs its transition model and normalization. Applying the lecture's simulator bucket as a dimensionless illustration gives about $100.008, but it is not an independently calibrated stock valuation. None of these quantities is a guaranteed executable price.
Problems, with worked solutions
Worked problems: four advanced
-
Conditional accuracy versus costs. 80 of 100 nonzero signs correct; gross gain 1.5 ticks, round-trip spread 1, fees 3 per side. Compute net and state limits.
Solution
Eighty correct signs among 100 nonzero future targets means 80% conditional accuracy. Flat targets are excluded, so all-observation accuracy cannot be recovered without their count, predictions and scoring rule. Suppose selected gross mid-to-mid gain is 1.5 ticks, with an immediate market entry and exit each paying half of a one-tick spread plus three ticks of fees. Net under these assumptions is
1.5-0.5-0.5-3-3 = -5.5 ticks, and break-even gross gain is 7 ticks. This ignores impact and latency and treats selections as comparable round trips. Overlapping forecasts need position accounting. Report the label, selection frequency, base rates, all-target errors, split, costs and dependence-aware uncertainty rather than equating accuracy with profit. -
Projection of a Markov queue. Queues \((1,1)\) and \((10,10)\) share imbalance \(1/2\). Remove one bid unit with probability 0.2: test Markov sufficiency.
Solution
Full states
(1,1)and(10,10)share imbalanceI=1/2. Remove one bid unit with probability 0.2, otherwise do nothing; bid depletion moves the mid down half a tick. The first full state has next-step down-move probability 0.2 and expected mid change -0.1 tick; the second has probability and expected move zero. Thus two full states in the same projected state have different transition/reward laws. Strong lumpability, which would require equal total transition probabilities into every projected class, fails. The full chain can be Markov while imbalance alone is not a sufficient Markov-additive state. This counterexample does not say every projection fails or every Markov model lacks clustering. -
Replay accounting. Fill probability 0.82; signed 1-s markout \(-14.7\) ticks includes entry spread; unfilled value zero. Compute gross contribution per submission and state omissions.
Solution
Suppose back fill probability is 0.82 and conditional signed one-second markout is -14.7 ticks. Assign unfilled orders zero; contribution is
0.82*(-14.7) = -12.054 ticks/submission. It already includes entry half-spread, so adding another half-tick is incorrect. If a separate chosen example has fill probability 0.8, markout -2 and rebate +0.1 tick/fill, contribution is -1.52 ticks/submission. A front/back difference compares these specified gross functionals on different fill sets. Inventory liquidation, missed opportunities, fees, adverse selection beyond the mark horizon and market reaction are still absent. It is not a complete net-profit or causal queue-priority estimate. -
Cancellation need not improve markout. Can cancellation on a state signal be guaranteed to improve markout? Give a numerical counterexample and a valid evaluation design.
Solution
Consider equally frequent states A and B. All orders would fill, with markouts -1 tick in A and +3 in B. Without cancellation, mean markout and per-submission contribution are
(-1+3)/2 = +1 tick. A misspecified signal leans against B only; cancelling B reduces fill rate from one to one half, conditional markout from +1 to -1, and contribution to0.5*(-1)=-0.5 tick. Thus no improvement is guaranteed. Evaluate a frozen, latency-feasible cancellation policy on separate data, with matched order opportunities, executable cancellation and queue rules, fill-selection changes, fees, inventory and liquidation. Keep all-submission value alongside conditional filled markouts and account for dependence; do not choose the rule on the evaluation sample.
Problems, with worked solutions
Worked problems: two qualifying
-
Centered microprice theorem. (qual) Under finite-state H1–H3 and integrable first-move rewards, prove convergence, the centered inverse formula, and uniqueness up to a constant fixed by mirror antisymmetry.
Solution
Use the setting and integrability assumptions stated above. First-step conditioning gives
g1=R+Qg1; sincerho(Q)<1,g1=(I-Q)^(-1)R. Summing the no-move waiting paths gives post-move lawB=(I-Q)^(-1)T. Since(Q+T)1=1,B1=(I-Q)^(-1)(I-Q)1=1. Strong Markov conditioning at successive moves yieldsE_x[M_tau_n]-M_0 = sum(k=0..n-1)(B^k g1)(x).
Let mirror permutation J commute with B and reverse g1: Jg1=-g1. Uniqueness of the stationary distribution implies pi'J=pi', so pi'g1=pi'Jg1=-pi'g1=0. The same centering may hold without any mirror. Set Pi=1 pi'; stochasticity and stationarity give B Pi=Pi B=Pi, and for k>=1, (B-Pi)^k=B^k-Pi. The eigenvalues of A=B-Pi are zero and B's nonstationary eigenvalues, all with modulus below one. In finite dimension, Jordan form gives for any rho(A)<rho<1 a finite constant bounding ||A^k|| <= C_rho rho^k; polynomial Jordan factors are absorbed by the strict spectral margin. An exact rho(A)^k bound is not valid in general. Since Pi g1=0, B^k g1=A^k g1, including k=0 after applying to g1. Absolute convergence follows.
The Neumann sum equals g=(I-A)^(-1)g1=(I-B+Pi)^(-1)g1, with pi'g=0. It solves (I-B)g=g1 and therefore g=g1+Bg. Conditional expectation of M_tau_(n+1)+g(X_tau_(n+1)) given the move-time past is M_tau_n+g1(X_tau_n)+(Bg)(X_tau_n)=M_tau_n+g(X_tau_n). Integrability of the increments and bounded finite-state g makes this a martingale. If f is another integrable state correction, (I-B)(f-g)=0. A finite irreducible chain's maximum principle makes its harmonic vectors constant, so f=g+c1. Stationary mean zero fixes c=0; mirror antisymmetry also fixes it because J1=1. If d=pi'g1 is nonzero, decompose g1=d1+h; the expected n-move sum is nd1 plus a bounded centered term, so the uncentered limit diverges. No assertion of fundamental value, executable arbitrage or a physical-time martingale follows without additional structure.
-
Two-state model and singular limits. (qual) Two mirror states: \(B=\bigl(\begin{smallmatrix}p&1-p\\1-p&p\end{smallmatrix}\bigr)\), \(0<p<1\), reward \(g^1=(2q-1)(1,-1)\) ticks. Solve centered \(g\); compare fixed \(q>1/2\), \(p\to1\) with \(q=1/2\).
Solution
Let
B=[[p,1-p],[1-p,p]],0<p<1, with stationary law(1/2,1/2). At a move from H the increment is +1 tick with probability q and -1 otherwise; L has the mirror law. Thusg1=(2q-1)(1,-1). The antisymmetric vector is an eigenvector with eigenvaluelambda=2p-1, whose modulus is below one. Its series givesg_H=(2q-1)/(1-lambda)=(2q-1)/[2(1-p)]andg_L=-g_H. Atp=q=3/4, the lean is one full tick. For fixedq>1/2,g_Htends to positive infinity asptends to one; at one, B is reducible and the stationary-centered inverse is no longer available. Ifq=1/2,g1=0and the normalized solution is zero for each0<p<1; the divergent-limit claim therefore needs nonzero reward. Atp=0, the chain is periodic; for nonzero reward the ordinary geometric partial sums oscillate, although the algebraic Poisson equation has a centered solution. A negative eigenvalue can cause alternating terms and must not be interpreted as a positive persistence multiplier. Bitcoin's fitted second modulus near 0.668 suggests a mode-specific geometric multiplier only when the reward has a component in the relevant positive eigenmode; it is not proof that the entire lean scales by three or that the market obeys this two-state model.
Reading and notes
The part's papers
from READING.md
- Smith, E., Farmer, J. D., Gillemot, L., Krishnamurthy, S. (2003). "Statistical theory of the continuous double auction." Quantitative Finance.
- Lillo, F., Farmer, J. D. (2004). "The long memory of the efficient market." Studies in Nonlinear Dynamics & Econometrics.
- Cont, R., Stoikov, S., Talreja, R. (2010). "A stochastic model for order book dynamics." Operations Research.
- Huang, R., Polak, T. (2011). "LOBSTER: limit order book reconstruction system." Working paper.
- Filimonov, V., Sornette, D. (2012). "Quantifying reflexivity in financial markets: toward a prediction of flash crashes." Physical Review E.
- Cont, R., de Larrard, A. (2013). "Price dynamics in a Markovian limit order market." SIAM J. Financial Mathematics.
- Gould, M., et al. (2013). "Limit order books." Quantitative Finance.
- Hardiman, S., Bercot, N., Bouchaud, J.-P. (2013). "Critical reflexivity in financial markets: a Hawkes process analysis." European Physical Journal B.
- Cont, R., Kukanov, A., Stoikov, S. (2014). "The price impact of order book events." J. Financial Econometrics.
- Bacry, E., Mastromatteo, I., Muzy, J.-F. (2015). "Hawkes processes in finance." Market Microstructure and Liquidity.
- Huang, W., Lehalle, C.-A., Rosenbaum, M. (2015). "Simulating and analyzing order book data: the queue-reactive model." JASA.
- Stoikov, S. (2018). "The micro-price: a high-frequency estimator of future prices." Quantitative Finance.
- Ntakaris, A., et al. (2018). "Benchmark dataset for mid-price forecasting of limit order book data with machine learning methods." J. Forecasting.
- Xu, K., Gould, M., Howison, S. (2018). "Multi-level order-flow imbalance in a limit order book." arXiv.
- Sirignano, J. (2019). "Deep learning for limit order books." Quantitative Finance.
- Sirignano, J., Cont, R. (2019). "Universal features of price formation in financial markets: perspectives from deep learning." Quantitative Finance.
- Zhang, Z., Zohren, S., Roberts, S. (2019). "DeepLOB: deep convolutional neural networks for limit order books." IEEE Trans. Signal Processing.
- Kolm, P., Turiel, J., Westray, N. (2023). "Deep order flow imbalance: extracting alpha at multiple horizons from the limit order book." Mathematical Finance.
- Nagy, P., et al. (2023). "Generative AI for end-to-end limit order book modelling: a token-level autoregressive generative model of message flow using a deep state space network." ICAIF.
- Coletta, A., et al. (2023). "Conditional generators for limit order book environments: explainability, challenges, and robustness." ICAIF (verify).
- Prata, M., et al. (2024). "LOB-based deep learning models for stock price trend prediction: a benchmark study." Artificial Intelligence Review.
- LOB-Bench (2025). Benchmark for generative order-book models (verify: authors and venue).
- Hawkes, A. (1971). "Spectra of some self-exciting and mutually exciting point processes." Biometrika. Hawkes, A., Oakes, D. (1974). "A cluster process representation of a self-exciting process." J. Applied Probability.
- Copeland, T., Galai, D. (1983). "Information effects on the bid-ask spread." Journal of Finance.
- Farmer, J. D., Patelli, P., Zovko, I. (2005). "The predictive power of zero intelligence in financial markets." PNAS.
- Lillo, F., Mike, S., Farmer, J. D. (2005). "Theory for long memory in supply and demand." Physical Review E.
- Avellaneda, M., Reed, J., Stoikov, S. (2011). "Forecasting prices from Level-I quotes in the presence of hidden liquidity." Algorithmic Finance.
- Dayri, K., Rosenbaum, M. (2015). "Large tick assets: implicit spread and optimal tick size." Market Microstructure and Liquidity.
- Gould, M., Bonart, J. (2016). "Queue imbalance as a one-tick-ahead price predictor in a limit order book." Market Microstructure and Liquidity.
- Moallemi, C., Yuan, K. (2017). "A model for queue position valuation in a limit order book." Working paper.
- Byrd, D., Hybinette, M., Balch, T. (2020). "ABIDES: towards high-fidelity multi-agent market simulation." ACM SIGSIM-PADS.
- Vyetrenko, S., et al. (2020). "Get real: realism metrics for robust limit order book market simulations." ICAIF.
- Coletta, A., et al. (2021). "Towards realistic market simulations: a generative adversarial networks approach." ICAIF.
- Cont, R., Cucuringu, M., Zhang, C. (2023). "Cross-impact of order flow imbalance in equity markets." Quantitative Finance.
Papers and sources
Reading
The lecture retains its textbook and chapter-level bibliography: Bouchaud, Bonart, Donier and Gould, Trades, Quotes and Prices (2018); Cartea, Jaimungal and Penalva, Algorithmic and High-Frequency Trading (2015); Abergel et al., Limit Order Books (2016); Gould et al., “Limit order books” (2013). Principal papers include Cont–de Larrard (2013), Cont–Kukanov–Stoikov (2014), Huang–Lehalle–Rosenbaum (2015), Stoikov (2018), Lillo–Farmer (2004), Hawkes–Oakes (1974), Zhang–Zohren–Roberts (2019), Sirignano–Cont (2019), Kolm–Turiel–Westray (2023), and Prata et al. (2024). See the series reading map and syllabus for full coverage.
Generated outputs remain under renders/qa/quant36/ and .cache/quant36/. Rendering uses pinned successful ordinary outputs only. Do not force or rerun originals to reproduce visual QA. Current artifact-bound visual evidence is linked in the review below. CPU signal checks do not certify pronunciation or complete continuous production listening.
Review log of the earlier QA passes on this part: docs/qa/quant/part36.md.
For the researcher
The model theorem
Let (X,M) be a finite-state Markov-additive process, with integrable absolute first-move rewards. Let Q contain no-move transitions, T move transitions and R one-step expected price increment, so Q+T is stochastic. Assume rho(Q)<1 and that B=(I-Q)^(-1)T is stochastic, irreducible and aperiodic on the actual support. Then g1=(I-Q)^(-1)R is the expected first-move reward. Centering pi' g1=0 is essential. Mirror symmetry is sufficient for centering, but is not necessary.
With Pi=1 pi' and A=B-Pi, the centered adjustment is
g = sum(k>=0) B^k g1 = (I-B+Pi)^(-1)g1, with pi' g=0.
For every rho satisfying rho(A)<rho<1, a finite C_rho bounds ||B^k g1|| <= C_rho rho^k ||g1||. A bound using exactly the second eigenvalue modulus can fail with Jordan blocks; diagonalizability gives the stronger bound when applicable. The Poisson equation g=g1+Bg makes M+g(X) a martingale at move times. Solutions differ by an additive constant, fixed by stationary-mean-zero normalization or by antisymmetry under valid mirror symmetry. Physical-clock conclusions require the corresponding timing and integrability conditions.
The stored estimator sums 401 terms, comparing its result with the first 201 terms. All 20 nominal states have positive counts in this restored fit, but some two-tick states are sparse. Its spectrum, near-zero stationary reward and small series/inverse residual are algebraic diagnostics. They do not certify the observed market's Markov hypothesis. A count-weighted next-sign gap can cancel across states; neither a small gap nor small bucket drift establishes full conditional martingale behavior. The fitted simulator also has a coarse projection, so its theorem assumptions are approximate rather than automatic.
Data, scope and reproducibilityData, computation and scope
Nine unchanged originals (book, micro, ofi, memory, deep, qr, queue, edge, research) completed once each. Four BTCUSDT perpetual bookTicker daily ZIPs and two training-day aggTrades ZIPs passed the unchanged frozen-input checker. May 16–17, 2023 fit the models; May 20–21 form a short weekend evaluation. All derived grids were absent at baseline, then generated by the unchanged reader after raw verification and pinned before reuse. Original financial algorithms and 98 protected files are unchanged. No new market trial, registry mutation, refresh or sealed strategy access occurred. Registrations remain 23,552 through Part 36 and 23,562 globally. See original-output evidence.
The initial archive is partial. Grid-span hours include carried quotes and do not certify continuous message coverage. Best-quote snapshots combine events and omit deeper and hidden liquidity. Concatenating days can compress gaps at boundaries. Horizons in such calculations count observations, with nominal hundred-millisecond spacing.
The daily OFI regressions refit on the same interval they explain, including the dates held out for other experiments. They are descriptive, endogenous relations, without causal identification or robust uncertainty. The stored log-depth slope floors nonpositive slopes before logging; its plotting floor is a further display transformation. The signature statistic is mean squared mid increment divided by the number of hundred-millisecond steps, in dollars squared per hundred milliseconds, rather than a demeaned variance per second.
The network uses 30 lagged OFI, mid-change and imbalance inputs, without a spread feature. OLS fits all training observations; the MLP fits 80% and validates on the remaining 20%, with overlapping horizon labels and no purging. Direction accuracy excludes zero targets. Accuracy stratified by realized future move size is retrospective; threshold choice using evaluation scores reuses that sample. Signed mid-to-mid gains omit executable costs and inventory.
The Hawkes hour deduplicates rounded-millisecond arrival times. Its branching ratio has a latent-cluster interpretation only within the positive stationary model. The rescaled-gap KS statistic uses fitted parameters and dependent data; no calibrated goodness-of-fit p-value is claimed. A finite positive-lag ACF slope alone does not establish asymptotic long memory or identify parent-order splitting.
The fill replay assumes a negligible order, one-tick initial spread, pro-rata net cancellations, displayed-size clipping and a specified priority rule when a level disappears. At-price aggressive volume must strictly exceed ahead size. Replay orders overlap and do not affect prices. Signed markout includes the entry half-spread and excludes fees, rebates, latency and executable liquidation. Conditional front/back means use different filled sets. Their difference is not a causal priority valuation; naive standard errors are not robust intervals. Proposed Rule 36 is a research standard, not a deployed strategy, surveillance system or trading approval.
The zero-intelligence dimensional illustration defines mu as market-order volume/time, alpha as limit-order volume/(price time), delta as cancellation rate per resting order and sigma as individual order size. Its continuum spread scale is (mu/alpha) f(delta*sigma/mu), with convention-dependent constants absorbed into f. The prefactor has price units and its argument is dimensionless. Dimensional analysis alone does not determine f, arbitrary finite-tick corrections or residual causes.
中文讲义
本讲的中文说明、交易台问题与习题解答(与英文版对应)。
Problems, with worked solutions中文说明与完整解答
本讲区分公开最优报价测量、拟合预测规则、简化队列模拟器与有限状态模型定理。完整队列过程是马尔可夫的,并不保证只保留不平衡分箱后仍是马尔可夫过程。模型中的鞅价格也不等于已识别的基本价值或可成交价格。
九个未修改原始计算各执行一次并成功;六个公开日档通过冻结校验。四个网格在基线时均不存在,由原始读取器在验证原始ZIP后生成并固定哈希,后续复用不改字节。5月16、17日训练,20、21日周末检验;首日档案不完整,网格前向填充与跨日拼接影响时钟解释。98个受保护文件和原始金融算法不变,无刷新、新市场试验、注册表写入或封存策略访问。第36讲累计注册数23,552,全局23,562。日内OFI回归各日同区间重拟合,不是样本外预测或因果估计;网络准确率排除未来不变目标,验证边界未净化重叠标签。回放标记收益包括入场半价差,但省略费用、延迟、库存平仓及市场响应;条件成交组不同,普通标准误不能当作稳健区间。
零智能量纲示例中,缪为市价订单量/时间,阿尔法为限价订单量/价格/时间,德尔塔为每张挂单撤销率,西格玛为单笔规模。连续价格模型的价差尺度为 (mu/alpha) f(delta*sigma/mu),约定常数可吸收进f;前因子单位是价格,函数自变量无量纲。量纲分析不单独确定函数、任意有限价格档修正或残差原因。
基础题六道
-
流体队列时间。 假设前方5 BTC仅按固定速度减少,主动成交0.2 BTC/秒,前方撤单0.1 BTC/秒,无新优先订单加入。前方数量为
max(5-0.3t,0),到队首需5/0.3=16.6667秒。自己的1 BTC只能由成交消耗,再需1/0.2=5秒,全部成交共 21.6667秒。别人的撤单不会执行自己的订单。这里是确定性流体计算,不是随机队列首达时间的期望。 -
耗尽概率。 两侧为独立、无漂移、相同方差速率的布朗队列,买9、卖3。象限中调和退出概率在卖队列耗尽边界为1、买队列耗尽边界为0,故
u=1-(2/pi)atan(3/9)=0.7951672。不平衡启发式为9/12=0.75,两者模型不同。两队列同倍放大不变概率;布朗缩放使耗尽时间分布按倍数平方缩放,这不保证耗尽时间有有限期望。不同方差、相关或漂移会改变简单角度公式。 -
平稳Hawkes。 正线性簇模型的移民率为2/秒,分支比
n<1。各代期望数为1,n,n²,...,总家族含移民为1/(1-n)。n=0.68时家族3.125、均速率 6.25/秒;n=0.95时家族20、速率 40/秒。68%与95%是该模型潜在后代占比,不是被识别的交易者因果反应比例。n=1时期望家族发散,不能推出有限正平稳均值;n>1时平稳均值公式无效。 -
符号和方差。 设平稳、中心化、单位方差符号协方差
C(l)~c l^(-gamma),c>0且0<gamma<1。展开平方得Var(S_n)=n+2 sum_(l<n)(n-l)C(l)。黎曼和给出sum(n-l)l^(-gamma)~n^(2-gamma)/[(1-gamma)(2-gamma)],故主项为2c n^(2-gamma)/[(1-gamma)(2-gamma)],快于n增长。gamma=0.85时指数 1.15。有限窗口拟合斜率不能证明这些渐近假设;由符号和推断价格还需要冲击及流动性模型。 -
规定OFI关系。 在固定深度关系
Delta m=delta E/(2 qbar)下,价格档0.10美元、平均队列8 BTC、OFI为+12 BTC。系数0.00625美元/BTC,所以 +0.075美元=+0.75档。深度变16 BTC时为0.0375美元=0.375档。BTC单位抵消。这是规定模型的算术推论,不是反事实订单的实证因果冲击。 -
面试盘口。 买价100美元500股,卖价100.01美元100股,中点 100.005美元。相反侧数量加权为
(500×100.01+100×100)/600=100.0083333美元,偏向薄卖队列。在第2题布朗假设下,上移概率1-(2/pi)atan(1/5)=0.8743341;若首次耗尽使中点严格上或下0.005美元,则预期下一中点100.005+0.005(2p-1)=100.0087433美元。多次变动微价格另需转移模型与归一化。把本讲模拟器分箱调整无量纲搬到股票仅得约100.008美元的示例,不是独立校准估值;这些量都不保证可成交。
进阶题四道
-
准确率和成本。 100个非零未来目标中80个方向正确,条件准确率 80%。平盘样本被排除;没有其数量、预测和计分方式,无法恢复全样本准确率。设选中交易中点到中点毛收益1.5档,立即主动入场及退出各付半档价差和3档费用,净额
1.5-0.5-0.5-3-3=-5.5档,毛收益盈亏平衡需7档。仍忽略冲击、延迟;重叠预测另需持仓核算。报告标签、选择频率、基准、全目标误差、划分、成本和考虑相关性的区间,不把准确率当作盈利。 -
马尔可夫投影反例。 完整状态(1,1)和(10,10)都有不平衡1/2。下一步以0.2概率移除一个买方单位,否则不变;买队列耗尽使中点降半档。第一状态下移概率 0.2,期望变动 -0.1档;第二状态两者为零。同一投影状态内,转移和奖励规律不同,因而不满足强可合并性要求的“进入每个投影类的总概率相同”。完整链可以是马尔可夫的,但不平衡不是充分的马尔可夫可加状态。此反例不意味着所有投影都失败,也不意味着马尔可夫过程不能聚集或有厚尾。
-
回放核算。 成交概率0.82、条件一秒有符号标记收益-14.7档,未成交赋零,提交订单贡献
0.82×(-14.7)=-12.054档/笔提交。标记收益已经包含入场半价差,不能再加半档。另一规定例子成交0.8、标记-2、每次成交返佣+0.1,贡献 -1.52档/笔提交。前后位置之差仅比较各自不同成交集合的这一毛函数。未成交机会、费用、库存平仓、标记时点后的损益与市场反应尚缺,不是完整净盈利或因果队列位置定价。 -
撤单未必改善。 等概率状态A、B的订单原本全部成交,标记分别-1与+3档。不撤单条件均值和提交贡献均为
(-1+3)/2=+1档。错误信号只在B偏空并撤单,成交率变1/2,条件标记降为-1,提交贡献为0.5×(-1)=-0.5档,所以无改善保证。应在独立数据上评估冻结且延迟可行的撤单策略,匹配下单机会,建模撤单成功、队列规则、成交选择、费用、库存和平仓;同时报告全部提交价值与条件成交标记,并处理依赖,不在检验样本上选择规则。
资格题两道
-
中心化微价格定理。 采用上述有限状态马尔可夫可加模型和首变动绝对奖励可积条件。第一步分析给
g1=R+Qg1;因rho(Q)<1,有g1=(I-Q)^(-1)R。将所有不变价等待路径求和,得首次变价后状态律B=(I-Q)^(-1)T。由(Q+T)1=1,可得B1=(I-Q)^(-1)(I-Q)1=1。强马尔可夫性逐次条件化得到E_x[M_tau_n]-M_0=sum_(k<n)(B^k g1)(x)。Solution
若镜像置换J与B交换且
Jg1=-g1,平稳分布唯一性给pi'J=pi',所以pi'g1=pi'Jg1=-pi'g1=0。无镜像也可能满足此中心化;对称充分而非必要。令Pi=1 pi',则B Pi=Pi B=Pi,k>=1时(B-Pi)^k=B^k-Pi。A=B-Pi的谱由0和B的非平稳特征值组成,模均小于1。有限维Jordan形说明,对任意rho(A)<rho<1,存在有限C_rho使||A^k||<=C_rho rho^k,多项式Jordan因子被严格谱间隙吸收;一般不能使用恰好rho(A)^k。因为Pi g1=0,作用在g1后有B^k g1=A^k g1,从而绝对收敛。Neumann级数为
g=(I-A)^(-1)g1=(I-B+Pi)^(-1)g1,且pi'g=0,满足g=g1+Bg。给定第n次变价过去,下一次M+g(X)的条件均值是M_tau_n+g1(X_tau_n)+(Bg)(X_tau_n)=M_tau_n+g(X_tau_n);奖励可积且有限状态g有界,所以是变价时刻鞅。另一修正f须满足(I-B)(f-g)=0;有限不可约链的最大值原理使调和向量只能常数,所以f=g+c1。平稳均值零固定c=0;有效镜像下反对称性也固定c=0。若d=pi'g1不为零,将奖励写为d1+h,n步期望和含nd1加有界中心化项,因此未中心化极限不存在。该证明不单独推出基本价值、可成交套利或物理时间鞅。 -
两状态和奇异极限。 令
B=[[p,1-p],[1-p,p]],0<p<1,平稳分布(1/2,1/2)。H状态下中点以q概率上1整档,否则下1档;L为镜像,因此g1=(2q-1)(1,-1)。反对称向量特征值lambda=2p-1,模小于1,故g_H=(2q-1)/(1-lambda)=(2q-1)/[2(1-p)],g_L=-g_H。p=q=3/4时偏移 1整档。固定q>1/2,p趋1时正向发散;p=1链可约,前述中心化逆矩阵论证不再适用。q=1/2时奖励恒零,每个0<p<1的归一化解为零,因此发散论断需要非零奖励。p=0时链周期为2,非零奖励的普通部分和振荡,虽然代数Poisson方程仍有中心化解。负特征值会使项交替,不能当作正持久性。比特币拟合次特征值模约0.668仅在奖励投影到相应正特征模式时支持模式几何倍数,不证明整个偏移统一放大三倍,也不证明市场服从本两状态模型。
Build the film
python -m videos.quant.quant36.compute # the part's numbers, into .cache/quant36
python tools/make.py quant36 # the narrated film, English and Chinese
EXPLAINER_TTS=silent python tools/qa_scene.py quant36 Hook # one chapter, silent, with a contact sheet
Scenes: videos/quant/quant36. Setup: see the course page. Source of these notes: the part's README and the scenes' narration.