Subscribe to get high-signal insights on how modern fintech is built.

engineering

Inside the Algorithms of the Stock Market

The Avellaneda-Stoikov model, VPIN toxicity detection, and the AMM equation that replaced all of it with one formula.

By Alex Kugell ·

Market makers quote bid and ask prices on stocks all day. The obvious approach is to center your quotes around the current price and collect the spread. If the stock is at $100, bid $99.99 and offer $100.01. Pocket the penny.

But the current price is not necessarily your fair price. If you've accumulated 5,000 shares from filling buy orders, a $1 drop costs you $5,000. Your risk is asymmetric, and your quotes should reflect that. The question is how much to adjust, and in which direction, given your inventory, the stock's volatility, and who might be trading against you.

In 2008, Marco Avellaneda and Sasha Stoikov at NYU reduced this to a closed-form formula. Eight pages. One core equation. Some version of it runs inside most major market making firms today.

The reservation price

A market maker fills buy orders and accumulates stock. It fills sell orders and goes short. That inventory swings constantly, and it's a liability.

If you're long 5,000 shares, a $1 drop costs you $5,000. The midpoint on your screen says $100, but $100 is not your fair price when you're carrying that exposure. Avellaneda and Stoikov formalized this as the reservation price, the midpoint adjusted for how much inventory risk the maker is carrying.

r = s - q · γ · σ² · (T - t)

Where s is the current mid-price, q is inventory (positive means long, negative means short), γ is the market maker's risk aversion, σ is the stock's volatility, and (T - t) is the time remaining in the trading session.

Say the stock is at $100, you hold 5 shares long, your risk aversion γ is 0.1, volatility σ is $2 per day, and you have 6 hours left (a quarter of the session).

Reservation price: 100 - 5 × 0.1 × 4 × 0.25 = $99.50.

Your internal fair value just dropped 50 cents below mid. That means you'll shade your ask price lower to encourage someone to buy from you, offloading inventory. If you were short 5 shares, the formula would push your reservation price above mid, making your bid cheaper to attract sellers.

The reservation price is a thermostat. When inventory builds up on one side, the formula pushes your quotes in the direction that corrects it. Inventory, volatility, and risk aversion jointly determine how hard.

Reservation price vs. inventory — γ=0.1, σ=$2/day, T-t=0.25
Short 5
q = -5
$100.50
Short 2
q = -2
$100.20
Flat
q = 0
$100.00
Long 2
q = 2
$99.80
Long 5
q = 5
$99.50
← Short inventory raises r (attract sellers)Mid = $100.00Long inventory lowers r (attract buyers) →

A market maker with γ = 0.01 barely adjusts for inventory. In the Avellaneda-Stoikov simulations, this produced an average profit of $68.60 per session but left the maker with a standard deviation of 5.1 shares at day's end. A maker with γ = 1 adjusts aggressively: average profit drops to $31.40, but end-of-day inventory deviation shrinks to 1.7 shares. The conservative maker earns less but sleeps better.

The optimal spread

Where you place your quotes relative to the reservation price is the spread decision. Avellaneda and Stoikov derived the optimal total spread (bid-to-ask distance).

δᵃ + δᵇ = γσ²(T - t) + (2/γ) · ln(1 + γ/k)

The first term is the inventory risk premium. It scales with volatility and time. A stock that moves $2 per day needs a wider spread than one that moves $0.50, because the price is more likely to run away from the market maker between filling a buy and filling a sell.

The second term depends on k, a parameter from the order arrival model. Orders arrive at rate λ(δ) = A · exp(-kδ), meaning the further your quote is from mid, the fewer orders you get. When k is large, orders dry up quickly as you widen the spread, so you keep it tight to maintain flow. When k is small, customers are price-insensitive and you can afford to widen.

In the paper's simulations with γ = 0.1 and k = 1.5, the optimal strategy produced an average spread of $1.49 on a $100 stock and a profit of $65 per session. That spread is wider than what you see on liquid stocks today, where competition has compressed it to a penny. The model gives the theoretical optimum for a single market maker. In practice, dozens of firms are quoting the same stock, and the spread converges to the point where the marginal maker barely breaks even.

