Module contents
Lesson 20 of 30Core 115 min

Market microstructure I: the limit order book and its simulation

Explore the market from within: limit and market orders, cancellations, the order book, price-time priority and the matching engine. Define spread, depth, midpoint and microprice, and build a book simulator with zero-intelligence order flow and a queueing model.

After this lesson you can

  • Describe order types and a continuous double auction with price-time priority.
  • Implement an efficient matching engine with appropriate data structures and message events.
  • Calculate spread, depth, midpoint, imbalance and microprice and examine their predictive value.
  • Simulate a zero-intelligence book and check which stylized facts emerge from mechanics alone.
  • Model best-level queues as birth-death processes and calculate upward price-move probabilities.

Before you start

Price forms in a queue

A screen shows a last price, but the next trade needs a willing counterparty. In a continuous double auction, buyers and sellers submit instructions during the session; the engine matches them when compatible. The limit order book holds outstanding limit-order liquidity. In a quote-driven market, intermediaries announce prices; actual rules may combine mechanisms. Opening and closing can use periodic auctions with a common-price rule different from continuous matching.

A limit buy sets the maximum price and a limit sell the minimum. If it crosses the best opposite price, it executes against available orders and any remaining quantity may rest in the book. A market order prioritizes execution over price and can sweep several levels; if liquidity is insufficient, the remainder’s treatment depends on market rules. IOC executes what it can immediately and cancels the remainder. A cancellation removes outstanding quantity; it does not undo an executed trade. Hidden and iceberg orders may show only part of their liquidity and be subject to specific priority rules.

InteractiveA live book

Synthetic order book. Each press generates a reproducible pseudorandom event. A market order can be partially unfilled.

Bids
99: 8
98: 4
Asks
101: 4
102: 6

No pending order of your own. Filled on entry: 0 units. Filled later in the queue: 0 units.

Type
Side
99
3
Insert an order and advance the flow; observe the quantity ahead of your order.

Price and time

Under price-time priority, an incoming buy first meets the lowest ask and a sell meets the highest bid. At the same price the oldest order executes first. Under this engine’s convention, the trade is recorded at the resting order’s price. Other platforms may use different rules. The book is not crossed after a message has been fully processed.

InteractiveMatching step by step

L id B|S price quantity, M id B|S quantity, C id. If a market order has insufficient counterparties, the remainder is left unfilled.

Step 0 of 5. Waiting for the first message.

Bids
Asks

Fills: none

Edit the messages, advance and observe the queues and executions.

A dictionary by level provides access to the FIFO queue, and another by identifier allows order cancellation. A priority queue maintains the best price; with LL levels, inserting or removing a level costs O(log⁡L)O(\log L), while identifier access is amortized O(1)O(1). Lazy cancellation leaves a marker removed when it reaches the head: its cleanup cost is spread across orders. An ordered tree also supports level traversal and range queries. These bounds exclude the number of partial fills, which must be processed individually. The small widget uses a list to show the process; the lab uses queues and heaps.

What the best level measures

Let bb be the best bid, aa the best ask and qb,qaq_b,q_a their quantities. Spread and depth are s=a−bs=a-b and the quantities available at each level. The midpoint is m=(a+b)/2m=(a+b)/2 and the bid fraction is I=qb/(qb+qa)I=q_b/(q_b+q_a), defined only when both quantities are positive. A common weighted midpoint is

pw=aqb+bqaqb+qa=m+s(I−1/2).p_w=\frac{a q_b+b q_a}{q_b+q_a}=m+s(I-1/2).

The weighting is crossed: if more visible bid quantity exists, pwp_w approaches the ask. It is not automatically a conditional expectation or a guarantee of better prediction. Stoikov’s microprice is constructed as a limit of expected future midpoints conditional on book state, when that limit exists. Its estimation requires transitions between states and price movements; it is not obtained merely by substituting quantities in the previous formula. Stoikov empirically compares estimators on his data. Results depend on asset, sample, horizon and calibration.

