NelworksNelworks
Engineering

High-Frequency Trading Orderbook

A simulation of the limit order book and the market makers who live in it — queue position, adverse selection, the latency race, and why picking pennies in front of a steamroller works when you own a faster car.

How do you make money from a stock without having any opinion about the stock?

Every other kind of trader has a view: the company is undervalued, the chart is about to break out, the internet is about to notice. High-frequency trading has no view. It trades the plumbing, EG: the queue of orders waiting at each price, the price difference between exchanges in milliseconds, the fact that someone, somewhere, is about to trade and you can be standing in front of them or out of their way.

This page simulates that plumbing. $STONK represents our fictional ticker on one exchange, at one-millisecond resolution. You observe a market maker -- the participant whose entire job is to be on both sides of the book at once.

Simulation

This is the expert screen.

If you dont understand the charts, keep reading. Come back after you finished the story.

  • One session shows twenty seconds of the book up close.
  • The verdict displays 3 different makers on the exact same order flow and their Monte Carlo PnL.
  • Pro screen is the whole session the way a desk would look at it.

Every row is a price, every column a moment, and the red/green brightness is how many shares were resting there, waiting. Most P&L charts show you what you made; this shows the thing you were standing in.

Every trade has a nice colour to label who took it -- noise, informed, sniper -- because the simulation is omniscient. Real flow is never labelled; how a maker tells the two apart after the fact is in How HFT makes money.

the market
our strategy
the race
our quote
fees: +$0.002 / −$0.003 per share
this session we made $107from 197 fillsadverse selection cost $65.50sniped 0×
1 · Liquidity over time — where resting orders sat, and what got hit (hover to scrub)
99.8099.90100.00100.10100.200 s5 s10 s15 s20 s
■ resting bids■ resting asks■ our quotes · ○ our fills— mid┄ hidden true value · vertical ┆ news● trades (green = buyer aggressed, red = seller)
2 · Our P&L, mark-to-market ($)
$0.00$50.00$100
3 · Our inventory (shares — we try to get back to 0)
-5000
4 · Liquidity (total shares within ±3 ticks from mid)
5k10k
5a · The ladder · 20.00 s
100.11100.10100.09100.08300100.07100.06600100.05100.04100.03800100.02800100.011100100.0030099.9910099.98500240099.97130099.96110099.9550099.9480099.9330099.92
■ bids■ asks■ our order, at its place in the queue
5b · Traded so far · 20.00 s
100.11100.10100.09100.08100.073300100.067200100.059300100.045000100.033700100.024000100.018000100.002390099.994340099.982890099.97990099.96170099.9599.9499.9399.92
■ shares traded■ our fills
6 · time & sales · end of session
row tint = who took the trade:noiseinformedsniperusour quote was hit
20.00s99.97100sell
19.91s99.97100sell
19.88s99.98200buy
19.88s99.98100buy
19.80s99.97300sell
19.78s99.98200buy
19.77s99.98100buy
19.77s99.98100buy
19.74s99.98100buy
19.74s99.98100buy
19.72s99.99100buy
19.72s99.98300buy
why did we get filled? (hover any chart near a ○)
19.72 s · we sold 100 at 99.99 (mid 99.98).
Queue: placed behind 100 shares, filled after 139 ms. Hit by an informed trader.
Captured 0.015/share of spread. One second later the mid was 99.98 → markout +0.000/share.
Net +$0.015/share — an informed trader hit you: the price kept going through your quote. The fill was the bad news.
7 · where the money came from
spread captured$147gross = 100%
adverse selection−$65.50−45% of gross
maker rebates$39.40+27% of gross
taker fees−$4.20−3% of gross
inventory marked to mid−$9.50−6% of gross
session P&L$107net margin 73%
every line as a share of spread captured (gross). A maker survives while adverse selection stays under 100% of it.
fills197 (19700 sh)18% of all tradesshares ahead in queue2792.8 lots ahead (0 = front)avg wait to fill120 msnews hits 2.4% of our quotesposition held (avg)15616% of the 10-lot capsniped fills00% of 2 newstime withdrawn1%of the sessionworst drawdown$11.108% of gross · 0.01% of capitalliquidity left after news25%of the depth before