Detecting informed flow

Inventory risk is only half the problem. The optimal spread formula says nothing about whether the person on the other side of your trade knows something you don't.

A hedge fund executing a large directional bet looks different from a retail investor buying 100 shares of Apple. If a market maker fills the hedge fund's buy order, the stock is likely to move up after the trade, and the maker's realized spread shrinks or turns negative. The hedge fund was right about direction, the maker paid for being on the other side, and that cost is adverse selection.

The spread formula handles inventory risk but not information risk. A market maker needs a way to measure how much of its current order flow comes from counterparties who know something it doesn't. In 2012, Easley, López de Prado, and O'Hara published a metric for exactly this: VPIN, Volume-Synchronized Probability of Informed Trading.

VPIN = Σ|Vˢ - Vᴮ| / (nV)

The sum runs over n volume buckets, each containing V shares of trading volume. Within each bucket, volume is classified as buy-initiated (Vᴮ) or sell-initiated (Vˢ) using a technique called Bulk Volume Classification.

Take a bucket of 10,000 shares traded while the stock moved from $100 to $101. The price went up, so more of that volume was probably buy-initiated. BVC uses the standard normal CDF to split it: Z(ΔP/σ) of the volume is classified as buys, the rest as sells.

If the price change divided by the typical standard deviation gives a z-score of 1.0, then Z(1.0) = 0.84. So 8,400 shares are classified as buys, 1,600 as sells, and the imbalance is |8,400 - 1,600| = 6,800.

VPIN calculation pipeline
1
Volume arrives
10,000 shares trade
V = 10,000
2
Bucket fills
Volume-synced, not clock-synced
1 of n buckets
3
BVC classifies
Z(ΔP/σ) splits buy vs sell
8,400 B / 1,600 S
4
Imbalance computed
|Vˢ - Vᴮ| per bucket
|6,800|
5
VPIN updated
Σ imbalances / (nV)
0 → 1 scale

A VPIN reading near 0 means buy and sell volume are roughly balanced in every bucket. Order flow is uninformed. A reading near 1 means almost all volume is on one side. Someone is pushing.

What makes VPIN different from older toxicity measures is volume-synchronized time. Instead of measuring toxicity every minute or every hour, VPIN updates after every V shares trade. On a quiet day, that might take an hour. On a volatile day, 30 seconds.

On May 6, 2010, the day of the Flash Crash, the standard sample window produced 137 VPIN estimations versus roughly 50 on a normal day. Volume-time compressed. By 12:17pm, the lookback window covered only half a day of clock time.

The algorithm was updating faster because trading was accelerating, and it detected the toxicity buildup before prices collapsed.

A market maker running VPIN in real time uses it to adjust quotes dynamically, widening the spread or pulling quotes when toxicity spikes and tightening to capture more flow when it drops. The optimal spread formula has no equivalent signal on its own.

Spread decomposition

Adverse selection sounds theoretical until you measure it. The SEC's Rule 605, amended in March 2024, requires brokers to report execution quality, and the data breaks the spread into components that isolate exactly how much informed flow costs.

Effective spread = 2 × |trade price - midpoint| measures the cost at execution. If the midpoint is $100 and you buy at $100.005, the effective spread is one cent.

Realized spread = 2 × (trade price - midpoint at t+5min) × trade direction measures what the market maker actually earned. You bought at $100.005 and the midpoint moved to $100.02 five minutes later. The realized spread is 2 × ($100.005 - $100.02) × 1 = -$0.03. The maker lost money on that trade.

Price impact = effective spread - realized spread is the gap. It's the cost of trading against someone who was right about direction.

High VPIN readings mean the price impact component dominates, and the market maker is losing to informed traders. As VPIN drops, realized spread converges toward effective spread, and the maker keeps most of the penny.

Spread decomposition — informed trade example
Effective spread$0.01
cost at execution
DECOMPOSES INTO
Realized spread-$0.03
maker lost money
Price impact (adverse selection)$0.04
cost of informed counterparty
The maker charged $0.01 but lost $0.03. The $0.04 gap is what informed flow costs.

This decomposition turns adverse selection from a theoretical concept into a measurable cost. Rule 605 data lets anyone compute it for any stock on any venue.

The AMM equation

Optimal quoting, toxicity detection, and inventory management each run as real-time software on co-located servers. In 2018, Uniswap replaced the entire stack with one equation.

x · y = k

x is the quantity of one token, y is the quantity of the other, and k is a constant. The price at any moment is the ratio y/x.

When someone buys token X, they add Y to the pool and remove X, and the new ratio gives the new price. For a trade of Δx tokens, Δy = y · Δx / (x + Δx).

A single formula produces deterministic pricing without an order book. The pool rebalances automatically, and anyone can trade against it.

Full-range positions spread capital across all prices from zero to infinity, which is wildly capital-inefficient. Uniswap v3 (2021) lets liquidity providers deploy capital within a specific price range [pₐ, p_b]. Within that range, the position acts like a leveraged version of the constant product formula. At the boundaries, the position converts entirely to one asset, like a filled limit order.

Within a concentrated range, the virtual reserves are

x_virtual = L / √p, y_virtual = L · √p

Where L is the liquidity parameter and p is the current price. A position concentrated in a narrow range provides far more depth per dollar of capital than a full-range position. A range of $1,990 to $2,010 on an ETH/USDC pool might provide 100x the depth of a full-range position with the same capital.

A concentrated liquidity position in a narrow range is functionally identical to a limit order. The LP acts as a market maker but cannot detect toxicity, adjust for inventory skew, or defend against adverse selection.

The cost of simplification

The AMM formula treats every counterparty identically. A Uniswap pool offers the same price to a retail trader and to an arbitrage bot running latency-optimized code against centralized exchange feeds, even though the retail trader is uninformed flow and the arbitrage bot is the most informed counterparty in the system.

A traditional market maker detects the difference through VPIN, responding to informed flow by widening spreads, pulling quotes, or skewing inventory. An AMM follows its formula regardless of who is trading, with no mechanism to distinguish informed arbitrage from retail flow.

This structural blindness shows up as impermanent loss. When an arbitrageur trades against a Uniswap pool, they are trading on information the pool doesn't have: the fact that the pool's price is stale relative to the broader market. The arbitrageur buys the underpriced token from the pool, pushing the pool's price toward the market price. The LP sold low.

At a 2x price change, impermanent loss is about 5.7%. At 5x, it's about 25.5%.

IL = 2√(price_ratio) / (1 + price_ratio) - 1

Impermanent loss is adverse selection by another name. The same economic force that makes VPIN necessary in traditional markets shows up as a deterministic cost in the AMM. Where a traditional market maker can measure adverse selection through VPIN and respond by adjusting quotes, an AMM absorbs the full cost with no detection or defense mechanism.

This is why Uniswap v3's concentrated liquidity is a double-edged design. Narrow ranges amplify capital efficiency, providing more depth per dollar, but they also amplify adverse selection exposure. A position in a $20 range gets liquidated into one asset much faster than a full-range position when the price moves. The LP is a market maker with tighter spreads and no toxicity detection.

Two architectures, one problem

The optimal quoting formula, the toxicity detector, and the constant product equation all address the same problem. How do you stand on both sides of a market without getting picked off by counterparties who know more than you?

Traditional market making answers by detecting informed flow, adjusting quotes in real time, and managing inventory through complex but adaptive systems. AMMs trade that adaptiveness for a single on-chain formula with permissionless, deterministic pricing, and LPs absorb adverse selection as the cost of that simplicity.

Firms like Jump Trading and Wintermute operate in both worlds. They run Avellaneda-Stoikov style algorithms on traditional exchanges and provide concentrated liquidity on Uniswap, applying the same statistical advantages to DeFi that they built for equities. The boundary between the two architectures is blurring.

Two architectures, one problem
Traditional market maker
Optimal quoting
Avellaneda-Stoikov
Toxicity detection
VPIN / BVC
Inventory management
Reservation price skew
Adaptive
Detects informed flow, adjusts quotes, manages inventory
Uniswap AMM
x · y = k
One formula replaces all three systems
Blind
Same price for retail and arbitrage bots. Impermanent loss = undefended adverse selection.

The math underneath is the same. The reservation price measures risk, VPIN measures information asymmetry, and impermanent loss is the cost of ignoring both. Whether the venue is the NYSE or a smart contract on Ethereum, someone has to quote a price, and quoting a price means taking the other side of a bet against every counterparty who walks through the door.

Sources

Alex Kugell
Alex KugellAI/ML Engineer, Fintech Infrastructure

Writes Ledger Drift. Engineer building AI systems and financial infrastructure. Open source contributor to x402, ACK, and MPP – agentic payment protocols.

Frequently Asked Questions

What is the Avellaneda-Stoikov model and how does it work?
Avellaneda-Stoikov is a mathematical model published in 2008 that tells a market maker where to place bid and ask quotes. The core formula computes a reservation price that shifts based on inventory: if the market maker holds too much stock, their internal fair price drops below the market mid, which makes their ask cheaper and encourages sellers to take the inventory off their hands. The optimal spread widens when volatility is high and tightens when orders arrive frequently. Most production market making systems started from this model.
What is VPIN and how does it detect informed trading?
VPIN stands for Volume-Synchronized Probability of Informed Trading. It measures order flow toxicity by splitting trading volume into equal-sized buckets and computing the imbalance between buy-initiated and sell-initiated volume in each bucket. A VPIN reading near 1 means almost all volume is on one side, which suggests informed traders are moving the market. On the day of the 2010 Flash Crash, VPIN was elevated before the crash happened, detecting the toxicity buildup before prices collapsed.
Why do Uniswap liquidity providers lose money to impermanent loss?
Impermanent loss is adverse selection by another name. When an arbitrageur trades against a Uniswap pool, they are informed: they know the pool's price is stale relative to the market. The pool has no mechanism to detect this, no equivalent of VPIN or inventory skew. It offers the same price to every counterparty. A traditional market maker would widen the spread or pull quotes when it detects informed flow. The AMM formula cannot. The result is that liquidity providers systematically sell low and buy high against arbitrageurs.
How does a market maker decide how wide to set the bid-ask spread?
The Avellaneda-Stoikov formula decomposes the optimal spread into two components. The first scales with volatility and time remaining: more volatile stocks need wider spreads because the price is more likely to move against the market maker between when they buy and when they sell. The second component depends on order arrival intensity: if orders come frequently, the market maker can afford tighter spreads because they will turn over inventory faster. At a risk aversion of 0.1 and volatility of $2 per day, the model produces an average spread of about $1.49 on a $100 stock.
What is the difference between realized spread and effective spread?
Effective spread measures the cost of a trade at execution: twice the distance between the trade price and the midpoint. Realized spread measures what the market maker actually earned after accounting for subsequent price movement. The difference between the two is the price impact component, which represents the adverse selection cost. If a stock's midpoint moves against the market maker after they fill an order, the realized spread shrinks below the effective spread. That gap is the cost of trading against someone who knew more about where the price was heading.

Built by Trio, a fintech-native engineering partner helping teams build the next generation of financial technology and infrastructure.

Subscribe to Ledger Drift for high-signal insights into how modern fintech is built, from systems to code to teams.

Keep reading

engineeringWho Watches the DeFi StackTools exist to manage risk within individual DeFi protocols, but the failures that actually cause damage cross protocol boundaries.
anatomyMoney Legos: How DeFi Composability Actually WorksReceipt tokens following the ERC-20 standard let the same capital earn yield from multiple DeFi protocols simultaneously, and stack the risk identically.
engineeringHow the Stock Market Actually WorksCo-located servers, microsecond algorithms, and 50 competing venues sit between your buy order and the fill.
View more ›