InteractiveImbalance and the next move

AAPL LOBSTER level-1 sample from June 21, 2012. States are counted by event and consecutive states share the same future move. Training labels that cross the time split are omitted. The colored line shows the observed frequencies.

0 %25 %50 %75 %100 %0–20 %20–40 %40–60 %60–80 %80–100 %

Frequencies: 40.4 % (n=6507) · 40.7 % (n=10164) · 47.8 % (n=17940) · 51.7 % (n=10048) · 55.3 % (n=14588). The lab fits a five-state approximation to these data.

Displayed sample
Compare frequencies in two time segments of a public sample.

The LOBSTER sample comes from NASDAQ Historical TotalView-ITCH. The figure uses AAPL, level 1, June 21, 2012, with 118,497 book rows. Each row corresponds to the state after the message with the same index. Rows are split chronologically in half and the sign of the first subsequent midpoint change is calculated; training labels crossing the split are excluded. The observation unit is the event and many rows can share the same subsequent change. Thus row count is not the number of independent moves; do not interpret frequencies as confidence intervals. This is one day and level, not a universal study.

Zero-intelligence flow

In a zero-intelligence model, flow arrives randomly without optimizing agents or private information. Limit arrivals, market orders and cancellations change queues; the mechanics can produce spread, depth and price changes. This does not prove real markets lack information or strategic behavior. Smith and coauthors study a version with random flows, cancellations and dimensional scaling.

InteractiveRates and outcomes

Gillespie simulation with 1,800 events, seed 28020, unit orders after initialization, and five possible prices per side. The first 200 events are discarded. The 32 states with a missing side are excluded from spread and depth. Quadratic variation omits jumps across these gaps and divides by all simulated time.

Observed spread: 2.84 ticks
Scale μ / (λ / 10): 3.75 ticks

Profile by level rank, normalized to the first. Simulation / AAPL LOBSTER level 5: 1: 1.00 / 1.00 · 2: 1.38 / 0.96 · 3: 1.29 / 0.98 · 4: 0.80 / 0.99 · 5: 0.14 / 0.99. A missing rank has zero quantity. The AAPL order book counts shares and the model counts units. The ratios compare the shape of the profiles.

With uniform limit order intensity across prices, Smith and colleagues obtain a spread scale proportional to market order flow divided by limit order flow per price. Here the limit rate per side and tick is λ/10, so μ/(λ/10) = 3.75 ticks gives a dimensional reference. Our finite grid, initialization, and rules differ from those of the original model.

8
3
0.20
Mean spread (ticks)2.84
Mean depth at the best level2.00
Sum of squared changes / time2.144
Change arrival, market and cancellation rates in a repeatable simulation.

Times between events are exponential with a total rate equal to the sum of rates. First draw the time, then the event type with probability proportional to its rate. In the widget each outstanding order has its own cancellation clock. A finite grid and a single seed limit comparison with asymptotic scaling laws; repeat the experiment with different seeds, horizons and grids before drawing conclusions.

For a depth comparison, the figure includes averages from the official five-level AAPL sample for the same day: 301,587 states, with mean depth of 164.93, 158.14, 161.52, 163.50 and 162.77 shares averaging both sides at each occupied rank. Mean spread is 0.1565 dollars. Ranks are occupied levels, not necessarily consecutive distances in ticks. The five-level sample has additional updates compared with the level-one sample, so their means weight different events. The simulator profile is normalized by its first level to compare shape, not to claim that a simulated unit is a share or that the model is calibrated.

Queue depletion

Queue dynamics can be modeled as births and deaths: orders arrive at the best price, while others execute or are canceled. In the simplified model, depletion of the ask moves price up and depletion of the bid moves it down. Cont, Stoikov and Talreja calculate conditional probabilities using transforms under explicit flow assumptions. In reality an order can arrive inside the spread, hidden liquidity may appear or price may change without a single queue explaining everything.