Speed alone does not guarantee profit in market making; raw speed simply increases your exposure to risk, while risk discipline protects your capital.


Trading strategies here

Description

StrategySpeed & LatencyInventory Management (Skew)News HandlingKey Vulnerability
Human ScalperSlow (100 ms delay; re-quotes every 100 ms)None (quotes standard 1 lot per side)Keeps quoting through newsOutdated quotes get crossed accidentally, incurring penalty fees.
Fast, Naive MakerFast (1 ms delay; re-quotes every 5 ms)None (quotes standard 1 lot per side)Keeps quoting through newsFront-of-queue speed causes it to swallow toxic, losing trades first.
Fast, Careful MakerFast (1 ms delay; re-quotes every 5 ms)Active (shifts quotes back 1 tick per 3 lots held)Pauses (withdraws quotes for 150 ms after news)May miss small gains in extremely quiet markets due to pulling quotes.

Performance

  • Human Scalper (Uncompetitive): Too slow to react. Its outdated quotes are frequently hit by faster market participants, forcing it to pay accidental "taker" fees. It performs poorly overall, especially during news events.
  • Fast, Naive Maker (The Worst Performer): Because it is fast, it lands at the front of every order queue. However, without safety rules, it gets repeatedly hit by informed traders right before the price moves against it (adverse selection).
  • Fast, Careful Maker (Consistent Winner): It succeeds by using two key defensive rules:
  1. Inventory Skew: Pulls back bids or offers when holding too many shares, avoiding over-exposure.
  2. News Pause: Steps out of the market for 150 ms during news events to dodge sudden price shocks.

Who Is the "Sniper"?

The Sniper is an ultra-fast automated algorithm located directly inside the exchange's data center.

  • How it works: It sits idle until a public news event occurs. The instant news breaks, it sweeps up to 30 lots of stale quotes still sitting at the old price.
  • The threat: If your algorithm cannot cancel outdated quotes faster than the Sniper can execute against them, the Sniper will take your money every time news hits.

Reading the PnL (panel 7)

linewhat it iswhy it matters
spread capturedProfit earned by buying slightly below the mid-price and selling slightly above it.This is the money the job is supposed to make.
adverse selection1 second after each of our fills, where was the price? If it had moved against us, that gap multipled by shares.Shows how much money smarter, faster traders took from you.
maker rebatesThe exchange pays us $0.002 per share every time our resting order gets hit.Essential baseline income that often keeps market makers profitable after costs.
taker feesThe exchange charges us $0.003 per share when we hit someone else's order.Directly measures speed failures. Paying this means your orders were too slow.
inventory marked to midValue change of unsold shares still held in your portfolio at the end of the run.Reveals if your P&L came from actual trading edge or simple price luck while holding stock.
session P&LThe sum of spread, rebates, adverse selection, taker fees, and inventory value.The final bottom-line profit or loss for the trading session.
fillsTotal number of executed trades and overall share volume.The multiplier for your strategy—low fills mean you are barely competing.
avg shares ahead in queueWhen we placed an order, how many shares were already waiting at that same price, ahead of ours.Sitting far back means you mostly get filled during large, toxic price moves.
avg wait to fillHow long our orders sat there before getting hit.Longer wait times leave stale quotes exposed to market changes, which incurs carry risk.
fills taken by the sniperOutdated quotes hit by fast algorithms right after market news drops.The direct cost of failing to cancel stale orders faster than high-frequency snipers.
time withdrawnThe percentage of the session spent with zero quotes active in the market.Highlights the trade-off between dodging sudden market crashes and making trading income.
worst drawdownThe largest peak-to-trough drop in total equity during the trading session.The core risk metric used by risk desks to determine capital limits and strategy survival.
liquidity left after newsRemaining order depth in the book immediately following a high-speed sweep.Measures overall market fragility—when this drops to zero, flash crashes happen.

Understanding a HFT

Every trader you have heard of holds a view on value, and they differ mostly by how far ahead they look and what evidence they use.

