backtrader
Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers,…
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 -y skills add agiprolabs/claude-trading-skills --skill market-microstructure-traditional --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
/market-microstructure-traditionalContext preview
The summary Claude sees to decide when to auto-load this skill.
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
name: market-microstructure-traditional description: 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
Market microstructure studies how orders become trades and how trades become prices. Understanding these mechanics is essential for execution optimization, market making, and detecting informed flow. This skill covers limit order book (LOB) theory as applied to crypto markets on centralized exchanges, and compares LOB mechanics to the AMM-based structure of DEXes.
| 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 |
---
The bid-ask spread is not a single thing. It decomposes into three components (Roll, 1984; Glosten & Harris, 1988):
1. **Adverse selection** — compensation for trading against informed traders 2. **Inventory holding** — compensation for carrying risk 3. **Order processing** — fixed costs of providing liquidity (fees, infrastructure)
# 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)
The **effective spread** matters most for execution quality. The difference between effective and realized spread measures adverse selection — what the market maker loses to informed flow.
---
A sequential trade model where the market maker sets bid and ask prices to break even against a mix of informed and uninformed traders.
Key insight: the spread is wider when:
Kyle models a single informed trader, noise traders, and a market maker. The market maker sets price as a linear function of net order flow:
price_change = lambda * net_order_flow
**Lambda (λ)** measures permanent price impact per unit of signed volume. Higher lambda = less liquid market. Lambda is estimated by regressing price changes on signed volume:
import 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])See `references/price_formation.md` for full model derivations and the PIN model for measuring informed trading probability.
---
When executing a large order:
Caused by consuming standing liquidity.
equilibrium price. Does not revert.
total_impact = permanent_impact + temporary_impact permanent = gamma * (shares / ADV) temporary = eta * (shares / time_horizon) ^ alpha
Typical alpha values: 0.5-0.7 (square root impact is a robust empirical finding).
Empirically, price impact scales as the square root of order size relative to daily volume:
def 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.5---
The ratio of bid-side to ask-side depth near the top of the book predicts short-term price direction:
def 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) / totalImbalance at levels 1-5 is a strong short-term predictor (Cont et al., 2014). Deeper levels add predictive power but decay quickly.
---
Simplest model: trades arrive at a constant rate λ. Inter-arrival times are exponentially distributed. Useful as a bas
A comprehensive collection of 68 ready-to-use trading, DeFi, and quantitative finance Agent Skills. Works with Claude Code, Cursor, Codex, Gemini CLI, and 30+ other tools.
Repo: agiprolabs/claude-trading-skills
Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers,…
Solana token market data via Birdeye — prices, OHLCV, trades, token metadata, security…
Broad crypto market data from CoinGecko covering 13,000+ tokens. Global market stats,…
Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability…
Wallet evaluation, monitoring, and copy-trade strategy design for Solana DEX trading
Cross-asset correlation analysis including rolling correlation, hierarchical clustering, tail…