For two independent Brownian motions with equal variance, absorbed on hitting zero and with initial sizes b,a>0b,a>0, the probability that the ask hits zero first is 2arctan⁡(b/a)/π2\arctan(b/a)/\pi. This is the harmonic solution in a quadrant, with value one on the ask axis and zero on the bid axis. It is a diffusion approximation, not an exact equality for every unit-step discrete walk. A finite discrete model can be solved with first-step equations, as in the lab.

Execution of a limit order depends on its queue position; it is not enough for price to touch its level. If 400 units are ahead and the constant average removal rate ahead is 70 units per minute, 400/70400/70 minutes is a continuous-flow approximation to reaching the head. Execution of the order itself also requires enough consumption; cancellations behind do not help, and rates may vary.

Lab: engine and events

The engine below maintains a dictionary of live orders, identifier queues per level and two price heaps. Canceling removes the identifier from the dictionary and leaves a marker in the queue, cleared when it reaches the head. Quantities and prices are integers; the engine does not implement hidden-order priority, auctions, modifications or clock synchronization. Executions use the resting order’s price. The log is a simplified representation, not a complete LOBSTER file.

[ ]FIFO engine with levels and heapsBrowser
from collections import deque
import heapq, math, random, time

class Libro:
    def __init__(self):
        self.niv={'B':{},'S':{}}; self.heap={'B':[],'S':[]}
        self.ordenes={}; self.usados=set(); self.ejecuciones=[]; self.mensajes=[]
    def mejor(self,lado):
        h=self.heap[lado]; niveles=self.niv[lado]
        while h:
            p=-h[0] if lado=='B' else h[0]; cola=niveles[p]
            while cola and cola[0] not in self.ordenes: cola.popleft()
            if cola: return p
            heapq.heappop(h); del niveles[p]
        return None
    def cancelar(self,ident):
        if ident not in self.ordenes: raise ValueError('Orden inexistente')
        del self.ordenes[ident]; self.mensajes.append(('C',ident))
    def enviar(self,ident,lado,cantidad,precio=None):
        if ident in self.usados or lado not in ('B','S') or not isinstance(cantidad,int) or cantidad<=0 or (precio is not None and not isinstance(precio,int)):
            raise ValueError('Orden inválida')
        self.usados.add(ident); otro='S' if lado=='B' else 'B'; restante=cantidad; trades=[]
        while restante:
            p=self.mejor(otro)
            if p is None or (precio is not None and (p>precio if lado=='B' else p<precio)): break
            cola=self.niv[otro][p]; resting=cola[0]; orden=self.ordenes[resting]
            q=min(restante,orden[2]); restante-=q; orden[2]-=q
            trades.append((resting,p,q)); self.ejecuciones.append((ident,resting,p,q))
            if orden[2]==0: del self.ordenes[resting]
        if restante and precio is not None:
            if precio not in self.niv[lado]:
                self.niv[lado][precio]=deque(); heapq.heappush(self.heap[lado],-precio if lado=='B' else precio)
            self.ordenes[ident]=[lado,precio,restante]; self.niv[lado][precio].append(ident)
        self.mensajes.append(('M' if precio is None else 'L',ident,lado,precio,cantidad))
        return trades,restante
    def mejor_cantidad(self,lado):
        p=self.mejor(lado)
        if p is None: return None
        return p,sum(self.ordenes[i][2] for i in self.niv[lado][p] if i in self.ordenes)

libro=Libro()
libro.enviar('a','S',3,101); libro.enviar('b','S',4,101); libro.enviar('c','S',2,102)
operaciones,resto=libro.enviar('compra','B',8)
print('Ejecuciones FIFO:',operaciones,'| resto no ejecutado:',resto)
print('Mejor oferta restante:',libro.mejor_cantidad('S'))

A level queue can contain cancellation markers until cleanup reaches them; quantity queries filter for live orders. A market order does not place the remainder. We check that best prices do not cross and that messages and fills are consistent with the quantity processed. Timing is indicative and depends on the device and Pyodide; it is not an exchange latency measurement.