ClassThe question they askTheir evidenceHolding period
WSBis this going to the moonvibes, momentumwhenever
Venture capitalwhat could this be worthTAM, growth, CAC vs LTVyears
Equity managerwhat is this worthearnings, margins, factor exposures, Sharpemonths to years
Technical traderwhere is the price goingthe price chart itself -- MACD, RSI, patternsdays
Social-arb traderwhere is attention goingmentions, trends, TikTokhours to days
HFTwho is about to trade, and can I be in front of them or out of their waythe order book, the queue, latencymicroseconds to seconds

HFT is the only trader that trades flow instead of value. It makes the same money whether $STONK is a great company or a fraud, because it never holds $STONK long enough for that to matter.

WSB and HFT are the two ends of one axis: one holds forever on no information, the other holds for milliseconds on nothing but information.

"HFT" names a speed tier, not a strategy. Inside it live at least three different businesses -- market making, latency arbitrage, and very-short-horizon prediction -- and they make money in different ways.

How did HFT happened?

NASDAQ started as an electronic quote board in 1971 when humans still traded by phone. After the 1987 crash, the Small Order Execution System was made mandatory so retail could always get filled, and a group of traders promptly learned to exploit it faster than the human dealers could update their quotes.

The "SOES bandits" are the first people to make a living from being quicker than the other side's screen. Electronic crossing networks followed in the 1990s, and the SEC wrote them a rulebook of their own in 1998.

Two regulatory changes then built the modern market almost by accident. Decimalization in 2001 (NYSE in January, NASDAQ in April) which replaced fractions with pennies, and the bid-ask spread -- the human market maker's whole income -- collapsed from a sixteenth of a dollar to a cent. The only way to make a living on a one-cent spread is volume, and volume means machines.

Then Regulation NMS (adopted 2005, phased in through 2007) required orders to be routed to whichever venue showed the best price, which split US trading across a dozen exchanges and handed a permanent arbitrage to whoever could see all of them fastest.

By the end of that decade, machines were roughly half of US equity volume -- the SEC's own 2010 review put the estimates at "50% or more".

The rest is the arms race becoming physical: a straight-line fiber cable dug from Chicago to New Jersey (2010, about $300 million, three milliseconds saved), then microwave towers because fiber was too slow, then a book (Flash Boys, 2014) and an exchange built around a deliberate 350-microsecond speed bump (IEX, approved 2016). Along the way HFT firms simply became the market makers that exchange specialists used to be. The casualties:

whotheir edge waswhat took itwhen
Day traders and scalpersthe spread itself: buy the bid, sell the ask, pocket an eighththe eighth became a penny, and the penny went to the machines2001-2005
Exchange specialists and dealersa human monopoly on the order flow at their postdecimalization, then Reg NMS; the post went to electronic makers2001-2007
SOES banditsbeing quicker than a dealer's handsmachines quicker than any handslate 1990s-2000s
Banks' arbitrage desksspotting the same thing priced differently in two placesthe same job, automated2000s
Long-horizon investorspatiencenet winners: they get the lowest transaction cost in history--

How does HFT work?

For each price, the exchange keeps a queue of orders waiting to trade there -- bids below the current price, asks above it -- first come, first served.

A limit order joins the back of the queue at its price. A market order sweeps the best queue first, then the next, until it is filled. Whoever is at the front of a queue when a market order arrives gets the trade. This is price-time priority.

Queue position is an asset. Two orders at the same price are not equal. The one at the front fills on the next uninformed order that comes through. The one at the back fills only when everyone ahead of it has been taken. Being last in line means you get filled precisely when you would rather not be.

The spread is not a fee; it is a price. The gap between the best bid and the best ask is what the market pays a maker to stand there. It is set by competition among makers, and it goes exactly as low as adverse selection and inventory risk allow.


How HFT makes money (ordered by impact)

1. Market making: sell the spread, many thousands of times

Quote a bid and an ask around the mid; when a buyer arrives you sell at the ask, when a seller arrives you buy at the bid, and the difference is yours.

For $STONK, that difference is a cent. Then, the exchange adds a rebate for providing the liquidity that got taken. Multiply by hundreds of thousands of fills a day and the cents add up to become a business.

$0.002 rebate for the maker and a $0.003 fee for the taker per share are the US convention: Rule 610(c) of Regulation NMS has capped the fee for taking a displayed quote at $0.003 per share since 2005, and exchanges set their rebates just under it (see any exchange price list).

