Act VI · Market Microstructure
Part 38 of 43Market Making, ETFs and the Speed Race
A market maker buys at the bid and sells at the offer all day. Where does the money come from, and who takes it away?
The spread earned on each round trip is the income; the losses come from quotes that are stale when the price moves. The part replays a maker on real trade data, slow and fast, and the difference between them is the business. Optimal quotes lean against inventory (Avellaneda-Stoikov and its closed-form approximation). Tick size and queue position decide who earns the spread. Exchange-traded funds are market making across two markets, held together by creation and redemption. The speed race is given its economics: when everyone is equally fast, the spread is the price of being picked off, and a batch auction would remove it.
What you need. Parts 35 and 36.
What you will be able to do
Undergraduate
- Explain a market maker's P&L: spread earned, adverse selection, inventory risk.
- Explain how ETF arbitrage keeps a fund's price near its holdings' value.
Master's
- Fit fill intensities and compute optimal quotes with an inventory skew.
- Evaluate a quoting rule by replay on trade data, including markouts and queue position.
PhD
- Derive the sniping equilibrium of Budish, Cramton and Shim for a general jump distribution and show what frequent batch auctions change.
Industry
- Explain the economics of speed, co-location, and what public filings show about a market maker's daily P&L.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 24 min · Master's 46 min · PhD 54 min · Industry 32 min.
- 0How does a market maker earn a living?Undergraduate3 min
- 1The maker's businessUndergraduate6 min
- 2A maker on the tapeMaster's5 min
- 3Fill rates and optimal quotesMaster's5 min
- 4Tick size and queue positionMaster's4 min
- 5Making markets in ETFsUndergraduate5 min
- 6The speed raceUndergraduate5 min
- 7The economics of fast market makingIndustry4 min
- 8Rule 38: quote only what you can measureIndustry4 min
- For the researcher: the sniping equilibriumPhD8 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.
How does a market maker earn a living?Undergraduate3 min
Market making, exchange-traded funds and the speed race: the business on the other side of every order in the last three parts, and why it has become a contest of microseconds.
A simple gross-spread story. Buy at the bid and sell at the offer, if both trades occur before value changes and other costs. In the selected Bitcoin perpetual snapshots a one-tick spread is common, about four hundredths of a basis point. What remains after marking the selected fills and inventory? This part compares model-based answers with a particular public-tape reconstruction.
Three results with different scopes. In our coarse-grid replay, the slow rule loses about 20 ticks per fill marked to the final mid, and the rule that knows which trades will pass through it still loses 9. Feeding reach proxies into a quoting model suggests roughly thirty ticks. A separate optimistic reach test has positive gross marks there, without queues, fees or an inventory strategy. A simplified sniping model has a spread independent of the number of equally fast firms. That is a conditional model result; ideal repricing in a batch removes its stale-quote prize.
Why this matters. Electronic market makers are important liquidity suppliers across stocks, futures, currencies and crypto, alongside banks and other dealers. Shares vary by venue and product. They sell immediacy: an executable price now while they manage the position that results. Part thirty-seven's executor trades against them. ETF creation and redemption add a second route between share liquidity and the underlying basket.
Three distinctions. Inventory need not express a directional investment thesis, although makers can use forecasts and may carry positions overnight. The spread is gross revenue. Our simple replay loses after marking its fills; this does not establish that professional makers have costs above revenue. Many firms manage portfolios of instruments and venues with hedges and capital constraints.
Where this sits. Part thirty-five met the dealer in theory; Part thirty-six measured the queue, and Part thirty-seven the executor's cost. This part runs the dealer's business, closing Act six's look at microstructure before Part thirty-nine moves to crypto and decentralised finance.
Fifty years of the dealer's problem. Inventory models from Mark Garman, then Thomas Ho and Hans Stoll; Glosten and Milgrom's adverse selection; and in 1993 the first American ETF. Then Avellaneda and Stoikov's optimal quotes, the flash crash, Guéant, Lehalle and Fernandez-Tapia's closed form, and Albert Menkveld's study of a high-frequency market maker. And the speed race: batch auctions proposed, a speed bump approved, the economics of high-frequency trading, bond ETFs in March twenty twenty, and the race measured on the London Stock Exchange.
The plan: a consistent profit ledger; a coarse-grid maker replay; reach probabilities, model quotes and markout proxies; tick size and queues; ETF arbitrage and the historical policy chronology; the speed race and its economics; and a conditional sniping equilibrium, with a separate speed-investment game.
In the House, the market-making desk opens beside the execution desk: one sells immediacy, the other buys it, and each must know what the other is paying.
1The maker's businessUndergraduate6 min
A market maker posts prices at which it will buy and sell, and lets others choose. Its profit is what remains after everyone who chose to trade with it has been paid for knowing more, or for being faster.
The accounting first. Marked wealth is execution edge at each fill, plus rebates, plus gains on inventory as the mid moves. Epsilon is the taker's sign; the maker holds the opposite trade. This self-financing identity omits other costs. Separately, adverse markout is the subsequent mid move in the taker's direction at a specified horizon. Subtract that from the fill's execution edge to obtain a horizon-marked edge. This already includes that price move. Subtracting it again from the full inventory ledger would double-count it.
Three risks. Adverse selection: the taker knows something, either private information or just a faster read of public news. Inventory: every fill leaves a position whose price risk the maker carries until the other side arrives. And operations: a quoting engine that misbehaves for minutes can lose more than a year of spreads. Knight Capital, as reported, lost about four hundred and forty million dollars in under an hour in August twenty twelve.
A model-based spread decomposition. Stoll, then Huang and Stoll, distinguish order processing, inventory and adverse selection under their respective identification assumptions. Processing includes fees, technology and capital. Inventory carries price risk until it is offset. Adverse selection concerns conditional losses to counterparties. A simple replay's loss does not separately identify those structural components.
Recall the symmetric Glosten and Milgrom example. Value is high or low with equal prior probabilities. A fraction mu knows value; uninformed traders buy and sell with equal odds, independently of value. Conditional on a buy, high value has probability one plus mu over two. A risk-neutral competitive dealer therefore asks the conditional expected value. Spread is mu times the value range, with no fees or inventory risk. A fifth informed and a range of ten give two. Against eventual value, the expected adverse move equals the half-spread. This theoretical balance does not identify which real Bitcoin maker breaks even.
The familiar Avellaneda and Stoikov approximation. Take a driftless Brownian mid, constant-size trades and CARA utility. The reservation-price approximation falls with inventory times remaining price variance. Its approximate total spread combines risk and an arrival-rate term. The model assumes exponential conditional arrival rates with price noise independent of the arrival drivers. A tape reach fit alone does not test those assumptions, queue fills or the control problem.
A restricted revenue calculation. Suppose an independently arriving unit fill earns delta and has rate A times exp minus k delta. Ignore adverse selection, fees and inventory. Differentiating delta times that rate gives delta equals one over k as the unique interior maximum for positive A and k. Risk aversion can widen even zero-inventory quotes as well as skew them. This baseline is not a universal optimal trading distance.
In numbers. An illustrative maker: risk aversion a tenth, variance still to bear of four, and a fill decay of one and a half. The total spread is 1.69, mostly the fill-rate term, close to two over k; the risk term adds only 0.4. Holding two units, it centres its quotes 0.8 below the mid, to sell more and buy less.
The GLFT closed-form approximation. With positive A, k, gamma, a Brownian reference price, unit trades and bounded inventory, a long-horizon spectral problem gives stationary quotes. Away from binding boundaries, a further Gaussian approximation gives these formulas. A long maker raises its bid distance and lowers its ask distance. Sigma is price per square root of time. Calibration to reach proxies does not validate the arrival model; the finite-inventory exact limit also differs from this interior approximation.
How the business changed. The New York Stock Exchange historically assigned specialists with quoting obligations and privileged book information. Christie and Schultz documented avoidance of odd eighths on Nasdaq in 1994; investigations and settlements followed. Decimalization and electronic competition changed those institutions and narrowed many spreads. Specialist functions evolved rather than disappearing everywhere at once.
Who does it today. In American stocks, wholesalers internalise most retail orders off exchange and pay brokers for the flow. Electronic market makers quote on exchanges in thousands of instruments at once; Virtu disclosed a single losing day in about twelve hundred, as Part thirty-four discussed. And some venues contract designated makers to quote within a maximum spread for a minimum share of the day, in return for rebates or priority.
Order flow differs. Retail flow often has lower average adverse markout than professional arbitrage flow, but neither label proves that an individual order is informed. Segmentation can change the flow remaining on exchanges; its effect on lit spreads depends on competition and routing, rather than following mechanically from payment for order flow. Makers measure markouts by size, time and available counterparty classifications to estimate those differences.
Real makers run many books at once. A maker in a thousand stocks hedges the common factor with index futures and keeps the stock-specific inventory small: Part thirty-one's risk model, at high frequency. An options maker quotes a whole volatility surface and hedges its Greeks, as in Part eleven. And in crypto the same Bitcoin trades on many venues, as spot and perpetual: makers quote on several and hedge on the cheapest.
Pause and predict. In the specified coarse-grid maker replay, orders join behind displayed quantity, with assumed pro-rata cancellations and through-price fills. After execution price is marked to the mid one minute later, would a half-tick quoted spread alone imply positive mean profit? Predict the sign before viewing the measured conditional mark.
2A maker on the tapeMaster's5 min
The slow rule has a one-minute signed mark of -20.0 ticks per fill. Its separate final-mid profit mean is -19.8. Both omit fees and executable liquidation. We will keep the horizon and fill-selection rules visible.
The simulated maker. It posts one unit behind displayed quantity while assuming its own orders do not change prices. It reconstructs events on a hundred-millisecond grid, canceling or retaining old levels under the source's priority rules. Inventory is limited to five units each way. At-price volume must exceed the queue ahead; cancellations are allocated pro rata and trades through the price fill. These are reconstruction assumptions, not message-level queue observations.
On the seventeenth of May. The slow rule has 42,019 fills, roughly half a tick of pre-step execution edge, an average same-step mid move of -8.1, and final-mid profit of -19.8 ticks per fill. The separate one-minute column is -20.0. The fast variant knows all trades in the step before deciding whether a through-price fill survives, and has final-mid profit -8.7. Adding the imbalance rule gives -4.6. The variants select different fills and inventory paths, so this is not an identified causal speed effect.
A decomposition of the slow rule's signed one-minute mark. Pre-step execution edge, then the same-step mid move, then increments to the one-second, ten-second and one-minute marks. Those components telescope to the one-minute statistic; the half-spread is already included. The same-step increment is the largest single negative piece here, but later movement matters too. A grid cannot recover exact ordering or an actual cancel latency within that step.
Signed marks for three different selected fill sets. The first point uses the previous grid mid, the next includes the fill step, followed by one, ten and sixty grid-second marks. Near the day end, horizons are clipped. All three minute means are negative, with the filtered set least negative. This documents conditional marks under the reconstruction. It does not separate causal speed, predictive skill or market impact.
What the imbalance filter changes. It removes nearly two-thirds of the hindsight variant's selected fills. The retained set has a less negative one-second signed mark. The final-mid total loss also falls, with both a lower count and a changed mean. A product decomposition depends on the chosen reference mean; these selected comparisons do not by themselves identify a causal forecast benefit.
Possible mechanisms, not identified counterparties. Cross-venue information can make a quote stale. Liquidations can generate one-sided aggressive flow. Other makers may withdraw ahead of a move. Our single-venue aggregate tape does not identify these trader types or attribute each replay loss to them.
Compare the replay variants. The slow rule accepts through-price fills. The idealized fast rule discards them with within-step hindsight. Their final-mid means differ by about 11 ticks per selected fill. Different denominators and inventory paths prevent interpreting this as the causal value of a latency improvement or a universal upper bound.
The inventory statistic. A hard five-unit limit is the rule's only explicit inventory control. Inventory standard deviation is 3.9 units over the grid path. At a boundary it stops posting one side. Standard deviation does not report boundary occupancy or prove what causes it. GLFT supplies an alternative control model, whose performance this replay has not evaluated.
On three days, two weekdays and a Saturday. The ordering never changes: slow worst, fast better, fast and filtered best, but never positive; the best day is -2.9 ticks a fill. A quoting rule with no forecast of its own, at the touch, on this market, pays its counterparties.
Converting the illustrative final-mid loss. One ten-cent tick is 0.037 basis points at the day's representative price. The filtered rule's mean loss is 0.17 basis points per fill under this conversion. A constant rebate of that size would offset this chosen gross replay loss arithmetically. It is not a complete break-even estimate: hedging, liquidation, funding, latency and market impact are absent.
What remains unmeasured. The fast rule uses within-step hindsight; the data cannot certify real cancel speed or order precedence inside one hundred milliseconds. Queue position is reconstructed. Part thirty-six's front and back results compare different selected fill sets and are not causal priority prices. Cross-venue hedging, fees, funding and executable inventory liquidation are missing. The conclusion is limited to these specified replay rules.
Pause and predict. Avellaneda and Stoikov's model assumes quotes fill at a rate that decays exponentially with their distance from the mid. Fitted to Bitcoin's tape, how far away would its optimal quotes sit: one tick, five, or thirty?
3Fill rates and optimal quotesMaster's5 min
At the lowest chosen risk aversion, the GLFT approximation gives 30 ticks from the mid. Its inputs include a reach-probability proxy rather than observed resting fills. We will compare it with a separate gross mark calculation, without claiming an optimized or profitable live strategy.
Measure reach first. At each second's start, take the mid from the hundred-millisecond quote grid. Count separately whether buy trades reach an ask-distance threshold and sell trades reach a bid-distance threshold, then average the two probabilities. Minus log one minus probability divided by one second is the equivalent rate for a homogeneous Poisson event. This transformation does not establish Poisson arrivals or queue fills. Fit log rate against distance: its slope is minus k. The pooled fit averages daily probabilities before taking the logarithm, not daily intensities.
The two-day reach fit. A half-tick threshold is reached on about a third of the averaged side-windows; a forty-five-tick threshold on about one in twenty. These are side reach events, not actual fill counts. The fitted k is 0.035 per tick, so the equivalent rate halves over about 20 ticks. The near point lies above the fitted line. Large threshold reaches can accompany trading and price moves; the grid does not identify a message-level sweep mechanism.
Across the two days, fitted k is 0.026 and 0.051. These descriptive differences accompany different flow and volatility. They do not prove a sweep mechanism or parameter stability. Pooled probabilities are averaged with equal day weights before conversion to an equivalent rate. A live estimator would need a specified past-only window and out-of-sample validation.
Compare the equivalent reach rates with the fitted exponential. The half-tick rate is 63 percent above the fit. From one through thirty ticks, the mean absolute relative deviation over these chosen points is 7 percent. That is a descriptive in-sample residual, without a confidence interval. At forty-five ticks the deviation is 14 percent. Near and far thresholds need not share one constant exponential law. Neither the residual pattern nor a log-linear fit tests independent arrivals, actual queue fills or an optimal quoting policy.
Feed the proxies into the GLFT approximation. Sigma is the standard deviation of one-second mid increments, about 20 ticks per square root of a second, without a claim that the price is Brownian. At gamma equal to one ten-thousandth per tick-unit, half-spread is 30 ticks. At one hundredth it is 39, with inventory skew 28 ticks per unit. Unit size, risk preference, arrival assumptions and interior approximation matter. This is a model output, not a verified optimal quote.
A separate reach experiment. At each second's starting mid, set two distance thresholds. Count at most one reach per side per window, and mark it at the mid sixty seconds after the window started, not sixty seconds after an exact fill time. No queue, tick rounding, fees or endogenous inventory are modeled. The gross mean at five ticks is -18 ticks. It is +1 at thirty and +20 at forty-five. Agreement in distance does not validate the control model or establish executable profit.
Aggregate the reach marks per elapsed hour, counting one hypothetical unit per reached side-window. At two ticks, the loss is about 25,075 tick-units per hour. At thirty it is +509. At forty-five it is +6,979, about seven hundred dollars if a unit is one bitcoin. Windows overlap, final windows are excluded while full elapsed time is used, and inventories are unconstrained. These sums are gross marks, not returns on a specified capital base.
Interpreting the positive far-distance marks. A threshold reached during a large trade can lie beyond the later mid, consistent with an overshoot story; the calculation does not identify its cause. At forty-five ticks there are about 355 reached side-windows per hour. Optimistic fill treatment is not a mathematical upper bound on every feasible strategy. Queue priority, tick feasibility, overlapping positions and subsequent liquidation are missing.
What the comparison tests. In the baseline model, arrival drivers are independent of the Brownian price noise, while controls can adapt to the current state. Conditional tape marks reveal dependence that a constant-rate independent-driver model omits. Similarity of a suggested distance and a gross-mark crossing is not validation. State-dependent arrivals and adverse-selection models are possible extensions. Their forecasts must be validated at actual decision times, with fills and costs.
A schematic way to add a forecast. Shift a quote center by an expected price move with matching price units, while solving the chosen model's inventory and arrival problem. This is not the full Cartea, Jaimungal and Ricci solution. The horizon must match the quote decision and possible fill time. Part thirty-six supplies descriptive state-conditioned means as candidate features, not validated executable alpha or proof that one estimator is always preferable.
Pause and predict. Bitcoin's perpetual sits at a one-tick spread almost all the time. If the tick were ten times smaller, would the spread shrink ten times? Who would gain, and who would lose?
4Tick size and queue positionMaster's4 min
And the answer to the pause: no. On a book pinned at one tick, a smaller tick lets the spread narrow only to where competition would put it, and it moves the contest from queue position to price. Takers gain from the narrower spread; makers who held the front of long queues lose their rent.
A pinned spread. When the spread makers would accept is smaller than the tick, the spread sits at one tick and the queues grow long: makers who would undercut each other cannot. So they compete for priority instead of price, and priority goes to whoever arrives first: a race in speed.
A rough model substitution. Treat the aggregate trade count, about 24 per second, as a proxy investor rate. Net mid changes of at least five ticks occur about 0.42 per second, with mean size 18. These are not identified public-news events or unit uninformed arrivals. The formula then gives 0.31 tick. That is below the quoted half-tick floor in this illustrative model. It does not establish the actual natural spread, rent, or the source of the replay losses.
Queue priority changes who can execute. Part thirty-six compared front and back replay functionals on different filled sets. Their gap was not a causal price for moving one order forward. Posting earlier can obtain priority, subject to cancellation and queue rules. Some futures use pro-rata size allocation or hybrid rules. Those designs change incentives, but their welfare cannot be inferred from one replay.
Another way to share a pinned spread. Time priority, the rule of most stock and crypto books, makes speed buy position. Pro-rata matching, used in some interest-rate futures, splits each incoming order across the resting orders in proportion to their size. Then makers post far more than they want, because fills scale with size: the race moves from speed to size, and displayed depth overstates what anyone intends to trade.
Recall the chosen queue reconstruction. Its back-of-queue filled orders have a median wait around three seconds, with roughly four in five submissions filled within a minute. Front placement has a median around a fifth of a second. These conditional waiting summaries and fill probabilities have different censoring and selected sets. Smaller adverse marks do not identify less informed trader identities or a causal gain from priority.
So what is the right tick? Too large, and spreads are set by the rule, queues are long, and makers spend on speed. Too small, and anyone can step ahead of a queue by a trivial amount, so quotes flicker and the best levels thin out. Khalil Dayri and Mathieu Rosenbaum proposed choosing the tick so the average spread sits a little above one tick, where competition on price works and quotes are still worth posting.
A static fee illustration with a common price benchmark. Hold the mid fixed, with one tick between bid and ask. A taker round trip pays that spread plus two equal per-unit taker fees. A maker completing the opposite round trip earns it plus two equal rebates, before adverse marks and other costs. Fees must use matching price units; changing prices and inventory prevent interpreting this as unconditional profit.
So who gains when the tick shrinks? Once it no longer binds, competition sets the spread. Takers pay less per trade. The makers who won the queue race lose their rent. And the displayed depth at the best thins out, which can make large orders costlier even as small ones get cheaper.
Historical rule changes. The United States tick-size pilot ran from twenty sixteen to twenty eighteen for selected small stocks. Published evaluations found wider spreads and changed displayed depth, with mixed investor effects. The SEC adopted half-cent increments for qualifying stocks in twenty twenty-four. Adoption and compliance are separate dates; this is a historical example, not a statement of the rule currently in force. Crypto venues also revise increments, changing queue and price incentives.
Pause and predict. An ETF holding corporate bonds trades at eighty dollars, while the published value of its bonds is eighty-four. Who could profit, how, and why might they not?
5Making markets in ETFsUndergraduate5 min
And the answer to the pause: an authorised participant could buy the cheap ETF, redeem it for the bonds, and sell the bonds, if the bonds could really be sold at their published value. In March twenty twenty, often they could not. Exchange-traded funds are market making with a second exit.
Creation and redemption mechanics. In an in-kind structure, an authorized participant delivers a specified basket for creation-unit shares. Redemption reverses that exchange, subject to the fund's terms; cash structures differ. NAV per share is marked assets minus liabilities, divided by shares outstanding. It is not necessarily an executable basket price. Secondary-market share trades between investors and market makers do not each trigger a primary transaction with the fund.
A conditional arbitrage band. If the ETF sale proceeds exceed the executable basket purchase cost plus creation, financing and settlement costs, a participant can create and sell. Reverse the transactions for redemption at a discount. The displayed NAV inequalities are a shorthand only when NAV approximates the executable basket. Stale marks, hedging error, trading restrictions and capital constraints prevent a hard bound around published NAV.
A chosen executable-basket calculation. Buy a share for eighty dollars. Assume the delivered basket really sells for eighty-four gross, with a two-percent selling cost applied to that gross amount. Net proceeds are eighty-two dollars thirty-two, a profit of 2.32 before other costs. If executable gross is only seventy-nine despite the published mark, the same cost leaves seventy-seven dollars forty-two, a loss of two dollars fifty-eight. The example illustrates why a marked NAV need not be an executable arbitrage.
Two connected roles. Exchange market makers quote ETF shares and may hedge with futures, baskets or related funds. Authorized participants submit primary-market creation or redemption transactions under fund terms, cutoffs and settlement procedures; execution is not simply one universal end-of-day event. A dealer estimates executable fair value and the cost of that route. Authorization usually does not oblige it to arbitrage every discount; capital constraints and basket risks can make a visible gap persist.
Three details that matter. Redeeming in kind lets an American fund hand over low-cost-basis securities instead of selling them, so fewer capital gains reach shareholders. Since the SEC's twenty nineteen ETF rule, funds may accept custom baskets that differ from their holdings, which helps bond funds. And some funds create in cash, so the fund itself trades the securities; the first American spot Bitcoin funds, approved in January twenty twenty-four, were set up that way.
How the price is watched. Many exchanges publish an indicative value of the basket every fifteen seconds, from its holdings' last prices. The premium is the price over the official value, minus one. But makers do not quote off published values. They build their own fair value from the most liquid related prices, futures and other funds, which is why they can quote a bond fund when the bonds themselves are not trading.
March twenty twenty as a literature case. BIS researchers documented bond ETF dislocations and the difficulty of arbitraging illiquid holdings during stress. A price drawdown and a discount to NAV are different quantities. A close-only series cannot measure the discount, and price response alone cannot identify an announcement's causal effect. A careful study needs synchronized NAV and executable basket information, funding, creation terms and a credible identification design. We use the cited case to explain mechanisms without a new numerical price chart.
Interpreting a NAV gap. Evaluated prices for less frequently traded bonds can lag executable values, although infrequent trading does not make every mark stale. Liquid ETF shares can contribute price discovery, while also reflecting their own flow and risk premia. The cited March literature discusses valuation and constrained intermediation channels. Our illustrations do not estimate their separate contributions or show that a particular discount is an error.
Keep the chronology precise. The March twenty-third SMCCF term sheet initially specified investment-grade corporate-bond ETFs. The April ninth expansion included high-yield bond ETFs, while retaining a predominant investment-grade allocation. Announcement effects can precede purchases, but an observed recovery alone does not show that dealer balance sheets were restored by that announcement. The official term sheets establish eligibility dates; causal policy studies require additional evidence.
Daily leverage resets. In a frictionless single-asset calculation, begin with assets A zero and exposure L times assets, with no subscriptions, financing or tracking costs. After underlying return r, new assets are A zero times one plus L r, while existing exposure is L A zero times one plus r. Their difference gives the required trade L times L minus one times r times A zero. For triple leverage and a five-percent fall, sell thirty percent of beginning-of-day assets in exposure. That is not thirty percent of the reduced ending assets. For leverage between zero and one, the directional statement reverses.
Three lessons. The band is a cost, not a law: in stress the cost of balance sheet dominates. For illiquid holdings, the fund's price can be the better one, and a discount can be information. And an ETF offers liquidity on top of assets that have little. It works because market makers warehouse the gap, and it strains when they cannot.
Pause and predict. Public news moves Bitcoin's value by ten ticks. A maker's stale quote can be cancelled, or picked off by any of four rivals as fast as it is. With five equally fast firms, how often is it picked off?
6The speed raceUndergraduate5 min
And the answer to the pause: four times in five. When news is public, the maker who quoted is one runner against many, and wins the race to cancel only as often as anyone else wins the race to trade. Eric Budish, Peter Cramton and John Shim turned that into an equilibrium.
The race. News arrives: a futures price moves, or a correlated asset ticks, public information that every fast firm sees within microseconds. The maker sends a cancel; its rivals send orders to hit the stale quote; the exchange processes messages one at a time, in the order they arrive. With N equally fast firms, the maker's cancel arrives first one time in N.
The simplified role model. Assume at least two equally fast firms, positive investor and public-jump rates, a positive fixed jump, unit uninformed orders and frictionless price undercutting. A provider receives half-spread h from each investor and loses J minus h when a rival beats its cancel, for h below J. Each of the other firms wins with probability one over N. The role-indifference condition cancels N and gives h equal to lambda J times J divided by the sum of rates. This is conditional on the model's trading and competition assumptions.
Simulate it: investors at rate one, jumps of four at rate a tenth, five firms, a long run. As the half-spread widens, the maker's profit rises and each sniper's falls. They cross where the formula says, at 0.36. A narrower spread would make makers become snipers; a wider one would draw snipers into making.
A consistency check within that model. At the formula's spread, expected provider profit and each sniper's profit are equal for every chosen N. The finite Monte Carlo estimates differ slightly. Each role receives investor payments divided by N; their sum is industry profit. The spread's independence from N holds with the other assumptions fixed and does not describe arbitrary entry or speed investment.
Replay losses in dollar units. With a one-bitcoin unit and ten-cent tick, the slow rule's final-mid loss is about 83 thousand dollars on May seventeenth. The within-step hindsight variant loses about 17 thousand. The numerical gap combines altered fills and inventory paths. It is neither a measured sniping rent nor a causal dollar value of real latency. The replay omits funding, fees, hedging and executable liquidation.
Separate the speed-investment game. Suppose a fixed prize R is split equally among fast firms, with slow firms getting nothing whenever a fast firm exists. If none invests, all share R over N. Investment costs c. With m fast rivals, joining them earns R over m plus one, less c; remaining slow earns zero. For positive c below R over N, investment is strictly dominant. Everyone invests and loses c relative to the all-slow outcome. These explicit assumptions establish a prisoner's dilemma; being faster alone does not prove it.
External evidence and our proxy have different meanings. Aquilina, Budish and O'Neill used exchange message data to study London latency races and estimate their trading cost. Our hundred-millisecond Bitcoin replay cannot identify such races or convert its selected performance gap into the same structural quantity. Baron and colleagues document concentrated profits and associations with relative speed among observed high-frequency firms. Neither result identifies every benefit or cost of faster markets.
The physics of the race. The futures exchanges near Chicago and the stock exchanges near New York are about eleven hundred and fifty kilometres apart. Light in air covers that in about 3.8 milliseconds. In glass fibre, slowed by its refractive index, about 5.6. The difference, under two milliseconds, is what paid for chains of microwave towers between the two cities: a calculation from physics, not any firm's measured route.
Design proposals. Uniform-price batches can permit quote updates and price competition within an interval; stale execution can remain near its boundary or with asymmetric information. IEX introduced a three-hundred-and-fifty-microsecond access delay and mechanisms to protect certain pegged orders. Details depend on the order type and rule version. Asymmetric delays and messaging fees change incentives too. Their welfare requires modeling information, participation and routing, rather than assuming every speed expense is waste.
An illustrative uniform-price auction. Aggregate bids by limit price. Aggregate offers in the same way. At a hundred dollars and one cent, demand is eight and supply six, so six units trade; nearby candidate prices trade fewer units. Better-priced bids receive priority: all three units at a hundred and two cents, then three of the five marginal bid units, rationed pro rata under our chosen rule. This allocation rule is an assumption, not universal across auctions.
Why it has not happened. Budish, Robin Lee and Shim argue that exchanges earn from selling speed, colocation and data, and have little private reason to switch. Batching has costs too: liquidity fragments if one venue batches alone, the interval must be chosen, and new games appear at the batch boundary. And batching already exists, in opening and closing auctions: doing it ten times a second is the novelty.
Pause and predict. If a market switched to batch auctions every tenth of a second, what would happen to the sniping prize, to the spread, and to the value of being a microsecond faster?
7The economics of fast market makingIndustry4 min
The batch question, conditionally. Ideal common-information repricing before clearing removes the stale-quote prize by assumption. Inventory, private information, fees and participation can still support a positive spread. With finite latency, a small speed difference can matter near the boundary. How much it matters requires an explicit information and update model, which the binary batch flag does not supply.
Chapter seven. A handful of studies have seen inside high-frequency firms' trading through regulators' data. They tell a consistent story about where the money comes from, and who keeps it.
An attributed case study. Menkveld examined one large high-frequency market maker trading on Chi-X and Euronext and documented spread and rebate revenues. Its positioning component was negative in the study's decomposition. Net profit was positive with high turnover and actively managed inventory. This is one firm's observed business, not our coarse-grid replay made profitable merely by substituting a faster label.
Across firms. High-frequency firms both make and take liquidity, and Baron and colleagues found the aggressive, liquidity-taking ones among the most profitable. Profits concentrate in the fastest few; new entrants earn less and exit more often. And what predicts profit is rank in speed, not speed itself: the asset is being faster than everyone else, the arms race of Chapter six.
What speed uses. Colocation, feeds and technical staff have fixed and variable costs. Faster intercity links use real resources. Hardware logic can reduce processing latency. The fixed-prize toy game treats this spending as redundant. In a broader market, technology may also improve reliability, hedging or price discovery, so its entire cost is not automatically social waste.
How inventory is really managed. A maker in many names accumulates small positions everywhere. The common factor is hedged at once in the most liquid instrument, an index future: Part thirty-one's risk model in real time. What remains is small and specific to each name, and is shed by skewing quotes, the way Menkveld's maker unwound within minutes.
In stress. In normal times, competition among fast makers has narrowed spreads in most markets. When volatility jumps, so do adverse selection and inventory risk, and makers widen or withdraw, as on the sixth of May twenty ten and the fifteenth of October twenty fourteen. Most electronic makers are not obliged to quote. Liquidity supplied by choice can be withdrawn by choice.
Quoting obligations depend on jurisdiction and role. MiFID two established agreement and quoting requirements for covered algorithmic market-making strategies, subject to its definitions and exceptions. American designated-maker and exchange programs have venue-specific requirements and incentives. Such rules can support continuity but do not guarantee unlimited liquidity in stress. This is an institutional overview, not a current legal compliance test or a claim that every electronic firm has the same obligations.
Interpreting the measured race prize. Aquilina, Budish and O'Neill extrapolated their London estimate to a multi-billion-dollar global equity figure, with the study's sampling and scaling assumptions. Race winners receive transfers that can affect investor costs and firms' incentives. The transfer itself is not automatically a deadweight social loss. Resource spending, liquidity and information effects require a separate welfare analysis.
Options at scale. An options maker quotes every strike and expiry from one volatility surface, so a move in the surface reprices them all at once. Its inventory is its Greeks: delta hedged continuously, vega and gamma managed by skewing quotes. And it runs the same race: a stale surface is sniped like a stale quote, thousands of prices at a time.
Crypto market-making costs. Volume tiers and contractual rebates change fees, but our chosen replay rebate arithmetic does not show a viable professional business. Cross-venue hedging adds basis, funding, collateral and counterparty risks absent from the single-book reconstruction. Token-issuer contracts can also create conflicts. Specific enforcement findings must be attributed to their cases rather than generalized to every maker.
Pause and predict. The House wants to make markets in Bitcoin's perpetual. Given Chapters two to six, what three things must its desk have before it posts a single order?
8Rule 38: quote only what you can measureIndustry4 min
The proposed desk standard. Estimate horizon-consistent marked edge after rebates and all trading costs, using the desk's actual fills and decision-time information. Markout is not an extra loss to subtract again from a complete inventory ledger. Measure latency and queue treatment rather than treating our hindsight variant as a speed estimate. Specify position and loss limits, monitoring and a kill switch. These are research requirements, not deployment approval.
Chapter eight. Rule thirty-eight is a proposed research standard for a market-making desk, not evidence that the House has launched one. Quoting can accumulate losses rapidly, so risk controls and accounting must be specified before any deployment decision.
The proposed research sheet. Five audited ordinary outputs support the Bitcoin replay, reach proxies, GLFT approximation and sniping illustrations. The touch rules lose on their specified final-mid ledger. Far reach marks can be positive without defining an executable portfolio. The sub-tick sniping root is a model substitution. The bond ETF example is qualitative and sourced; it has no fresh price or NAV statistic.
Controls, before any edge. Position limits per instrument and in total, each with its hedge. Loss limits, and a switch that stops quoting automatically when losses, messages or fills move faster than expected. And pre-trade checks on every order, price collars and size limits, which in the United States the Market Access Rule requires of broker-dealers.
A possible validation sequence. First a past-only replay with measured latency, conservative queue assumptions and all execution costs. A separately authorized small live experiment could compare realized fills and marks with predeclared predictions. That difference includes model error and changing market conditions. Scaling would require independently reviewed uncertainty, controls and capital. None of these deployment experiments or approvals is performed in this lesson.
Capital and liquidity requirements. Perpetual and derivative positions require venue collateral; spot inventory also ties up funds and can have financing or settlement requirements. A stress budget needs adverse scenarios for one-sided fills, hedge slippage, funding and venue access, rather than a claim that one observed worst minute sets capital. Proposed quoting size must fit those scenarios, limits and execution assumptions. This part performs no capital approval.
Chapter three's measurement. For each second, the furthest any buy reached above the starting mid, and any sell below it, in ticks; then, for each distance, the share of seconds that reached it.
Chapter one's closed form, in four lines: the skew constant from volatility, risk aversion and the fill parameters, and the half-spread as the base term plus half the skew.
The unchanged replay excerpt. With the fast flag, it knows whether any trade in the current grid step passes through the quote and discards that fill. Otherwise a through-price trade, or at-price volume strictly exceeding reconstructed ahead quantity, fills one unit. This is an assumed event reconstruction with hindsight, not an implementable cancellation policy.
The unchanged sniping source. The closed-form root solves the stipulated role comparison. The simulation allocates jump races using one over N random priority. Setting a batch flag removes those stale trades by construction; the numerical batch interval is unused, so it cannot validate the separate finite-latency formulas.
Two desks under one roof. When the portfolio desk's order could trade against the market-making desk's inventory, crossing it inside the House saves both sides the spread. But the maker would see the executor's flow, and trading ahead of it would be front-running its own client. So the desks are separated, crossing happens only at a price fixed by the public market, and compliance reviews every case.
The proposed toolkit. Reach measurements, an approximate quoting model, a reconstructed maker replay and simplified sniping functions. Rule thirty-eight asks for one consistent horizon-specific edge calculation, actual latency and queue treatment, all costs, uncertainty, capital and kill-switch controls. ETF trades require executable baskets and financing under stress. The House has not deployed or approved these strategies; the tools are research building blocks.
The rule against three cases. A backtest of a quoting strategy: ask how fills were simulated, at the back of the queue or the front, and whether sweeps were counted. A vendor's optimal-quote model: ask for its markouts, not its fill rates. An ETF arbitrage that always works: ask what happens when the bonds cannot be sold at their published value, and whose balance sheet holds them.
For the researcher: the sniping equilibriumPhD8 min
For the researcher. We derive a unique role-indifference spread under a simplified equal-speed model and extend its root equation to integrable random jump magnitudes. We distinguish industry revenue from transfers to pure snipers. A batch exposure heuristic and an explicit speed-investment game are separate models. Simulation checks arithmetic under the source assumptions; it does not prove market-wide welfare or identify public news from Bitcoin snapshots.
The assumptions. Public value has symmetric fixed jumps of positive size J at positive rate lambda J. Independent uninformed investors arrive at positive rate lambda I and trade one unit. At least two identical-speed, risk-neutral firms have simultaneous messages ordered uniformly at random. One quotes around value and others can snipe or undercut continuously, with no tick, inventory, fees or investment cost. The conclusion is limited to this role model.
Lemma one, the payoffs. The provider earns from every investor, and loses whenever one of the other N minus one messages beats its cancel. Each other firm wins a given race one time in N. And the difference between the two roles does not contain N at all: the provider's losses and one sniper's gains add up to one whole race per jump.
Lemma two, indifference. If providing paid more than sniping, a rival would post a slightly narrower spread, take the investors, and earn more: competition on price. If it paid less, the provider would rather snipe, and no one would provide at that spread. So in any equilibrium the two roles are equally attractive.
Existence and uniqueness of the indifference root. Let D of h be investor revenue minus the jump excess rate. With positive rates and positive J, it is negative at zero and positive at J. Continuity gives a root. It increases by at least lambda I times any increase in h, so the root is unique. Inside zero to J, solve the linear equation. This establishes the unique candidate spread under the prior role and undercutting assumptions, not a complete endogenous-speed equilibrium.
The conditional result. The unique half-spread is independent of N when rates, jump sizes and the stated market design are fixed. Each of the N roles earns investor payments divided by N. Industry profit therefore equals all investor spread payments, while the N minus one pure snipers receive only N minus one over N of that amount. Sniping transfers cancel inside the industry's accounts. A separate investment game is needed to discuss speed spending.
Comparative statics with other inputs fixed. A higher public-jump rate increases this model's spread. This alone says nothing about which real correlated markets are sniped most. A higher uninformed investor rate lowers the spread for a fixed jump process and unit size. N cancels only under the equal-speed role structure. Entry can affect other parameters in real markets.
Random magnitudes U. Assume U is nonnegative, integrable, and positive with positive probability, with both arrival rates positive. The indifference equation uses the expected positive excess U minus h. The left side increases strictly; the excess is continuous and nonincreasing, bounded above by the finite mean. Thus there is exactly one positive root. If one magnitude distribution dominates another in convex order, its expected excess is no smaller at every h, so its root is no smaller. Equal mean and higher variance alone, or a generic fat-tail label, does not imply this ordering.
An arithmetic consistency check. The fixed-jump formula gives 0.364. Interpolating simulated profit differences gives 0.364. Across the selected N values, the role means are approximately equal within Monte Carlo variation. This simulation implements the stipulated race probabilities; it does not independently validate an equilibrium in observed markets.
What the batch flag actually tests. At the continuous-market spread, the five-firm simulation gives roughly 0.072 per pure sniper per time unit. With the batch flag, stale-trade losses are removed by construction. The numeric interval is not used in the unchanged algorithm, and there is no modeled cancellation latency. The provider retains investor payments at this fixed spread. The program does not simulate entry, undercutting, the new equilibrium spread or a latency-to-interval law.
The ideal repricing argument. If all providers receive public news and can replace quotes before uniform-price clearing, earlier messages within that batch need not win stale trades. With multiple providers, common information and negligible costs, competition can narrow the spread. Real latency, batch-boundary news, private information, inventory and fragmentation remain. Zero stale trades in our flagged simulation are an imposed mechanism, not a proof that every batch design eliminates those costs.
A separate exposure heuristic. Assume news has uniform phase in a batch and a deterministic quote-update latency delta. Only the final delta of an interval tau is unprotected when delta is below tau, giving an exposure fraction delta over tau. This is not yet the probability a sniper wins. If we also preserve the same conditional race and role assumptions, replacing the jump-opportunity rate by that fraction gives this illustrative root. One microsecond over one hundred milliseconds is ten to the minus five for opportunities. The spread ratio has a further rate-dependent factor. Our unchanged simulator does not test this latency model.
Separate transfers from resource costs. Investor spread payments equal industry profit in this simplified model, not profit of the pure snipers alone. With the chosen rates, payments are 0.364 per time unit. Narrower spreads can transfer surplus from firms to investors. Real resources spent on otherwise redundant speed can be a social loss, but adding the entire investor payment again would double-count a transfer. Welfare also depends on participation, information and trading benefits absent from this calculation.
Prove dominance in the separate fixed-prize game. If no rival invests, becoming the sole fast firm gains R times one minus one over N, less cost c. With m fast rivals, remaining slow gets zero, while investing gets R over m plus one, less c. The smallest gross gain across these cases is R over N. Thus positive cost below R over N makes investment strictly dominant. Every firm then gets R over N minus c, worse than the all-slow outcome by c. Total resource use is N c under these explicit assumptions.
Check three: the general condition, with Bitcoin's own jump sizes. Simulate the market with jumps drawn from every real mid change and the takers' real rate. The difference between the two roles crosses zero at 0.33 of a tick, where the condition, solved directly, puts it: 0.33.
A proxy substitution, not identification. Net mid changes occur 0.63 times per second in the snapshots, averaging 13 ticks. Treating their empirical magnitudes as independent public jumps and aggregate trade counts as uninformed unit arrivals gives a root 0.33 tick. That is below the quoted half-tick floor in this model. Snapshots combine endogenous order flow and news, traders have different sizes and information, and jumps are dependent. The result neither identifies the actual natural spread nor attributes the replay losses to another channel.
Where this sits. Budish, Cramton and Shim's paper has general jumps, the arms race, and batch auctions, with evidence from correlated futures and funds. Aquilina, Budish and O'Neill measured the races on the London Stock Exchange. And Markus Baldauf and Joshua Mollner, and Menkveld and Marius Zoican, showed that once acquiring information is a choice, faster markets can widen spreads or narrow them.
Three open questions. An equilibrium spread with private information, public jumps and inventory together, estimated from message data. When continuous and batch markets coexist, where does liquidity go, and is the result efficient? And sniping across crypto's many venues, with different latencies and no consolidated quote: who wins, and what does it cost takers?
Pause and predict. Investors arrive at rate ten and jumps of three ticks at rate two. What is the sniping half-spread? And if the jumps are one or five ticks with equal chance, the same mean?
Recap, desk questions, problemsAll tracks5 min
Marked wealth uses execution edge, rebates and inventory gains. A horizon mark is another view, not an additional loss in that ledger. Our coarse-grid touch replay loses, with different selected fills under hindsight and filtering. Reach probabilities produce equivalent rates, not queue fills. Model quotes and far reach marks are illustrations with omitted execution and inventory costs. Tick constraints change price and priority incentives.
ETF arbitrage depends on executable baskets, settlement and capital; the March twenty-twenty case is sourced literature. The initial March facility covered investment-grade bond ETFs; high-yield eligibility expanded in April. A unique role-indifference spread follows from the simplified equal-speed assumptions. Industry profit and pure-sniper transfers differ. A separate fixed-prize investment game can have a prisoner's dilemma. Rule thirty-eight is a proposed validation standard.
Three lessons. Gross execution revenue and horizon-consistent marked gains need one consistent ledger. Reach probabilities, quote-control models and executable profit are different objects requiring different validation. Tick, priority and batch rules change incentives, but a welfare conclusion needs explicit resource costs, information and participation assumptions.
The formulas with their scopes. Horizon edge uses execution edge and adverse markout once. The exponential rate is a model, fed here with reach proxies. GLFT is an interior approximation, with finite-inventory qualifications. The ETF band uses executable basket values. The sniping root is conditional on equal-speed role assumptions. The batch expression is a separate uniform-phase, fixed-latency exposure heuristic, not the output of the batch-flag simulation.
How this part connects. Backwards: Part thirty-five's dealer models become a business with costs; Part thirty-six's markouts become its profit and loss; Part thirty-seven's executor is its customer. Sideways: Part eleven's options maker is the same business in another product. Forwards: Part thirty-nine's automated makers quote by formula, Part forty-one's crises are when makers step back, and Part forty-two's learning agents take the maker's chair.
Six desk questions. How should a maker account for profit? Keep a consistent marked-wealth ledger, and do not subtract a horizon mark twice. Why skew inventory? To change the arrival incentives within the chosen model. What do reach probabilities establish? Threshold frequencies, not actual queue fills or a validated optimal quote.
What does a pinned spread change? It can shift competition toward priority, while actual rents need further evidence. What keeps an ETF near basket value? Executable creation and redemption, subject to costs and constraints rather than a hard bound at a stale published NAV. What does the sniping root establish? A conditional role spread. Industry revenue, pure-sniper transfers and investment welfare are different quantities. Complete answers are in the notes.
The random-jump pause. With investor rate ten, jump rate two and magnitude three, the root is half a tick. A one-or-five mixture has the same root because both magnitudes exceed half a tick. The positive-part function is linear on that support. Convex-order increases can leave the root unchanged; a strict widening needs additional excess mass at the relevant kink, not a generic statement about tails.
Twelve problems with complete bilingual solutions. Six basic problems cover consistent edge accounting, the Avellaneda and Stoikov approximation, Poisson-equivalent rate conversion, selected replay losses, a fixed-mid tick markup and executable ETF redemption. Four advanced problems distinguish random priority and industry accounting, the random-jump root, batch exposure from a spread ratio, and strict dominance in an explicitly specified four-firm investment game. The two qualifying problems prove the integrable random-magnitude root and convex-order comparison, then derive the CARA HJB, quote first-order condition, finite-inventory linear system and spectral limit. The exact fixed-cap risk-neutral limit must be distinguished from the interior Gaussian approximation. All units and additional assumptions belong to the problems, not to claims of identified market profit.
Where this comes back. Part thirty-nine replaces quotes with a pricing curve: the automated market maker. Part forty-one asks who provides liquidity when it vanishes. Part forty-two puts learning agents in the maker's chair. And Part forty-three asks whether anyone beats the market after paying the makers.
The cited textbooks and papers distinguish models from attributed institutional evidence. Our successful numerical originals use public Binance inputs and stipulated simulations. Chosen arithmetic is labeled separately. The ETF discussion uses the cited BIS study and official term sheets, with no newly verified price series. Exact audits, the rejected input and final review limitations are retained in the notes.
The House has a proposed framework for measuring quoting costs and testing model assumptions, not a completed live market-making business. Next, Part thirty-nine: crypto and decentralized finance, perpetual funding, curve-based liquidity and venue failures. The same distinctions between accounting, assumptions and identified evidence will matter there.
Where it goes next. Crypto rebuilds all of this with a formula in place of a dealer: Part 39. Learning market makers that find each other's prices are Part 42.
Key results
The part's results in one place, for revision.
Try it
Lab 38 · The speed race sets the spread
A liquidity provider earns the half-spread from investors and loses to snipers whenever the value jumps before it can cancel. Simulate its profit across spreads, find the zero-profit spread, compare it with Budish, Cramton and Shim's formula, then replace the continuous book with batch auctions.
python -m videos.quant.labs 38
needs numpy, scipy, matplotlib, numba · download lab38.py ·
source on GitHubEquilibrium half-spread, formula 0.1667 (lam_jump J / (lam_invest + lam_jump))
Where quoting pays what sniping pays 0.1610 (simulated, 5 equally fast firms)
At equilibrium: per unit time provider +0.388, each sniper +0.321; investors pay 1.667
Batch auctions, half-spread 0.02 provider +0.200, each sniper +0.000
GLFT quotes half-spread 0.220 at zero inventory; shade by 0.060 per unit held
Investors pay the spread; the spread pays for the arms race. With batch auctions a stale quote is never hit, so the sniping tax and most of the spread disappear.
The code (55 lines; it asserts its own result)
"""Lab 38: the market maker's spread as the price of being sniped, and quotes that lean on inventory."""
import numpy as np
from videos.quant import labs
from explainer.quant.house import making
TITLE = "The speed race sets the spread"
GOAL = ("A liquidity provider earns the half-spread from investors and loses to snipers whenever the value jumps "
"before it can cancel. Simulate its profit across spreads, find the zero-profit spread, compare it with "
"Budish, Cramton and Shim's formula, then replace the continuous book with batch auctions.")
TASKS = [
"Go from 5 to 50 fast traders. Does the equilibrium spread change? Does anyone's total profit?",
"Double the rate of investor arrivals. Who gains: investors, the provider or the snipers?",
"Use making.glft to quote with inventory: by how much should a maker long 5 units shade both quotes?",
]
def run(seed=0):
lam_invest, lam_jump, J, N, T = 10.0, 2.0, 1.0, 5, 4000.0
s_star = making.bcs_spread(lam_invest, lam_jump, J)
halves = np.linspace(0.05, 0.4, 15)
lp = np.array([making.bcs_simulate(h, lam_invest, lam_jump, J, N, T, seed=seed)["lp"] for h in halves])
sn = np.array([making.bcs_simulate(h, lam_invest, lam_jump, J, N, T, seed=seed)["sniper"] for h in halves])
zero = float(np.interp(0.0, lp - sn, halves)) # the provider is indifferent between quoting and sniping
batch = making.bcs_simulate(0.02, lam_invest, lam_jump, J, N, T, seed=seed, batch=0.1)
lab = labs.Lab()
lab.row("Equilibrium half-spread, formula", f"{s_star:.4f} (lam_jump J / (lam_invest + lam_jump))")
lab.row("Where quoting pays what sniping pays", f"{zero:.4f} (simulated, {N} equally fast firms)")
eq = making.bcs_simulate(s_star, lam_invest, lam_jump, J, N, T, seed=seed)
lab.row("At equilibrium: per unit time", f"provider {eq['lp']:+.3f}, each sniper {eq['sniper']:+.3f}; investors pay "
f"{lam_invest * s_star:.3f}")
lab.row("Batch auctions, half-spread 0.02", f"provider {batch['lp']:+.3f}, each sniper {batch['sniper']:+.3f}")
g = making.glft(A=10.0, k=5.0, sigma=0.5, gamma=0.5)
lab.row("GLFT quotes", f"half-spread {g['half_spread']:.3f} at zero inventory; shade by {g['skew']:.3f} per unit held")
lab.note = ("Investors pay the spread; the spread pays for the arms race. With batch auctions a stale quote "
"is never hit, so the sniping tax and most of the spread disappear.")
assert abs(zero - s_star) < 0.02 and abs(eq["lp"] - eq["sniper"]) < 0.08 and abs(batch["sniper"]) < 1e-9
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].plot(halves, lp, "o-", color=labs.GAIN, ms=4, label="liquidity provider")
ax[0].plot(halves, sn, "o-", color=labs.LOSS, ms=4, label="each sniper")
ax[0].axvline(s_star, color=labs.P, ls="--", lw=1)
ax[0].text(s_star + 0.005, ax[0].get_ylim()[0] + 0.1, "formula", color=labs.P, fontsize=8)
ax[0].axhline(0, color=labs.MUTED, lw=0.8)
ax[0].set(title="Profit per unit time against the quoted half-spread", xlabel="half-spread")
ax[0].legend(fontsize=8)
q = np.arange(-8, 9)
ax[1].plot(q, g["half_spread"] - g["skew"] * q, "o-", color=labs.LOSS, ms=4, label="ask distance")
ax[1].plot(q, -(g["half_spread"] + g["skew"] * q), "o-", color=labs.GAIN, ms=4, label="bid distance")
ax[1].axhline(0, color=labs.MUTED, lw=0.8)
ax[1].set(title="Optimal quotes lean against inventory (GLFT)", xlabel="inventory", ylabel="quote minus fair value")
ax[1].legend(fontsize=8)
lab.fig = fig
return lab
Now change it
- Go from 5 to 50 fast traders. Does the equilibrium spread change? Does anyone's total profit?
- Double the rate of investor arrivals. Who gains: investors, the provider or the snipers?
- Use making.glft to quote with inventory: by how much should a maker long 5 units shade both quotes?
Problems, with solutions
Try each problem before opening its solution; the last two of each set are at qualifying-exam level.
Desk questions, with solutions
- Where does profit come from?
Answer
Use one marked-wealth ledger. Per-fill horizon edge is another view with a specified horizon, not an independent extra loss. Execution revenues do not establish net profit without all costs and liquidation assumptions. - Why skew inventory?
Answer
Within the GLFT approximation a long position widens the bid distance and narrows the ask distance. Risk affects zero-inventory width too. Finite boundaries and the model's assumptions matter. - What do reach rates establish?
Answer
Threshold frequencies and Poisson-equivalent rates; they do not establish queue fills, independent price innovations or an optimal executable quote. - What does a binding tick change?
Answer
It can move competition from price to priority or size. A selected front/back replay gap is not an identified causal priority price or total rent. - What keeps ETF shares near basket value?
Answer
Creation and redemption at executable prices, net of all costs and constraints. A stale published NAV need not be realizable. - What does the sniping root prove?
Answer
A unique role-indifference spread under the stated competition assumptions. Industry revenue, pure-sniper transfers, real resource spending and welfare are separate objects.
Problems, with worked solutions
Twelve problems, with complete solutions
The first six are basic, the next four advanced, and the final two qualifying-exam level. Their givens match the three enlarged on-screen pages.
-
Consistent edge. Chosen horizon: execution edge 0.5 tick, rebate 0.2, adverse taker-direction mid move +0.9. Compute marked edge; state why it is not an extra term in the inventory ledger.
Solution
Execution edge is +0.5 tick, rebate +0.2 and the subsequent adverse taker-direction mid move +0.9. Horizon marked edge is
0.5+0.2-0.9 = -0.2 tick/fill. A negative signed maker mark and a positive adverse taker mark use opposite signs. This is not a further -0.9 term to subtract from a ledger already including the same inventory price move. Other costs and horizon risk are not included. -
Avellaneda–Stoikov approximation. AS approximation: \(\gamma=0.1\), \(\sigma^2(T-t)=4\) price units squared, \(k=1.5\), \(q=2\). Compute total spread and reservation shift.
Solution
With gamma 0.1, remaining price variance 4, k 1.5 and inventory 2, approximate total spread is
gamma*variance + (2/gamma)*log(1+gamma/k) = 0.4+20*log(16/15) = 1.6907704price units. The reservation shift is-q*gamma*variance = -0.8price units. Gamma, inventory size and price units must be consistent. This is the stated approximation under its Brownian/CARA/exponential-arrival assumptions. -
Convert reach probabilities before fitting. One-second reach probabilities are 0.30 at 1 tick and 0.05 at 45 ticks. Convert to Poisson-equivalent rates and solve the two-point exponential \(k\) and half-distance.
Solution
Over one second,
lambda1=-log(0.70)=0.35667494/sandlambda45=-log(0.95)=0.05129329/s. For two points onlambda(delta)=A exp(-k delta),k=log(lambda1/lambda45)/44, approximately 0.0441 per tick, and the rate halves overlog(2)/k, approximately 15.7 ticks. A fit to probability itself gives a different coefficient and does not solve this question. A islambda1*exp(k). None of this conversion proves actual queue execution or a Poisson process. -
Selected replay losses. Slow and hindsight variants lose 20 ticks on 40{,}000 fills and 9 on 20{,}000. Compute total-loss gap; why is this not causal speed value?
Solution
Slow loss is
20*40,000=800,000tick-units; hindsight loss is9*20,000=180,000. The total-loss difference is 620,000 tick-units. With a one-bitcoin unit and $0.10 tick that is $62,000 under the chosen marking convention. Changed selection, number of fills and inventory paths prevent calling it a causal latency value. It is not a universal speed bound or an executable profit forecast. -
Tick markup. Fixed-mid illustration: one-cent spread versus 0.3-cent unconstrained spread, no fees or adverse selection. Compute full-spread and per-side markup; distinguish allocation from identified profit.
Solution
In the fixed-mid, no-cost illustration, the full-spread markup is
1-0.3=0.7 cent/unitfor a completed round trip; under symmetry the per-side markup is 0.35 cent per unit filled. Time priority and pro-rata size allocation distribute execution opportunities differently. Actual expected rent additionally depends on fills, adverse selection, capital, cancellations and costs; the markup alone identifies neither who receives it nor net profit. -
Executable redemption. ETF costs \\(80; executable basket gross \\)84 and selling cost 2% of gross. Compute redemption profit. Repeat if executable gross is \\(79 despite a published NAV of \\)84.
Solution
Buy a share for $80. Gross basket proceeds $84 less a selling cost of
0.02*84=$1.68leave $82.32, hence $2.32/share, or 2.9% of $80 before other costs. If executable gross is $79, proceeds are79*0.98=$77.42, yielding -$2.58/share, even if published NAV still says $84. Financing, primary fees, settlement, basket differences and price risk can change these results. Published NAV alone does not create a locked-in arbitrage. -
Random priority and rents. Profitable stale-quote race, uniform independent priority among \(N\) equal-speed messages. Compute sniping probability for \(N=5,10\), and pure-sniper aggregate profit as a share of industry profit.
Solution
For a profitable stale quote and N equally likely first messages, cancellation wins with probability
1/N; a pure sniper wins with probability1/Nindividually, and any sniper wins(N-1)/N. Thus the aggregate sniping probabilities are 4/5 and 9/10 at N=5 and 10. At the role root, each role's expected profit ispi*=lambdaI*h*/N. Industry profit isN*pi*=lambdaI*h*; aggregate profit of the N-1 pure snipers is only(N-1)/Nof this. Conditional jump gains are transfers from the provider to snipers and cancel from industry profit. -
Same root under a particular dispersion. \(\lambda_I=10\), \(\lambda_J=2\): solve the role root for constant magnitude 3, then equal-probability magnitudes 1 and 5. Explain the equality using the positive-part function.
Solution
With rates 10 and 2 and magnitude 3,
h=2*3/(10+2)=0.5 tick. For an equally weighted mixture of 1 and 5, both magnitudes exceed h when h<1. Then10h=2*[(1-h)+(5-h)]/2=6-2h, again giving 0.5, which verifies the assumed branch. On this support the positive-part payoff is affine, so this mean-preserving spread leaves the root unchanged. Convex-order comparisons need not be strict; variance alone does not give the required order. -
Exposure is not a spread ratio. Uniform news phase, deterministic latency \(\delta=5\,\mu\)s, batch \(\tau=50\) ms. Compute exposure fraction \(u\), then \(h_u/h_1\) with \(\lambda_I=10\), \(\lambda_J=2\). State the extra race assumptions.
Solution
With uniform news phase, deterministic update latency 5 microseconds and batch length 50 milliseconds,
u=delta/tau=10^-4. This is a final-window exposure fraction, before the probability a rival wins. Preserve the continuous model's conditional race and role structure and replace its jump-opportunity rate byu*lambdaJ: thenh_u=lambdaJ*u*J/(lambdaI+lambdaJ*u). Consequentlyh_u/h_1=u*(lambdaI+lambdaJ)/(lambdaI+lambdaJ*u). For rates 10 and 2 this is approximately 0.0001199976, not 0.0001. The uniform phase, fixed latency, absence of other stale exposure and unchanged conditional competition are extra assumptions. The source batch flag tests none of them. -
Four-firm investment game. Four-firm binary investment game: fixed prize \(R\) shared by fast firms only; if none is fast all share equally. Cost \(c\) per firm. Derive gains for 0–3 fast rivals and strict dominance threshold.
Solution
Assume a fixed positive prize R per time unit, a binary speed choice, cost c>0, equal sharing among fast firms and zero for slow firms whenever any fast firm exists; if all remain slow each receives R/4. With no fast rival, investing gains
3R/4-c. With 1, 2 or 3 fast rivals, gains are respectivelyR/2-c,R/3-candR/4-c. Thus 0<c<R/4 gives strict dominance of investment. At equality there is a tie in the last case, so dominance is no longer strict. With all investing, each gets R/4-c, worse than all-slow by c; aggregate real resource cost is 4c. This is a fully specified fixed-prize game, not an inference from “a small speed edge wins” alone. -
Qualifying: integrable random magnitudes. (qual) For \(N\ge2\), positive arrival rates and integrable nonnegative jump magnitude \(U\) with \(\Pr(U>0)>0\), prove a unique role root and its convex-order monotonicity. Distinguish industry revenue from pure-sniper transfers.
Solution
Let U>=0,
0<E[U]<infinity, lambdaI>0, lambdaJ>0 and N>=2. WriteB(h)=lambdaJ E[(U-h)+]for h>=0. In the equal-speed unit-order role model,piL=lambdaI*h-(N-1)B(h)/Nand eachpiS=B(h)/N. Continuous undercutting and switching roles give the indifference candidatePhi(h)=lambdaI*h-B(h)=0; N cancels. This is a role-model result under the stated assumptions, not a characterization of all market games.Positive part is 1-Lipschitz in h, so B is finite, continuous and nonincreasing.
Phi(0)=-lambdaJ E[U]<0. SinceB(h)<=lambdaJ E[U], Phi tends to infinity. The intermediate value theorem gives existence. For h2>h1,Phi(h2)-Phi(h1)>=lambdaI*(h2-h1)>0, establishing uniqueness. Constant U=J gives the root in problem 8. Zero jump mass or zero arrival rates require separate boundary cases and are excluded by the givens.If
U1 <=cx U2in convex order, with finite equal means,(u-h)+is convex in u and henceB1(h)<=B2(h)at every h. At root h1,Phi2(h1)<=0; strict monotonicity of Phi2 impliesh2>=h1. This does not follow from equal means and larger variance alone. Equality is possible, as in problem 8. At the root B=lambdaI*h, each role earns B/N; industry receives B, pure snipers(N-1)B/N. Investor payments are transfers to the industry, not automatically an equal deadweight welfare loss. Resource costs and participation effects need a separate analysis. -
Qualifying: exact finite-cap HJB versus interior approximation. (qual) Derive GLFT's CARA HJB, quote FOC and finite-inventory linear system. Give its long-horizon spectral solution and interior Gaussian approximation; distinguish their risk-neutral limits at fixed inventory cap.
Solution
Let
dS=sigma dW, inventory q in the integers -Q,...,Q with Q>=1, unit fills, bid distance delta_b=S-b, ask distance delta_a=a-S, and intensitiesA exp(-k delta)with A,k,gamma>0. Arrival drivers are independent of W, controls predictable and admissible, and a boundary-disallowed side is omitted. Terminal utility is-exp[-gamma(x+qS)]with no liquidation penalty. The HJB is0 = u_t + (sigma^2/2)u_SS + sup_delta_b Ae^(-k delta_b)[u(t,x-S+delta_b,q+1,S)-u] + sup_delta_a Ae^(-k delta_a)[u(t,x+S+delta_a,q-1,S)-u].Set
u=-exp[-gamma(x+qS+theta_q(t))], theta_q(T)=0. At an interior admissible optimum, the bid FOC givesexp[-gamma(delta_b+theta_(q+1)-theta_q)]=k/(k+gamma). Hencedelta_b*=theta_q-theta_(q+1)+log(1+gamma/k)/gamma; replace q+1 by q-1 for the ask. If a separate nonnegative-distance or tick constraint is imposed, this unconstrained FOC must be modified at that constraint.Write
a0=log(1+gamma/k)/gamma,C=A(1+gamma/k)^(-k/gamma)/(k+gamma). Substitution yieldstheta'_q=(gamma*sigma^2/2)q^2-C*sum_neighbors exp[k(theta_neighbor-theta_q)]. Withw_q=exp(k theta_q),alpha=k*gamma*sigma^2/2andeta=A(1+gamma/k)^(-(1+k/gamma)), the exact calendar-time system isw'_q=alpha*q^2*w_q-eta*sum_neighbors w_neighbor, w_q(T)=1. There is only one neighbor at each inventory endpoint.In time to maturity tau=T-t,
w_tau=B w, withB_qq=-alpha*q^2and neighbor entries eta. This finite irreducible symmetric Metzler matrix has a strictly positive eigenvector psi for its largest eigenvalue. As tau grows, w after scalar normalization converges to psi. Therefore stationary quotes are(1/k)log(psi_q/psi_(q+1))+a0and(1/k)log(psi_q/psi_(q-1))+a0on allowed sides. The scalar exponential growth factor cancels from the ratios; the unnormalized w need not converge.Away from relevant finite boundaries, replace neighbor sums by
2psi+psi''. A Gaussian ansatzpsi(q)=exp[-b*q^2/2]balances q^2 terms withb=sqrt(alpha/eta). Thenc=b/k=sqrt[sigma^2*gamma*(1+gamma/k)^(1+k/gamma)/(2Ak)], givingdelta_b≈a0+(2q+1)c/2,delta_a≈a0-(2q-1)c/2. At zero inventory half-spread is a0+c/2. These are the interior Gaussian approximations computed in this lesson, not exact finite-Q formulas.Within that approximation, as gamma tends to zero, a0 tends to 1/k and c tends to zero. At fixed finite Q, however, the exact risk-neutral long-horizon B has zero diagonal and off-diagonal A/e. Its top eigenvector is
psi_q=cos(q*pi/(2Q+2))up to scale. Thus at q=0 the exact half-spread tends to1/k-log[cos(pi/(2Q+2))]/k, which exceeds 1/k. Taking Q large removes this boundary correction. The orders of the finite-cap, long-horizon and small-risk limits must not be conflated.
Reading and notes
The part's papers
from READING.md
- Avellaneda, M., Stoikov, S. (2008). "High-frequency trading in a limit order book." Quantitative Finance.
- Comerton-Forde, C., Hendershott, T., Jones, C., Moulton, P., Seasholes, M. (2010). "Time variation in liquidity: the role of market-maker inventories and revenues." Journal of Finance.
- Guéant, O., Lehalle, C.-A., Fernandez-Tapia, J. (2013). "Dealing with the inventory risk: a solution to the market making problem." Mathematics and Financial Economics.
- Cartea, Á., Jaimungal, S., Ricci, J. (2014). "Buy low, sell high: a high frequency trading perspective." SIAM J. Financial Mathematics.
- Hendershott, T., Menkveld, A. (2014). "Price pressures." JFE.
- Moallemi, C., Yuan, K. (2016). "A model for queue position valuation in a limit order book." Working paper.
- Guéant, O. (2017). "Optimal market making." Applied Mathematical Finance.
- Petajisto, A. (2017). "Inefficiencies in the pricing of exchange-traded funds." FAJ.
- Ben-David, I., Franzoni, F., Moussawi, R. (2018). "Do ETFs increase volatility?" Journal of Finance.
- Spooner, T., Fearnley, J., Savani, R., Koukorinis, A. (2018). "Market making via reinforcement learning." AAMAS.
- Yao, C., Ye, M. (2018). "Why trading speed matters: a tale of queue rationing under price controls." RFS.
- Baron, M., Brogaard, J., Hagströmer, B., Kirilenko, A. (2019). "Risk and return in high-frequency trading." JFQA.
- Falato, A., Goldstein, I., Hortaçsu, A. (2021). "Financial fragility in the COVID-19 crisis: the case of investment funds in corporate bond markets." J. Monetary Economics.
- Aquilina, M., Budish, E., O'Neill, P. (2022). "Quantifying the high-frequency trading 'arms race'." QJE.
- Koont, N., Ma, Y., Pástor, Ľ., Zeng, Y. (2024). "Steering a ship in illiquid waters: active management of passive funds." RFS (verify).
- SEC (2013). Order in the matter of Knight Capital Americas LLC.
- Garman, M. (1976). "Market microstructure." JFE.
- Ho, T., Stoll, H. (1981). "Optimal dealer pricing under transactions and return uncertainty." JFE.
- Stoll, H. (1989). "Inferring the components of the bid-ask spread: theory and empirical tests." Journal of Finance.
- Christie, W., Schultz, P. (1994). "Why do NASDAQ market makers avoid odd-eighth quotes?" Journal of Finance.
- Huang, R., Stoll, H. (1997). "The components of the bid-ask spread: a general approach." RFS.
- Cheng, M., Madhavan, A. (2009). "The dynamics of leveraged and inverse exchange-traded funds." J. Investment Management.
- Menkveld, A. (2013). "High frequency trading and the new market makers." J. Financial Markets.
- Budish, E., Cramton, P., Shim, J. (2015). "The high-frequency trading arms race: frequent batch auctions as a market design response." QJE.
- Dayri, K., Rosenbaum, M. (2015). "Large tick assets: implicit spread and optimal tick size." Market Microstructure and Liquidity.
- Menkveld, A., Zoican, M. (2017). "Need for speed? Exchange latency and liquidity." RFS.
- Budish, E., Lee, R., Shim, J. (2019). "Will the market fix the market? A theory of stock exchange competition and innovation." NBER WP.
- Pan, K., Zeng, Y. (2019). "ETF arbitrage under liquidity mismatch." Working paper.
- Baldauf, M., Mollner, J. (2020). "High-frequency trading and market performance." Journal of Finance.
- Aramonte, S., Avalos, F. (2020). "The recent distress in corporate bond markets: cues from ETFs." BIS Bulletin 6.
- Haddad, V., Moreira, A., Muir, T. (2021). "When selling becomes viral: disruptions in debt markets in the COVID-19 crisis and the Fed's response." RFS.
Papers and sources
Sources and reproducibility
The primary mathematical reference is Guéant, Lehalle and Fernandez-Tapia, Dealing with the Inventory Risk, especially its setup, linear transformation and spectral approximation. BCS refers to Budish, Cramton and Shim (2015), The High-Frequency Trading Arms Race. Further references include Avellaneda and Stoikov (2008); Garman (1976); Ho and Stoll (1981); Glosten and Milgrom (1985); Stoll (1989); Huang and Stoll (1997); Menkveld (2013); Cartea, Jaimungal and Ricci (2014); Dayri and Rosenbaum (2015); Menkveld and Zoican (2017); Baron et al. (2019); Pan and Zeng (2019); Baldauf and Mollner (2020); Haddad, Moreira and Muir (2021); Aquilina, Budish and O'Neill (2022). Textbooks are Guéant (2016), Cartea–Jaimungal–Penalva (2015), Lehalle–Laruelle (2018), and Gastineau (2010).
The historical ETF discussion uses Aramonte and Avalos, BIS Bulletin 6, The recent distress in corporate bond markets: cues from ETFs, and the Federal Reserve's official March 23 term sheet and April 9 term sheet. The 2024 tick amendment is described as an adoption, without claiming its historical compliance date is the current rule. Proprietary studies and firm disclosures are attributed literature findings, not numbers generated from the House's public inputs.
Local audit, failures, pinned hashes and subsequent actual visual reviews are preserved under renders/qa/quant38/. Use existing pinned ordinary outputs for rendering; do not refresh or retry the rejected ETF original. One existing pure library test is tests/test_quant_house.py::test_making_glft_fills_and_sniping. Chosen arithmetic and finite-matrix checks are distinct from new market experiments. Final visual approval will be recorded only after fresh English/Chinese construction and final render inspection; a render exit code is not approval. Continuous production listening remains a separate task.
Data, scope and reproducibilityEvidence and model scope
Five audited, unchanged ordinary computations succeeded once: fills, glft, maker, deep and bcs. glft loads the previously pinned fills output. The sixth original, etf, failed the recorded immutable checksum for yahoo/bars/HYG/2015-01-01_2020-12-31. It was invoked once; the failed key was recorded, never refreshed or retried, and the function stopped before TLT. No substitute historical fit is used. The ETF chapter uses mechanisms, chosen arithmetic and cited literature rather than a new HYG/TLT chart. The public market manifest, all financial algorithms and all 98 protected files remain unchanged. No strategy is registered: the existing count is 23,552 through Part 38; 23,562 globally.
The successful measurement inputs are Binance's public bookTicker and aggTrades for the BTCUSDT perpetual on 16, 17 and 20 May 2023. The 100 ms quote grids are authenticated independently against completed Part 37 provenance; their corresponding raw files still pass the unchanged original checker. Possible key dependencies are audited before dispatch and share a persistent rejection barrier. A possible dependency is not a claim that every original reads every key.
fill_intensitymeasures a per-side/window threshold-reach probability, averaging buy-side and sell-side events. Its-log(1-P)/dtis the rate of a homogeneous Poisson event process with the same no-event probability, not evidence that arrivals are Poisson or that an actual resting queue order fills. Pooled daily probabilities are averaged before the nonlinear conversion. The fitted pooled values are approximatelyA=0.2300/s,k=0.03530/tick.- GLFT assumes an exogenous Brownian reference price, constant trade size, exponential conditional arrival intensities, independent noise drivers and CARA utility. The source computes an interior long-horizon approximation. Its one-second mid-increment standard deviation is about 20.26 ticks/sqrt(second); a standard deviation at that sampling interval does not itself establish diffusion scaling. At the four chosen risk aversions, approximate zero-inventory half-spreads are 29.6, 32.1, 38.9 and 75.8 ticks. A reach fit does not validate optimality, queue execution or profit.
maker_replayassumes no impact from its own one-unit orders, pro-rata allocation of net cancellations, displayed-quantity clipping and a specific treatment of old levels. At-price volume must strictly exceed the quantity ahead; a through-price trade fills. The fast flag sees all through-price trades in the current grid step before discarding such fills. That is hindsight selection, not a measured cancel latency or a universal speed bound. Variants produce different selected fills and inventory paths. Final-mid P&L and one-minute signed marks are distinct statistics; late horizons are clipped at the day's end. Funding, fees, executable liquidation and cross-venue hedging are absent.- On 17 May the slow rule has 42,019 fills, a final-mid mean of -19.785 ticks and a one-minute mean of -19.981. Fast and filtered final-mid means are -8.700 and -4.575, on 19,587 and 7,061 fills. A difference between these selected means is not a causal value of speed. Inventory standard deviation does not report time spent at a boundary.
deepcounts at most one reach per side per one-second window. It marks at the mid 1, 10 or 60 seconds after the window starts, rather than after a known exact fill time. Threshold prices may require tick rounding in practice. There are no queues, constrained inventory, fees or executable liquidation; positions across windows overlap. Gross marks of about +1.03 ticks at distance 30 and +19.67 at 45, and their sums per elapsed hour, are not a capital-based return or a rigorous upper bound on feasible strategies. The denominator includes full elapsed days while final windows without a full horizon are excluded.- BCS illustrations assume at least two equally fast firms, independent positive arrival rates, unit uninformed investors, random serial priority and frictionless price undercutting. Snapshots' net mid changes are not identified public-news jumps; aggregate trades are not identified uninformed unit arrivals. The 0.332-tick empirical-magnitude root is a proxy substitution, not an estimate of the actual natural spread or an attribution of the replay losses.
- The unchanged batch flag removes stale executions by construction; its numerical interval is unused. It does not simulate latency, a new price-competition equilibrium or welfare. A uniform-phase exposure heuristic and a binary investment game are separately stated below.
Marked wealth obeys a self-financing identity: execution edge at each fill plus rebates plus gains on held inventory, before omitted costs. With taker sign epsilon, a horizon adverse mark is epsilon*(M_h-M_fill). The separate horizon edge subtracts that mark once. Subtracting it again from the full inventory ledger would double-count the same price move. A signed maker mark from execution price already includes its entry edge.
An ETF band concerns executable basket prices, primary-market terms, funding and settlement, rather than an unconditional bound around published NAV. NAV is marked assets less liabilities divided by shares. Drawdown over time and discount to contemporaneous NAV are different quantities. A close-only series does not measure NAV discount or identify the causal effect of a policy announcement. The March 23, 2020 SMCCF term sheet initially covered investment-grade corporate-bond ETFs; the April 9 expansion included high-yield ETFs. Under a frictionless leveraged-fund calculation with no flows or financing costs, rebalancing exposure is L(L-1) r A0, using beginning-of-day assets; after a -5% return, a 3x fund sells 30% of starting assets, not ending assets.
Rule 38 is a proposed research standard: use consistent accounting, conservative execution assumptions, past-only validation, measured latency and queue treatment, costs and capital. Live experiments, scaling and deployment approvals have not been performed here.
中文讲义
本讲的中文说明、交易台问题与习题解答(与英文版对应)。
导言量化金融,从零构建 — 第38部分:做市、ETF与速度竞赛
本部分结束第六幕“市场微观结构”,连接第35部分的交易商模型、第36部分的队列重建与第37部分的执行成本。核心是分清做市账本、报价控制模型、成交记录回放及市场设计论证;任何一种结果单独都不能证明可执行的盈利业务。十一章依次讨论开场、生意核算、记录回放、触达率与模型报价、最小价位与队列、ETF、速度竞赛、高频行业、拟议第38条规则、条件狙击模型及总结题。
Desk questions, with solutions六个桌面问题
- 利润如何核算?使用一个一致的标记财富账本;时限边际是另一种观察,不能重复扣标记。净利润还需费用、资金与平仓。
- 为什么倾斜库存报价?在指定GLFT近似中,持多使买距增加、卖距减少;风险也改变零库存宽度,边界和模型假设不可省略。
- 触达率说明什么?阈值频率与等效速率,不是队列成交、价格独立性或可执行最优报价。
- 被价位约束的价差改变什么?竞争可能转向优先或数量;条件回放差异不是因果优先定价或总租金。
- ETF靠什么贴近篮子价值?按可执行价格申赎并计全部成本与约束;陈旧公布净值可能无法兑现。
- 狙击根证明什么?指定等速角色模型下的唯一无差异价差;行业收入、纯狙击者转移、资源支出和福利分别核算。
Problems, with worked solutions十二道题与完整解答
前六道基础,随后四道进阶,最后两道资格考级;题面与三张放大的屏幕页一致。
-
一致边际。 入场边际+0.5档、返佣+0.2、不利主动方向中点变动+0.9,时限标记边际
0.5+0.2-0.9=-0.2档/次成交。做市方有符号标记与主动方不利标记符号相反。若库存账本已包含同一价格变动,不能另扣0.9;其他费用和风险仍缺失。 -
AS近似。 γ=0.1、剩余价格方差4、k=1.5、q=2,总价差
γ方差+(2/γ)log(1+γ/k)=0.4+20log(16/15)=1.6907704价格单位,保留价偏移-qγ方差=-0.8。风险厌恶、单位订单及价格的量纲须一致;结论依赖指定布朗/CARA/指数到达近似。 -
先转换概率。 一秒触达概率0.30与0.05给
λ1=-log(0.70)=0.35667494/秒、λ45=-log(0.95)=0.05129329/秒。两点指数拟合k=log(λ1/λ45)/44≈0.0441/档,速率减半距离log(2)/k≈15.7档,A=λ1 exp(k)。直接拟合概率比会得到不同参数,不能回答本题;等效转换也不证明实际排队成交或泊松过程。 -
选定回放损失。 慢速
20×40,000=800,000档单位,事后快速9×20,000=180,000,相差620,000档单位;一单位为1 BTC且每档0.10美元时为62,000美元。成交筛选、笔数和库存路径均变,不能称为实测延迟的因果价值、普适上界或可执行利润预测。 -
价位加成。 固定中点、无费用及逆向选择时,完整往返的全价差加成为
1-0.3=0.7美分/单位,对称每侧0.35美分。时间优先和按量分配改变成交机会;实际预期租金还需成交、信息、资本、撤单及成本,不能仅由0.7识别净盈利或领取者。 -
可执行赎回。 80美元买入,篮子毛卖价84,成本
84×2%=1.68,净82.32,赚2.32美元/份,即80的2.9%,未计其他成本。若可执行毛卖价仅79,即使公布净值84,净价79×0.98=77.42,亏2.58美元。融资、申赎费、结算、篮子差异和价格风险还可改变结果;公布净值不是锁定套利。 -
随机优先与租金。 限有利可狙击的陈旧报价,N个等概率首消息中撤单赢1/N,每个纯狙击者赢1/N,至少一家狙击赢
(N-1)/N;N=5为4/5,N=10为9/10。角色根处每家预期利润π*=λIh*/N,行业共λIh*,N-1个纯狙击者合计仅占其(N-1)/N。跳跃收益由提供者转给狙击者,在行业合计内抵消。 -
不同幅度同一根。 到达率10和2、幅度3,
h=2×3/(10+2)=0.5档。等概率1和5都超过假设根h<1,因此10h=2[(1-h)+(5-h)]/2=6-2h,仍得0.5,满足分支条件。正部函数在该支持上线性,所以此均值保持扩散不改变根;凸序比较可以不严格,较大方差本身不足。 -
暴露不是价差比。 新闻相位均匀、确定更新延迟5微秒、批长50毫秒,
u=δ/τ=10^-4是末端未保护暴露比例,尚未乘竞争者胜出概率。额外保持原条件竞赛和角色结构,以uλJ替代机会率,可得h_u=λJuJ/(λI+λJu)。因此h_u/h_1=u(λI+λJ)/(λI+λJu),到达率10和2时约0.0001199976,不是0.0001。均匀相位、固定延迟、无其他陈旧暴露及不变竞争都是额外假设,原批量标志没有检验。 -
四家投资博弈。 固定正奖池R、二元速度选择、正成本c;有快者时只有快者平分,均慢时各R/4。快对手数为0,投资增益
3R/4-c;有1、2、3个快对手,增益依次R/2-c、R/3-c、R/4-c。所以0<c<R/4给严格占优;等号时最后一种无差异,不再严格。全投各得R/4-c,比全慢各少c,资源总成本4c。必须先给这些奖池规则,不能由“一点速度优势能赢”直接推出。 -
资格题:可积随机幅度。 设U非负、
0<EU<∞、λI与λJ正、N≥2。定义B(h)=λJ E[(U-h)+]。等速单位订单角色模型中πL=λIh-(N-1)B/N、每个πS=B/N。连续压价及角色切换要求候选无差异Φ(h)=λIh-B(h)=0,N抵消;这里只刻画指定角色模型,不是所有市场博弈。Solution
正部对h是1-Lipschitz,故B有限、连续、非增;
Φ(0)=-λJEU<0,且B(h)≤λJEU使Φ趋于正无穷。介值定理给根;h2>h1时Φ(h2)-Φ(h1)≥λI(h2-h1)>0,故唯一。常幅度时得到第8题公式。零幅度或零到达率的边界情况不在题设内。若
U1≤cx U2且有限同均值,因为(u-h)+对u凸,每个h均有B1≤B2。在h1处Φ2≤0,Φ2严格增说明h2≥h1;均值相同且方差更大并不保证凸序。第8题展示可相等。根处B=λIh,各角色B/N,行业B,纯狙击者合计(N-1)B/N。投资者支付是行业转移收入,不自动等于相同数额的社会无谓损失;资源支出及参与效应另需分析。 -
资格题:有限上限精确HJB与内点近似。 参考价
dS=σdW,整数库存q=-Q,...,Q、Q≥1,单位成交,买距δb=S-b、卖距δa=a-S,强度Ae^-kδ,A、k、γ正,成交噪声驱动与W独立,控制可预见且可容许。库存端点删去不允许的一侧,终值效用-exp[-γ(x+qS)]、无额外平仓惩罚。HJB为Solution
0=u_t+(σ²/2)u_SS+sup_b Ae^-kδb[u(t,x-S+δb,q+1,S)-u]+sup_a Ae^-kδa[u(t,x+S+δa,q-1,S)-u]。令
u=-exp[-γ(x+qS+θq(t))]、θq(T)=0。内点一阶条件exp[-γ(δb+θ(q+1)-θq)]=k/(k+γ),故δb*=θq-θ(q+1)+log(1+γ/k)/γ,卖方将q+1换q-1。若另加非负距离或价格网格,约束处须修正,不能直接套内点解。定义
a0=log(1+γ/k)/γ、C=A(1+γ/k)^(-k/γ)/(k+γ),代回得θ'q=(γσ²/2)q²-CΣ邻居 exp[k(θ邻-θq)]。令wq=exp(kθq)、α=kγσ²/2、η=A(1+γ/k)^(-(1+k/γ)),精确日历时间系统为w'q=αq²wq-ηΣ邻居w邻,wq(T)=1,端点只有一个邻居。用剩余时间τ=T-t则
w_τ=Bw,B对角-αq²、邻项η。有限不可约对称Metzler矩阵的最大特征值具有严格正特征向量ψ;τ变大时w经标量归一化趋于ψ,未归一化不一定收敛。稳态买卖距分别为log(ψq/ψ(q+1))/k+a0与log(ψq/ψ(q-1))/k+a0,公因子抵消。在有限边界影响可忽略的内点,用
ψ(q-1)+ψ(q+1)≈2ψ+ψ'',取高斯ψ=exp(-bq²/2),配平q²项得b=√(α/η),c=b/k=√[σ²γ(1+γ/k)^(1+k/γ)/(2Ak)]。由相邻比得δb≈a0+(2q+1)c/2、δa≈a0-(2q-1)c/2;零库存半价差a0+c/2。这才是本部分代码计算的高斯内点近似,不是有限Q精确公式。在该近似内γ趋零,a0→1/k、c→0。若固定有限Q,精确风险中性长时限矩阵对角零、邻项A/e,首特征向量
ψq=cos(qπ/(2Q+2))。因此q=0精确半价差趋1/k-log[cos(π/(2Q+2))]/k>1/k。Q变大才消除边界修正;有限库存、长时限、小风险的极限次序不能混淆。
Papers and sources来源与复现
数学、ETF历史及监管采用上方英文区的原始论文、BIS与官方条款链接。价格跌幅没有替代重算。公开数据完整审计、拒绝键、一次执行日志及后续真实视觉观察保存在renders/qa/quant38/;渲染只使用已钉住的五个常规输出,不刷新或重跑失败ETF。纯库测试、指定数学算例不构成新市场试验。只有重新实际检查双语构建、最终节点表、动画表、原尺寸重点画面及标记区间后才能记录视觉完成;进程成功不等于批准,完整制作配音连续听审另列待办。
Review log of the earlier QA passes on this part: docs/qa/quant/part38.md.
Data, scope and reproducibility数据、核算与模型范围
五个经审计且未改动的常规原函数各执行一次并成功:fills、glft、maker、deep、bcs。glft只读取先前钉住哈希的fills。第六个etf在HYG公开数据的不可变校验处失败,错误键已写入共享拒绝表;不刷新、不重试、不使用替代历史拟合,函数也未继续读取TLT。ETF章节因此采用所引文献、机制和指定算例,没有新的HYG/TLT价格图。原金融算法、公开清单和98个受保护文件未变;没有登记策略,既有计数为本部分累计23,552、全局23,562。
成功测量使用2023年5月16、17、20日币安BTCUSDT永续公开最优报价与归集成交。100毫秒派生网格独立对照第37部分完成证据认证,原始文件仍由未改动的原校验器检查。每个函数可能使用的公开键先经审计并共享失败屏障;可能依赖不等于声称每个函数都实际读取每个键。
每秒窗口的双侧触达概率,经-log(1-P)/dt转换为具有相同无事件概率的齐次泊松等效速率;这不是实际队列订单成交率,也不能证明事件是泊松过程。汇总时先等权平均每日概率,再作非线性变换,不能称为平均每日强度。拟合约为A=0.2300/秒、k=0.03530/档。
GLFT假设外生布朗参考价、固定单位成交、指数条件强度、独立噪声驱动及CARA效用。代码计算长时限内点近似;一秒中点增量标准差约20.26档/根号秒,单一采样尺度的标准差不能验证扩散尺度关系。指定风险厌恶下零库存半价差约29.6、32.1、38.9、75.8档。触达拟合不验证实际成交或报价最优性。固定库存上限的精确小风险极限与内点近似不同,见第12题。
回放按前方数量、比例分配的净撤单、显示量截断及旧价位优先规则重建队列;同价成交量必须严格超过前方数量,穿价成交视作执行一单位。快速标志先看到当前100毫秒步内所有穿价成交再取消,属于事后筛选,不是测得的撤单延迟或普适速度上限。各规则筛选出的成交与库存路径不同;日终中点损益与一分钟有符号标记不同,日末时限还会被截断。手续费、资金费、可执行平仓和跨市场对冲均缺失。
5月17日慢速规则成交42,019次,日终标记均值-19.785档、一分钟标记-19.981档;快速及过滤规则日终均值为-8.700与-4.575档,成交数分别19,587及7,061。条件均值之差不是速度的因果价值。库存标准差不能说明边界占用比例。远档实验每侧每秒最多算一次触达,以窗口开始后60秒中点标记,未必是实际成交后60秒;没有排队、档位取整、库存限制、费用及平仓,跨窗口头寸重叠。30档约+1.03、45档约+19.67的毛标记及小时加总不是资本收益率,也不是所有可行策略的严格上界。
完整自融资账本为成交价相对同时中点的执行边际、返佣及持仓随中点变化的收益。以主动方符号ε定义不利标记ε(M_h-M_fill),指定时限边际只能减这项一次;不能再从已包含同一价格变化的库存账本中扣一次。以成交价计算的做市方有符号标记已经包含入场边际。
BCS说明模型假设至少两家等速企业、正且独立的到达率、无信息单位投资者、随机串行优先及无摩擦压价。净中点变化不是识别出的公共新闻,归集成交也不是识别出的无信息单位订单。代入经验幅度得0.332档,只是代理模型算例,不是实际自然价差估计或回放亏损归因。原批量标志直接删除陈旧执行,数值间隔未被使用;它不模拟延迟、新均衡或福利。统一相位暴露近似及二元投资博弈另有假设。
ETF净值为资产标记减负债再除以份额。套利取决于可执行篮子价值、申赎条款、资金与结算,而不是围绕公布净值的无条件硬界。跨期跌幅不同于同时点折价;仅收盘价既不能计算净值折价,也不能识别公告因果效果。2020年3月23日SMCCF最初规定投资级公司债ETF,4月9日才扩展至高收益ETF。杠杆基金无资金流、无融资费用的算例中,再平衡量为L(L-1)rA0,A0是日初资产;三倍杠杆在标的下跌5%后卖出日初资产30%的敞口,而非日末资产30%。第38条是拟议研究标准,没有进行实盘、扩容或部署审批。
Build the film
python -m videos.quant.quant38.compute # the part's numbers, into .cache/quant38
python tools/make.py quant38 # the narrated film, English and Chinese
EXPLAINER_TTS=silent python tools/qa_scene.py quant38 Hook # one chapter, silent, with a contact sheet
Scenes: videos/quant/quant38. Setup: see the course page. Source of these notes: the part's README and the scenes' narration.