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

engineering

How the Stock Market Actually Works

Co-located servers, microsecond algorithms, and 50 competing venues sit between your buy order and the fill.

By Alex Kugell ·

Citadel Securities made $12.2 billion in net trading revenue in 2025. Jane Street made $39.6 billion, more than JPMorgan Chase's entire trading desk. Virtu Financial, in its 2014 IPO filing, disclosed that it had lost money on exactly one trading day out of 1,278.

These are technology companies that happen to trade financial instruments. Their product is infrastructure: algorithms that quote prices, detect when counterparties know something they don't, and hedge accumulated risk across thousands of correlated assets. The spread between the bid and the ask on your stock trade is their raw material, and the systems that compress it to a penny are among the most precisely engineered real-time systems in production anywhere.

Behind that penny spread is a stack of co-located servers, microsecond-latency networks, statistical models for detecting informed order flow, and a fragmented market of 50 venues that all have to agree on a price. Every layer is a feat of engineering that can also fail catastrophically. Knight Capital demonstrated this when a single missed server deployment cost over $440 million in 45 minutes.

Where your order actually goes

You open your brokerage app and buy 100 shares of Apple (AAPL) at $230. The order almost certainly never reaches the New York Stock Exchange.

Your broker routes the order to a wholesale market maker, most likely Citadel Securities, the largest retail wholesaler in US equities. The broker does this because the wholesaler pays for the privilege, a practice called payment for order flow. The rate is small, roughly $0.0015 per share for equities, but it adds up across billions of shares.

The market maker pays because retail flow is statistically uninformed. You're buying AAPL because you want to own it, not because you have inside information about next quarter's earnings.

For a market maker, uninformed flow is safe flow. They can fill your order, pocket the spread, and not worry that the price is about to move against them.

The wholesaler's algorithm decides whether to fill your order internally or route it to an exchange. If it fills internally, it typically offers a small price improvement over the national best bid and offer, maybe a fraction of a cent better than the best displayed price on any exchange. The SEC's Rule 605 requires disclosure of execution quality, and wholesalers compete on this metric.

Over half of all US equity volume now executes off-exchange. In 2025, 50.6% of consolidated equity volume traded through wholesalers, dark pools, and other alternative venues rather than on the 17 national securities exchanges. The NYSE, for all its brand recognition, is one venue among 50.

Where a retail AAPL order actually goes
You
Tap 'Buy 100 AAPL' in brokerage app
Broker
Routes order to wholesaler for PFOF rebate
Wholesaler
Citadel Securities or Virtu receives order
Fill Internally
Price improvement over NBBO, order complete
~50% of volume
Route to Exchange
Sent to NYSE, NASDAQ, or one of 48 other venues

The algorithm stack

A server 150 kilometers from an exchange faces at minimum a 1-millisecond round trip from the speed of light in fiber, and real-world latencies are much higher. That's too slow. So market makers put their servers physically inside the exchange's data center, usually Mahwah, New Jersey for NYSE or Carteret for NASDAQ.

A co-located round trip takes 5 to 50 microseconds, roughly 100x faster than remote connections.

Inside these data centers, exchanges equalize the cable lengths to every co-located rack. Extra meters of cable add tens of nanoseconds, and when the competition is measured in microseconds, tens of nanoseconds matter. The playing field has to be level at the speed of light.

The algorithm runs four functions simultaneously, each feeding into the others.

Quoting. It posts bid and ask prices on one or more exchanges. These prices change millisecond by millisecond based on the current inventory, recent price movements, order book depth, volatility estimates, and signals arriving from other exchanges. When AAPL's price ticks on NASDAQ, the algorithm adjusts its quote on NYSE in microseconds.

Adverse selection detection. If a hedge fund with better information starts buying aggressively, the market maker who sells to them takes a loss when the price moves up. The algorithm watches for statistical signatures of this informed trading: sudden volume imbalances, unusual concentration in a narrow time window, flow that correlates with news events.

Academic models like VPIN (Volume-Synchronized Probability of Informed Trading) formalize the detection, estimating the probability that current flow is informed based on the balance between buy-initiated and sell-initiated trades in recent volume buckets. When toxicity metrics spike, the algorithm widens the spread to compensate for the higher risk of trading against someone who knows something it doesn't.

Inventory management. Every trade the market maker fills creates a position. If the algorithm fills a large retail buy order for AAPL, it's now short AAPL shares and needs to hedge, maybe by buying S&P 500 futures, shorting a correlated tech stock, or posting a bid on a different exchange.

The goal is to stay as close to flat as possible, earning the spread without taking directional bets on where the market is going.

Cross-exchange arbitrage. With 17 exchanges and 33 alternative trading systems, prices can momentarily diverge. AAPL might be $230.01 on NYSE and $230.02 on BATS for a fraction of a second. The algorithm buys at $230.01 and sells at $230.02, capturing the penny difference minus exchange fees. This arbitrage is also what keeps prices synchronized. The act of buying the cheap exchange and selling the expensive one pushes them back together.

The infrastructure arms race

Co-location solves latency to a single exchange. But the US equity market is 50 venues, and the most profitable trades often involve acting on information from one exchange before anyone else can react on another.

The critical corridor runs between Chicago (where CME Group's futures exchange sits in Aurora, Illinois) and New Jersey (where NYSE and NASDAQ operate). Futures prices in Chicago often lead equity prices in New Jersey by milliseconds. A firm that sees a futures price change in Chicago and adjusts its equity quotes in New Jersey faster than competitors captures the spread.

Fiber optic cable on this route takes about 6.7 milliseconds one way. That's the speed of light through glass. Fiber slows light to roughly two-thirds of its vacuum speed because the signal bounces off the walls of the cable.

Starting around 2011, firms realized microwave relays could beat fiber. Microwave signals travel through air at nearly the speed of light. A network of line-of-sight relay towers between Chicago and New Jersey delivers a signal in about 4 milliseconds, roughly 2.5 milliseconds faster than fiber. The fastest measured network on the CME-to-NYSE path clocks in at about 3.93 milliseconds, within 0.02 milliseconds of the theoretical speed-of-light floor.

Dozens of entities have filed FCC licenses for microwave links on the corridor. Jump Trading placed an antenna across the street from CME's Aurora data center. McKay Brothers, partly owned by IMC and Tower Research Capital, sells access to its network.

The entities that lease tower space and hold FCC licenses often operate under shell company names, obscuring which trading firm is behind which antenna. The infrastructure is worth too much to advertise.

This infrastructure costs millions to build and tens of thousands per month to operate. It exists to shave 2.5 milliseconds off a 700-mile signal path.

Chicago → New Jersey one-way latency
3.93ms
Speed of light
Theoretical floor
0.07ms
4.0ms
Microwave relay
Line-of-sight towers
2.7ms
= millions/yr
6.7ms
Fiber optic
Glass slows light to ~⅔c

The economics of a penny

The bid-ask spread compensates for two things that can go wrong. The person on the other side of your trade might know something you don't. That's adverse selection. And the position you just took might move against you before you can hedge it. That's inventory risk.

A stock like AAPL trades roughly 50 million shares per day. With a one-cent spread, the theoretical maximum gross revenue from making markets in AAPL alone is $500,000 a day if you captured every share on both sides. In practice, competition compresses this. Dozens of firms are quoting the same stock. The economics work because market makers operate across thousands of instruments simultaneously.

Exchanges have to attract firms to post quotes, so they pay for it. A typical rebate for adding liquidity runs $0.0020 to $0.0032 per share, funded by charging $0.0030 per share to firms that hit those quotes. Some exchanges invert this: they charge makers and rebate takers to attract a different type of order flow.

With 17 exchanges, each with its own fee schedule, the algorithm factors exchange fees into every quoting decision.

Citadel Securities generated $12.2 billion in net trading revenue in 2025, up 25% from $9.7 billion in 2024, on about $21 billion in trading capital. Jane Street, a private firm that has never taken outside investment, generated $39.6 billion, more than JPMorgan Chase's entire trading division.

Virtu Financial, the only publicly traded pure-play market maker, reported $2.1 billion in adjusted net trading income in 2025, working out to $8.6 million per trading day.

Virtu's IPO filing contained a chart that became central to the debate about whether these firms provide genuine liquidity or extract rents. Out of 1,278 trading days between January 2009 and February 2014, Virtu lost money on exactly one. A 99.92% win rate, day after day, for over five years.

Virtu framed it as proof that diversification and risk management work. Critics read the same chart as evidence of structural advantages retail investors can never access.

What breaks

The same infrastructure that makes a one-cent spread possible can also lose over $440 million before anyone finishes their morning coffee.

On August 1, 2012, Knight Capital was deploying new software for the launch of NYSE's Retail Liquidity Program. The update went to eight production servers in Knight's Smart Market Access Routing System, deployed manually by technicians copying code to each server in turn.

Seven servers got the new code, but the eighth did not.

That eighth server still contained dead code for a function called Power Peg, which Knight had retired in 2003. In 2005, the firm had refactored the codebase and moved a cumulative-quantity tracking mechanism, but nobody retested whether Power Peg still worked if accidentally triggered.

The new deployment repurposed a flag that had previously activated Power Peg. On the unpatched eighth server, the flag turned on the dead function instead of the new logic.

At 9:30 AM, the eighth server started processing 212 parent orders through the old Power Peg code, sending millions of erroneous child orders into the market across roughly 150 NYSE-listed stocks. Knight's internal monitoring system had generated 97 email alerts with the subject line "Power Peg disabled" before the market even opened.

Staff did not review them.

In 45 minutes, Knight accumulated a massive unintended position and lost over $440 million. The firm's stock dropped over 70% in the days that followed, and GETCO agreed to acquire Knight within five months.

The SEC's enforcement order faulted Knight for having no written procedures requiring a second review of deployments and no retesting after the 2005 code change.

A single unpatched server, a repurposed flag, and a function nobody had tested in seven years cost over $440 million in 45 minutes.

Knight Capital — August 1, 2012
Pre-market
Deploy to 8 servers
Manual copy of RLP code. 7 servers updated, 1 missed.
Pre-market
97 email alerts fire
"Power Peg disabled" — staff do not review them.
9:30 AM
Market opens
8th server activates Power Peg via repurposed flag.
9:30–10:15
212 parent orders
Power Peg sends millions of erroneous child orders across ~150 stocks.
10:15 AM
$440M loss
Massive unintended position accumulated in 45 minutes.
After
Stock drops 70%+
GETCO acquires Knight within five months. SEC fines $12M.

The Flash Crash of May 6, 2010 demonstrated a different failure mode. A large institutional investor initiated an automated sell program for 75,000 E-Mini S&P 500 futures contracts. The algorithm targeted an execution rate based on recent volume, but it had no price limit and no time limit. As prices dropped, trading volume increased, so the algorithm sold faster, which pushed prices down further, which increased volume further.

Market makers and high-frequency firms withdrew as conditions deteriorated. The Dow Jones dropped roughly 1,000 points in minutes, about 9% of its value, and individual stocks traded at absurd prices. Accenture briefly hit $0.01 per share.

The market regained most of the drop within 36 minutes, though it still closed the day about 3% down. The SEC and CFTC investigation that followed led to the Limit Up-Limit Down mechanism, which pauses trading when a stock moves beyond its price band, typically 5% to 10% depending on the security's tier and price.

The DeFi mirror

DeFi solves the same problem, matching buyers and sellers and pricing assets, with a fundamentally different architecture. Traditional market makers run adaptive algorithms that adjust prices millisecond by millisecond based on order flow, volatility, and inventory risk. Uniswap's automated market maker replaces that entire stack with a single equation: the constant product formula (x times y equals k), which sets the price deterministically based on the ratio of two assets in a pool.

The quoting logic, toxicity detection, and inventory management all collapse into one smart contract. But the tradeoff is information. A traditional market maker detects informed flow and widens the spread to protect itself, while an AMM treats every counterparty identically. Everyone gets the same price from the same formula. That makes AMM liquidity providers structurally vulnerable to adverse selection, which shows up as impermanent loss.

DeFi has its own version of the latency arms race, though the mechanism differs. Speed advantages in traditional markets come from microsecond arbitrage across exchanges, while DeFi extraction targets transaction ordering. Validators and searchers see pending trades in the mempool and can reorder, frontrun, or sandwich them.

This extraction, called maximal extractable value, serves the same economic function as latency arbitrage but targets a different surface: block construction rather than wire speed.

Firms like Jump Trading and Wintermute operate in both worlds, applying the same statistical and infrastructure advantages to DeFi that they built for traditional markets. The boundaries between the two are blurring.

DimensionTraditional Market MakerDeFi AMM
PricingAdaptive algorithms, millisecond adjustmentDeterministic formula (x · y = k)
SpeedMicroseconds (co-located servers)Block time (~12 seconds on Ethereum)
Flow segregationInformed vs uninformed (via PFOF)No segregation — everyone gets the same price
Risk managementActive hedging across correlated assetsPassive — impermanent loss is structural
Capital efficiencyHigh (leverage, netting, inventory mgmt)Lower (full collateral locked in pool)
TransparencyOpaque (proprietary algorithms)Fully transparent (open-source contracts)
AccessPermissioned — exchange membership requiredPermissionless — anyone can provide liquidity
Extraction vectorLatency arbitrage (speed advantage)MEV (transaction ordering)

Someone has to stand on both sides of every trade. The firms that do it fastest, across the most venues, with the best read on who's informed and who isn't, get to keep the penny.

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 happens when you tap buy on a stock in your brokerage app?
Your broker almost certainly does not send it to the NYSE. Most retail orders go to wholesale market makers like Citadel Securities or Virtu Financial under payment for order flow arrangements. The wholesaler's algorithm decides the fill price in microseconds, typically offering a small price improvement over the best displayed exchange price. In 2025, over 50% of US equity volume executed off-exchange through these wholesalers and dark pools rather than on a traditional exchange.
How do market makers profit from a one-cent spread?
Volume. A penny spread on a stock that trades 50 million shares a day adds up. Market makers also earn exchange rebates of roughly $0.0020 to $0.0032 per share for posting quotes, receive payment for order flow revenues from retail broker arrangements, and profit from arbitraging momentary price differences across the 17 US exchanges and 33 alternative trading systems. Citadel Securities generated $12.2 billion in net trading revenue in 2025 from these fractions of a penny, compounded across billions of shares.
Why do market making firms co-locate servers inside exchange data centers?
Speed. A co-located server can complete a full order round trip in 5 to 50 microseconds. A server 150 kilometers away faces a minimum 1 millisecond round trip from the speed of light alone, and practical latencies are far higher. Exchanges even equalize the cable lengths inside the data center so no firm gains a nanosecond advantage from rack placement. For cross-market connections, firms like Jump Trading built line-of-sight microwave relay networks between Chicago and New Jersey that deliver signals in about 4 milliseconds versus 6.7 milliseconds over fiber optic cable.
What caused Knight Capital's $440 million loss in 45 minutes?
A deployment error. Knight was updating software on eight production servers for the launch of NYSE's Retail Liquidity Program on August 1, 2012. Seven servers received the update. The eighth did not. That server still contained dead code for an old function called Power Peg, retired in 2003. The new deployment flag accidentally activated Power Peg on the unpatched server, which sent millions of erroneous orders into the market for about 150 NYSE-listed stocks in 45 minutes. Knight lost over $440 million, its stock dropped over 70% in the days that followed, and GETCO agreed to acquire the firm within five months.
How does DeFi market making differ from traditional market making?
Traditional market makers run adaptive algorithms that adjust prices millisecond by millisecond based on order flow, volatility, and inventory risk. DeFi automated market makers like Uniswap use a fixed mathematical formula to set prices deterministically. Traditional systems segregate informed and uninformed order flow through payment for order flow arrangements. AMMs treat every counterparty identically. The tradeoff is transparency and permissionless access in exchange for the ability to adapt pricing in real time.

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

analysisFintech's Center of Gravity ShiftedWealthtech has led fintech by deal count for six straight years, and the 2026 data makes the rotation from payments hard to miss.
analysisPayoneer's Stablecoin Bank Is a Settlement ShortcutA cross-border payments company that already supports stablecoins through Bridge just got a charter to issue its own.
analysis$34.5 Billion in Tokenized Assets and Almost No Secondary MarketDune measured what $34.5 billion in tokenized assets actually does after issuance, and most of it just sits there.
View more ›