[ ]Simulate events and check invariantsBrowser
rng=random.Random(2820); book=Libro()
for i in range(5):
    book.enviar(f'b{i}','B',5,99-i); book.enviar(f's{i}','S',5,101+i)
reloj=0.; mids=[]; spreads=[]; estados=[]; started=time.perf_counter()
for i in range(2000):
    tasa_l,tasa_m,tasa_c=8.,3.,.15
    total=tasa_l+tasa_m+tasa_c*len(book.ordenes)
    reloj+=rng.expovariate(total); u=rng.random()*total; lado=rng.choice(['B','S'])
    if u<tasa_l:
        p=rng.choice(range(96,101) if lado=='B' else range(100,105))
        book.enviar(f'l{i}',lado,1,p)
    elif u<tasa_l+tasa_m: book.enviar(f'm{i}',lado,1)
    elif book.ordenes: book.cancelar(rng.choice(list(book.ordenes)))
    b=book.mejor_cantidad('B'); a=book.mejor_cantidad('S')
    if b and a:
        assert b[0]<a[0]
        spreads.append(a[0]-b[0]); mids.append((a[0]+b[0])/2)
        estados.append(((a[0]+b[0])/2,b[1]/(b[1]+a[1])))
    else: estados.append(None)
print('Eventos:',len(book.mensajes),'| ejecuciones:',len(book.ejecuciones),'| tiempo simulado:',round(reloj,2))
print('Spread medio condicionado a ambos lados:',sum(spreads)/len(spreads),'| estados válidos:',len(spreads))
print('Tiempo de cálculo orientativo (s):',round(time.perf_counter()-started,3))

The following bins include only events whose next change occurs before one side of the book disappears. The model uses ticks and the historical sample uses dollars, so their numerical spreads are not compared without calibrating tick size and rates. Comparing probabilities shows a conditional property, not complete validation of the model.

[ ]Next move in the simulationBrowser
import numpy as np
cuenta=np.zeros(5,dtype=int); subidas=np.zeros(5,dtype=int)
proximo=None; anterior=None
for e in reversed(estados):
    if e is None: proximo=None; anterior=None; continue
    m,fraccion=e
    if anterior is not None and m!=anterior: proximo=anterior
    if proximo is not None:
        grupo=min(4,int(5*fraccion)); cuenta[grupo]+=1; subidas[grupo]+=int(proximo>m)
    anterior=m
print('Simulación, conteos y frecuencias:',[(int(n),round(int(u)/int(n),3) if n else None) for n,u in zip(cuenta,subidas)])
print('LOBSTER test, conteos y frecuencias:',[(n,round(u/n,3)) for n,u in [(6507,2626),(10164,4137),(17940,8577),(10048,5195),(14588,8072)]])

Lab: probabilities and data

For a discrete-queue example, we cap each size at NN: births at NN are reflected. The first-step equation for each interior state sets its probability of an upward move equal to the mean of its four neighbors, because all four clocks have the same rate. Absorbing boundaries correspond to first depletion; solving the system gives the exact value for the truncated model, not the untruncated diffusion formula.

[ ]First-step equationsBrowser
import numpy as np
def agotamiento(N):
    A=np.zeros((N*N,N*N)); y=np.zeros(N*N)
    idx=lambda b,a:(b-1)*N+(a-1)
    for b in range(1,N+1):
        for a in range(1,N+1):
            i=idx(b,a); A[i,i]=1
            for bb,aa in [(b-1,a),(min(N,b+1),a),(b,a-1),(b,min(N,a+1))]:
                if aa==0: y[i]+=.25
                elif bb==0: pass
                else: A[i,idx(bb,aa)]-=.25
    return np.linalg.solve(A,y).reshape(N,N)
prob=agotamiento(12)
print('Colas b=2, a=1:',prob[1,0], '| aproximación browniana:',2*np.arctan(2)/np.pi)
print('Colas simétricas b=a=3:',prob[2,2])

For execution, the quantity ahead of an order that is not canceled differs from the whole queue: new orders at the same price arrive behind it. In the one-tick case, Cont, Stoikov and Talreja model this quantity as a pure-death chain with rate μ+(i−1)θ\mu+(i-1)\theta for ii remaining original orders, including one’s own, and compare it with first depletion of the ask. Their formula uses first-passage-time transforms; with a larger spread there are also arrivals inside the spread. The following calculation uses the still simpler case θ=0\theta=0, unit service at rate 1 and an ask that has births and deaths at rate 1, reflected at NN. It is not the paper’s general formula.

[ ]Execute before losing the askBrowser
def ejecutar_antes(N,C):
    A=np.zeros((N*C,N*C)); y=np.zeros(N*C)
    idx=lambda c,a:(c-1)*N+(a-1)
    for c in range(1,C+1):
        for a in range(1,N+1):
            i=idx(c,a); A[i,i]=1
            # Un servicio, un nacimiento y una muerte de la oferta son equiprobables.
            if c==1: y[i]+=1/3
            else: A[i,idx(c-1,a)]-=1/3
            A[i,idx(c,min(N,a+1))]-=1/3
            if a>1: A[i,idx(c,a-1)]-=1/3
    return np.linalg.solve(A,y).reshape(C,N)
ej=ejecutar_antes(12,2)
print('Probabilidad de ejecutar con 1 delante y oferta de 1:',ej[1,0])
print('Referencia sin truncar para este caso:',1/np.sqrt(5))

The untruncated benchmark comes from transforms. For the symmetric birth-death ask starting at one unit, the depletion-time transform is f(s)=(s+2−s(s+4))/2f(s)=(s+2-\sqrt{s(s+4)})/2. Execution of two units at rate one has a two-stage Erlang distribution, independent of the ask. Therefore P(Tej<Ta)=1−f(1)+f′(1)=1/5P(T_{ej}<T_a)=1-f(1)+f'(1)=1/\sqrt5. The truncated result approaches that value for this state. Execution occurs when the own queue is absorbed, not when a process with arbitrary births is depleted. Without specifying which cancellations can affect the own order and how liquidity arrives, position and rates alone do not determine the entire distribution.

The figure’s table directly summarizes the public file. The following code reproduces frequencies from the book CSV downloaded and unpacked locally. It is shown without browser execution because the external file is not included in the Pyodide environment. Integer prices are divided by 10,000 to obtain dollars; using integers to detect changes avoids rounding errors.

import numpy as np
x=np.loadtxt('AAPL_2012-06-21_34200000_57600000_orderbook_1.csv',delimiter=',',dtype=np.int64)
mid=x[:,0]+x[:,2]; siguiente=np.full(len(x),-1,dtype=int); j=-1
for i in range(len(x)-2,-1,-1):
    if mid[i+1]!=mid[i]: j=i+1
    siguiente[i]=j
fraccion=x[:,3]/(x[:,1]+x[:,3]); bins=np.minimum((5*fraccion).astype(int),4)
corte=len(x)//2
for inicio,fin in [(0,corte),(corte,len(x))]:
    for grupo in range(5):
        ids=np.arange(inicio,fin)
        ok=(siguiente[ids]>=0)&(bins[ids]==grupo)&(x[ids,1]>0)&(x[ids,3]>0)&(x[ids,0]>x[ids,2])
        if inicio==0: ok &= siguiente[ids]<corte
        ids=ids[ok]; subidas=np.sum(mid[siguiente[ids]]>mid[ids])
        print(grupo,len(ids),int(subidas),subidas/len(ids))
valido=(x[:,1]>0)&(x[:,3]>0)&(x[:,0]>x[:,2])
Qn=np.zeros((5,5),dtype=int); Rn=Qn.copy(); gn=np.zeros(5,dtype=np.int64)
for i in range(corte-1):
    if not (valido[i] and valido[i+1]): continue
    a,b=bins[i],bins[i+1]; cambio=mid[i+1]-mid[i]
    (Rn if cambio else Qn)[a,b]+=1; gn[a]+=cambio
print('Transiciones sin cambio:',Qn,'con cambio:',Rn,'suma de cambios:',gn)
for grupo in range(5):
    ids=np.arange(corte,len(x)); ids=ids[valido[ids]&(siguiente[ids]>=0)&(bins[ids]==grupo)]
    y=(mid[siguiente[ids]]-mid[ids])/20000
    w=(x[ids,0]-x[ids,2])/10000*(fraccion[ids]-.5)
    print(len(ids),y.sum(),(y*y).sum(),((y-w)**2).sum())

# Repetir con el archivo de cinco niveles, que contiene más eventos.
x5=np.loadtxt('AAPL_2012-06-21_34200000_57600000_orderbook_5.csv',delimiter=',',dtype=np.int64)
valido5=(x5[:,1]>0)&(x5[:,3]>0)&(x5[:,0]>x5[:,2]); x5=x5[valido5]
print('Spread medio USD:',np.mean((x5[:,0]-x5[:,2])/10000))
print('Profundidad media por rango:',[np.mean((x5[:,4*j+1]+x5[:,4*j+3])/2) for j in range(5)])

To estimate a Stoikov microprice, discretize state, for example spread and imbalance, and estimate transitions without a move QQ, transitions with a move RR and the associated expected displacement gg. If I−QI-Q is invertible, the expected correction until the next change is (I−Q)−1g(I-Q)^{-1}g and the transition matrix between changes is (I−Q)−1R(I-Q)^{-1}R. Summing corrections for successive changes approximates the expectation at increasing horizons. Convergence requires additional conditions, including absence of cumulative drift; upward-move frequencies alone cannot verify it. Fit only on training data, compare against mm and pwp_w on test data and report errors, costs and uncertainty. The figure does not claim to have calibrated that limit.

The following matrix provides a complete and deliberately simple case. At each event there is an 80% chance of remaining unchanged in the current state; with 20% probability there is a change of ± half a tick, with upward probabilities 0.2, 0.5 and 0.8, and the balanced state is reset. The midpoint starts at zero and spread is one tick. Later movements have zero mean, so the limit exists and can be computed without claiming this structure describes AAPL.

[ ]Microprice in a three-state modelBrowser
Q=.8*np.eye(3); R=np.zeros((3,3)); R[:,1]=.2
prob_sube=np.array([.2,.5,.8]); g=.2*.5*(2*prob_sube-1)
G=np.linalg.solve(np.eye(3)-Q,g); B=np.linalg.solve(np.eye(3)-Q,R)
esperanza=np.zeros(3); potencia=np.eye(3)
for _ in range(5):
    esperanza+=potencia@G; potencia=potencia@B
ponderado=np.array([.1,.5,.9])-.5
print('Corrección tras cinco cambios:',esperanza)
print('Punto medio:',np.zeros(3),'| precio ponderado:',ponderado)
print('El estado equilibrado tiene corrección:',G[1])

Now fit a five-state model to the first half of AAPL, using the same imbalance intervals as the figure. The following matrices count transitions between consecutive rows; gg accumulates midpoint changes in units of 1/20,000 dollars. Dividing each row by its number of transitions gives QQ, RR and gg. The state omits spread, additional depth and time of day, making this a deliberately limited approximation. We subtract stationary mean drift per change so that the correction series has a limit; that is a modeling choice, not a measurement of future drift.

The second half is summarized by interval with observation count, sum of future changes, sum of their squares and sum of squared errors of the weighted estimate. These aggregates allow test mean squared error to be calculated without distributing the full file. The target is the next midpoint change; therefore comparing the long-horizon correction there also measures possible horizon mismatch. States share future changes and are not independent trials. Costs and latency are excluded.