That cap is scheduled to change, slowly. A 2024 amendment cuts it to $0.001; it was upheld by the D.C. Circuit in October 2025; and its compliance date has since been pushed back twice -- to November 2026 by an order of October 2025, then to the first business day of November 2027 by an order of June 2026, which also lets exchanges charge up to $0.0015 in the meantime. As of this writing (August 2026) the $0.003 cap is still the one in force, and the simulation uses it.

In the meantime, market makers watch out for adverse selection. Defined by price at the moment of the fill, subtracted by the midprice one second later.

When an uninformed trader hits you, the price wanders and you keep the spread. Low risk money.

When an informed trader hits you -- someone who knows where the price is going -- the price keeps going through your quote, and the fill was not income; it was the bad news arriving. A fill is evidence that you might have been wrong, and the market maker's real skill is telling the two kinds of fills apart and pricing the second into the spread.

This is also why the biggest HFT firms pay retail brokers for their customers' orders (PFOF). Retail flow is uninformed, so its fills low risk.

How do you tell informed flow from noise? You do not -- not at the moment of the fill. The simulation labels every trade because it is omniscient.

In real life, a maker has to count thousands of fills and sorts them by everything it can observe -- which broker the order came through, its size, how soon after a news print it arrived, which venue -- then "toxic flow" is labeled after the maker recognizes fills that kept losing.

2. Latency arbitrage: be first when the world moves

The same stock trades on many exchanges. An ETF and its basket are the same thing. A future and the spot it settles to are the same thing. When one of them moves, the others are momentarily wrong, and whoever reaches them first collects the difference.

In the simulation, anyone (not including you) who moves this fast is the sniper. When news moves $STONK's true value, every quote left on the wrong side is stale, and the sniper takes all of them -- at the old prices -- before their owners can cancel.

Whether your quote is among them is decided by one comparison: your latency against theirs.

3. Short-horizon prediction

The queue itself leaks information. Suppose a best bid has 10 times the size of the best ask, it is normal to assume the next tick is more likely to be up.

Strategies that trade that milliseconds-ahead statistics are like trying to catch a wave before it arrives.


Isn't this pennies in front of a steamroller?

By definition, yes: tiny gains, and maybe a large loss. How does the market maker not get flattened?

The trades that do get flattened -- short volatility, leveraged carry, the funds that blew up in 1998 and 2018 -- share one property HFT does not have: commitment. IE: they hold a position they cannot sell when the steamroller arrives.

The market maker is a penny-picker with no commitment, and the business is engineered around that fact:

  1. Risk is position × time, and they hold neither. A crash takes seconds to minutes to develop; a maker's exposure per fill is a few hundred shares for a few hundred milliseconds, and it does not keep what it buys: there is a hard cap (ten lots here). When it is long, its quotes shift so the next customer is more likely to buy from it than sell to it, so the position drains away on its own.
  2. The spread is the steamroller premium. They are literally paid to stand in front of a steamroller and get out of the way before it hits. If no one dares to stand, the spread gets wider until it starts to be worth it.
  3. They have the option to not be there. When news hits, or volatility jumps, a maker can quote more carefully: wider, smaller, or not at all. If enough makers do that, the spread widens until some other maker is greedy enough to take the risk at the new price. The 2010 flash crash was every maker stepping back at the same moment -- with nobody left to take the other side, prices fell through the hole until buyers were found far below. Their safety is the market's fragility.
  4. Speed reassigns the steamroller to someone slower. When news hits, the fastest firm can cancel its quotes in a millisecond; the same event then runs over whoever was still quoting. If you are fast enough, you can play hot potato with anyone without burning your own hand.
  5. The law of large numbers reduces their risk. Trade hundreds of thousands times, and your P&L stabilizes to a range you can accept.

What actually runs them over is operational, not directional: a deployment bug that kept firing orders cost one firm $440 million in 45 minutes in 2012; bad data feeds, exchange outages, or a risk module that fails launch.

The classic penny-picker is a man who picks up slowly from the road. The market maker is someone who runs fast enough to pick up any penny, and the only thing that reliably kills him is his own shoelaces.


