Loading...
Loading...
Traditional market microstructure concepts applied to crypto — order book dynamics, market making theory, price formation models, execution quality measurement, and CEX vs DEX structural differences
npx skill4agent add agiprolabs/claude-trading-skills market-microstructure-traditional| Concept | What It Tells You |
|---|---|
| Bid-ask spread | Cost of immediacy — how much you pay to trade now vs later |
| Price impact | How your order moves the market price |
| Order book imbalance | Short-term directional predictor from queue sizes |
| Adverse selection | Risk of trading against informed counterparties |
| Inventory risk | Market maker exposure from accumulated positions |
| Execution quality | How well your fills compare to a benchmark |
# Quoted spread: what you see on the order book
quoted_spread = best_ask - best_bid
quoted_spread_bps = (best_ask - best_bid) / midprice * 10_000
# Effective spread: what you actually pay (accounts for price improvement)
effective_half_spread = abs(trade_price - midprice_at_trade)
effective_spread_bps = effective_half_spread / midprice_at_trade * 10_000
# Realized spread: market maker's actual profit (after price moves)
# Measured at trade_price vs midprice N seconds later
realized_spread = trade_sign * (trade_price - midprice_after_delay)price_change = lambda * net_order_flowimport numpy as np
from numpy.linalg import lstsq
def estimate_kyle_lambda(
price_changes: np.ndarray,
signed_volumes: np.ndarray,
) -> float:
"""Estimate Kyle's lambda from trade data.
Args:
price_changes: Midprice changes between trades.
signed_volumes: Trade volume * trade_sign (+1 buy, -1 sell).
Returns:
Estimated lambda (price impact per unit volume).
"""
X = signed_volumes.reshape(-1, 1)
beta, _, _, _ = lstsq(X, price_changes, rcond=None)
return float(beta[0])references/price_formation.mdtotal_impact = permanent_impact + temporary_impact
permanent = gamma * (shares / ADV)
temporary = eta * (shares / time_horizon) ^ alphadef square_root_impact(
order_size: float,
daily_volume: float,
volatility: float,
impact_coefficient: float = 0.1,
) -> float:
"""Estimate price impact using the square root model.
Args:
order_size: Number of units to trade.
daily_volume: Average daily volume.
volatility: Daily return volatility (decimal).
impact_coefficient: Empirical constant (typically 0.05-0.20).
Returns:
Expected price impact as a fraction.
"""
return impact_coefficient * volatility * (order_size / daily_volume) ** 0.5def order_book_imbalance(
bid_qty: float,
ask_qty: float,
) -> float:
"""Compute order book imbalance.
Returns:
Imbalance in [-1, 1]. Positive = more bids (bullish).
"""
total = bid_qty + ask_qty
if total == 0:
return 0.0
return (bid_qty - ask_qty) / totalintensity(t) = mu + sum(alpha * exp(-beta * (t - t_i)))qreservation_price = midprice - q * gamma * sigma^2 * T
optimal_spread = gamma * sigma^2 * T + (2/gamma) * ln(1 + gamma/k)qgammasigmaTkdef vwap(prices: list[float], volumes: list[float]) -> float:
"""Compute VWAP from trade prices and volumes."""
pv_sum = sum(p * v for p, v in zip(prices, volumes))
v_sum = sum(volumes)
return pv_sum / v_sum if v_sum > 0 else 0.0
# Execution quality vs VWAP
slippage_vs_vwap = (avg_fill_price - vwap_benchmark) / vwap_benchmark * 10_000implementation_shortfall = (execution_price - decision_price) * quantityreferences/execution_quality.md| Dimension | CEX (LOB) | DEX (AMM) |
|---|---|---|
| Price discovery | Limit orders express willingness to trade | Algorithmic curve (x·y=k) |
| Spread | Set by competing market makers | Determined by pool depth and fee tier |
| Depth | Visible order book | Implicit from TVL and curve shape |
| Adverse selection | MMs reprice on information | LPs suffer impermanent loss |
| Execution | Price-time priority | First-come via block inclusion |
| Latency | Microseconds | Block time (400ms Solana, 12s Ethereum) |
| MEV | Front-running is harder (colocated MMs) | Sandwich attacks are endemic |
| Fees | Maker/taker (often maker rebate) | Fixed tier (e.g., 5, 30, 100 bps) |
references/cex_vs_dex.md| Tier | Maker Fee | Taker Fee | Net Spread Required |
|---|---|---|---|
| VIP 0 | 0.10% | 0.10% | 20 bps to break even |
| VIP 5 | 0.02% | 0.05% | 7 bps to break even |
| VIP 9 | -0.005% | 0.03% | 2.5 bps + rebate income |
def maker_pnl_per_trade(
spread_captured_bps: float,
maker_fee_bps: float,
adverse_selection_bps: float,
) -> float:
"""Compute market maker P&L per round trip.
Args:
spread_captured_bps: Half-spread captured on each side.
maker_fee_bps: Maker fee (negative = rebate).
adverse_selection_bps: Expected loss to informed flow.
Returns:
Net P&L in basis points per round trip.
"""
gross = 2 * spread_captured_bps # earn half-spread on each leg
fees = 2 * maker_fee_bps # pay/receive fee on each leg
return gross - fees - adverse_selection_bpsreferences/price_formation.mdreferences/execution_quality.mdreferences/cex_vs_dex.mdscripts/spread_analysis.pyscripts/market_maker_sim.pyuv pip install numpy pandas scipy matplotlib