[ ]Fit and evaluate an approximate micropriceBrowser
conteos=np.array([12232,8497,15565,8545,14408])
Qn=np.array([[3680,424,279,56,35],[430,2131,911,140,100],
             [239,1059,3562,890,382],[96,97,879,2220,551],[39,139,352,641,4589]])
Rn=np.array([[4621,980,1291,494,372],[899,1617,1063,516,690],
             [1338,933,4560,915,1687],[514,464,991,1660,1073],[375,654,1677,1013,4929]])
gn=np.array([-316700,-292800,-7900,316600,242400])
Q=Qn/conteos[:,None]; R=Rn/conteos[:,None]; g=gn/conteos/20000
assert np.allclose((Q+R).sum(axis=1),1)
G=np.linalg.solve(np.eye(5)-Q,g); B=np.linalg.solve(np.eye(5)-Q,R)
eig,vec=np.linalg.eig(B.T); pi=np.real(vec[:,np.argmin(abs(eig-1))]); pi=pi/pi.sum()
deriva=pi@G; centrado=G-deriva
micro=np.linalg.solve(np.eye(5)-B+np.outer(np.ones(5),pi),centrado)
test=np.array([[6507,-14.045,3.109775,25.232077250808334],
               [10164,-32.045,4.658825,10.973201388444451],
               [17940,-15.095,8.196775,8.601827970213279],
               [10048,3.655,4.635425,11.92634983831775],
               [14588,15.72,5.93035,51.30616025221008]])
n,y,y2,err_w=test.T
mse_mid=y2.sum()/n.sum()
mse_micro=(y2-2*micro*y+n*micro**2).sum()/n.sum()
mse_ponderado=err_w.sum()/n.sum()
print('Corrección microprecio por intervalo (USD):',micro)
print('MSE siguiente cambio, medio / ponderado / microprecio:',mse_mid,mse_ponderado,mse_micro)
print('Deriva centrada por cambio (USD):',deriva)

In this run, the midpoint mean squared error is approximately 0.000448 squared dollars, the microprice approximation’s is 0.000449 and the weighted estimate’s is 0.001824. The approximate microprice does not improve on the midpoint for this target and sample; superiority observed in another study must not be turned into a general guarantee. These results are for one date, instrument, time split and discretization, weighted by event count. Aggregates and calculation can be reproduced from the original CSVs with the same valid-row filtering; neither a strategy nor the statistical significance of the difference has been evaluated. The last trade price does not automatically replace the midpoint as a benchmark either: it can alternate between sides due to the spread itself.

Exercises

NumericTwo prices
The bid is 99.98 for 300 shares and the ask is 100.00 for 100. What is the cross-weighted price?
QuizMechanics and strategy
How can flow without informed agents generate a spread and price variation?
NumericReaching the head
There are 400 units ahead. 50 per minute are consumed and 20 per minute ahead are canceled. In a continuous-flow approximation, how many minutes until reaching the head?
ProofDepletion in the quadrant
Prove: Two independent Brownian motions with equal variance start at (b,a), with b,a positive. Derive the probability that a hits zero before b.
The proof will appear here as you work.

Step 1 of 3. What equation does the probability satisfy inside the quadrant?

CodeMarket order
Implement barrer(niveles, cantidad). niveles is a list of ask (price, quantity) pairs in ascending order and cantidad is a positive integer. Return (ejecuciones, precio_medio, resto), with executions (price, quantity). If nothing executes, precio_medio is None. Do not modify the input.
def barrer(niveles,cantidad):
  raise NotImplementedError()
Shift+Enter to run

Key takeaways

Key idea
A trade passes through a queue structure: price, priority and available liquidity determine its execution. Flow models are hypotheses to test against data, not substitutes for the observed market.

The midpoint, weighted price and microprice answer different questions. A simulator isolates mechanics, tests invariants and allows experimentation with rates, but own-queue position, hidden liquidity, latency and flow variation matter in an implementation. Useful validation separates calibration from testing and states both the scope of the data and the missing rules.