The engineering

Latency is the time from something happening in the world to your order arriving at the matching engine.

It consists of multiple components, including the feed reaching you, your decision, and your order.

It matters because after news, every quote resting at the old price is free money for whoever reaches it first. Your quote survives only if your cancel lands before the fastest predator's order.

The cost of being slow has a shape:

loss to snipers ≈ (news events) × (how wrong a stale quote is, minus the spread it was paid) × P(your cancel arrives after the predator's order)

Only the last factor depends on speed, and it is a cliff, not a slope: faster than the sniper and we are that sniper, slower and we are sniped at every news event.

The cliff decides whether we pay the news tax, not whether we can still be profitable. A sniped fill costs us (one lot times the jump, minus the spread we were paid), and whether that tax exceeds our income depends on how often news comes and how big the jumps are, against how often we get filled and at what spread.

Since ranking, not speed, determines the winner, the race has no finish line. Every expense on tryign to win the latency game is a deadweight tax on everyone who trades -- the formal version is Budish, Cramton & Shim (2015), and the races have since been measured on exchange message data by Aquilina, Budish & O'Neill (2022):

Mean P&L per 20-second session vs our latency, three sniper speeds, 24 sessions per point · dotted verticals = the sniper's latency
  1. (Left) There's a sniper with a fixed speed. If you're faster than him, he never catches your quotes — you lose nothing to him. If you're slower, you lose all quotes to him.

  2. Past the step you're already getting caught every time. So why does revenue keep going down as you get slower? Because slow quotes are wrong quotes — the price moved and yours didn't. And why does it flatten out near zero instead of going to minus infinity? Because a really slow quoter barely trades at all. Fewer trades = less to lose. You're not winning, you're just not playing.

  3. The grey line (20 ms sniper) starts to fall way before 20 ms. This is because the sniper isn't the only guy hunting you. The informed trader may hit stale quotes, or reacts a few milliseconds after news at random times, not on a fixed clock. With the slow sniper, the informed guy now becomes the fastest hunter.

  4. (Right). A naive maker never generates revenue at any speed because he isn't cautious for informed flows. His worst spot is 5 ms: still fast enough to get filled constantly, too slow to be right about the price. Past 5 ms his line "recovers", not because it starts to make money, but because he quits.

Both MM PnL meet when their latency gets slow enough, because at 100 ms everybody is the human scalper.


How much does it cost to be fast?

The simulation lets you pick a latency with a slider. In real life, the slider is expensive. This is how HFT becomes a high CAPEX business instead of being smarter than your rivals and why individuals should give up day trading.

latencywhat it takeswho has itwhat it costs
100 msa person, a screen, a mouseyou; any retail appa laptop
20 msa program on a rented server in another city, talking to the exchange over the interneta hobbyist's algorithmhundreds of dollars a month
5 msa server in a data center near the exchange, ordinary software and network cardsa small trading firmtens of thousands a year
1 msco-location: your server in the exchange's own building, cables in the cage cut to equal length so nobody is a nanosecond closer; the exchange's direct data feeds, which arrive before the public tapea mid-size HFThundreds of thousands a year in cabinets and feeds, before people
0.1 mskernel bypass: the network card hands packets straight to your program, no operating system in between; lock-free code; clocks synchronized to nanoseconds so you can even tell who was firstmost HFT firmsengineers
0.005 msFPGAs: chips wired to read the feed and fire the order without a CPU in the loop -- about a microsecond from tick to trade, against tens of microseconds for well-written softwarethe top dozen firmsmillions in hardware, more in people
between citiesmicrowave: radio towers on the straight line between two venues, because radio through air is faster than light through glass (below)the top fewhundreds of millions

Why do people buy radio towers to solve a math problem?

Because in the late game, the race is decided by who arrives first, and arriving first is a matter of distance and hardware, not cleverness.

Light has a speed. In glass it travels at about two-thirds of its speed in air. Chicago's futures exchange and New Jersey's stock exchanges are 1,179 km apart, so light in a vacuum needs 3.93 ms one way, about 7.9 ms for the round trip.

Microwave towers on the straight line got within 0.1 ms of the physical limit by 2012, about 8 round trip, at the cost of low bandwidth and outages in rain (Laughlin, Aguirre & Grundfest 2014, who measured the drop in the timestamps of the trades themselves).

A microsecond saved in a chip is worth nothing next to a millisecond saved by a shorter path, so the money goes into tower leases and radio licenses.

Software can be copied; a tower on the straight line cannot. There is even a physics paper computing the best places on Earth to put trading nodes given the speed of light (open-access copy).


Simulation details

What the simulation ignores

herein practicewhy it matters
One venue.Latency arbitrage lives between venues: a price prints on one exchange and the race is to the 15 others.The sniper here is a stand-in for that whole cross-venue race.
The sniper and the informed trader see the true value directly.Predators infer it from correlated instruments and the queue. EG: the same stock elsewhere, the imbalance between bid and ask depth.Our losses to the sniper and the informed trader are higher here than in real life because we let our sandbox predator cheat.
Order flow is synthetic: noise traders at random depths, one informed trader, news as jumps.Hidden orders and icebergs, thousands of participants with different horizons, trades that arrive in clusters.The sandbox book is smoother than a real one, so queue estimates are easier here.
No tick-size rules, no opening or closing auctions, no halts, no short-sale limits.The tick is a rule (Rule 612); the day opens and closes with auctions; limit-up/limit-down bands and circuit breakers stop trading; Rule 201 restricts short sales after a 10% fall.Every one of these changes what a maker should quote around it.
Our maker quotes only one ticker.Makers layer several price levels, quote every venue at once, hedge inventory in correlated instruments, and manage risk across thousands of symbols.Our fills, inventory swings and P&L are stable and uniformed.
Every number is invented -- fees, rebates, latencies, the size of a news jump are all approximation.The real numbers are proprietary tick data I get sued if I share.Read the shape of the graph, not numbers

What each of our parameters do

ParameterSimple SettingWhat It Simulates
True ValueHidden price moving randomly by a fraction of a tickThe actual underlying value of the asset behind market noise.
NewsSudden price jumps of 4 to 16 ticksMajor public announcements (e.g., earnings reports, economic data, price updates).
Crowd Lag100 millisecond delayThe reaction time of average automated market participants.
Informed TraderBot trading 2–4 lots when price drifts more than 1.5 ticks from true valueInstitutional traders using private signals to pull market prices toward fair value.
SniperFast bot snapping up to 30 stale orders right after newsHigh-frequency bots picking off slow, outdated quotes.
Resting Noise~50 random limit orders per sec expiring after ~2 secondsBackground liquidity continuously building and clearing the order book.
Taking Noise~25 random market orders per secRegular retail and institutional buy/sell order flow.
Fees+$0.002 rebate for making; -$0.003 fee for takingStandard US exchange maker-taker fee structures.
Capital at Risk$100,000 maximum position size (10 lots)The baseline cash allocation used to calculate equity drawdowns.

Glossary

TermMeaning
Noise traderuninformed flow -- a fund rebalancing, a retail order; trades for reasons unrelated to where the price is going
Informed tradersomeone who knows, roughly, where the price is going and trades toward it; the fills that cost a maker money
Sniperthis page's HFT rival. After news, takes every quote left at a stale price
Limit orderan order that waits in the queue at its price; adds liquidity
Market orderan order that sweeps the best queues immediately; takes liquidity
Price-time priorityat each price, first come first served
Queue positionhow many shares are ahead of yours at your price
Spreadbest ask minus best bid; the maker's gross income per round trip
Adverse selectionthe loss from being filled by someone who knew where the price was going
Markoutthe mid price some time after your fill, compared to your fill price
Maker rebate / taker feewhat the exchange pays for adding liquidity and charges for removing it; in the US the taker fee is capped at $0.003 per share (a cut to $0.001 is scheduled for November 2027) and rebates sit just under it
Latencythe time from an event in the world to your order landing at the exchange
Inventorythe position a maker accumulates by accident (makers try to get to 0)
Latency arbitragebeing first to the quotes that a price move has made stale
Co-locationrenting rack space inside the exchange's data center

References

Models the simulation is built on:

History and figures:

Open-source references used for the screens: