# Market Microstructure Theory

> A Claude skill from brainbytes-dev/everything-claude-trading.

- **Type:** Skill
- **Install:** `agentstack add skill-brainbytes-dev-everything-claude-trading-market-microstructure-theory`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [brainbytes-dev](https://agentstack.voostack.com/s/brainbytes-dev)
- **Installs:** 0
- **Category:** [Finance & Payments](https://agentstack.voostack.com/c/finance-and-payments)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [brainbytes-dev](https://github.com/brainbytes-dev)
- **Source:** https://github.com/brainbytes-dev/everything-claude-trading/tree/main/skills/execution/market-microstructure-theory

## Install

```sh
agentstack add skill-brainbytes-dev-everything-claude-trading-market-microstructure-theory
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Market Microstructure Theory

> Market microstructure theory — limit order books, price discovery, bid-ask spread economics.

## When to Activate

- User needs to understand how prices form in electronic markets
- Analyzing bid-ask spread components (adverse selection, inventory, order processing)
- Modeling limit order book dynamics and depth
- Understanding informed vs uninformed trading (Kyle, Glosten-Milgrom models)
- Evaluating market quality metrics (spread, depth, resilience, price efficiency)

## Core Concepts

### What Is Microstructure?

Market microstructure studies how the mechanics of trading — order types, market rules, information asymmetry, and participant behavior — affect price formation, liquidity, and transaction costs. It bridges the gap between financial theory (efficient prices) and trading reality (discrete orders, imperfect information, strategic behavior).

### The Limit Order Book (LOB)

The central data structure of modern electronic markets:

```
Ask Side (sell orders)           Price    Bid Side (buy orders)
                                150.10   [500, 200, 1000]     ← best bid
                                150.09   [300, 800]
                                150.08   [2000]
[1500, 300]     ← best ask      150.11
[800, 600, 200]                  150.12
[2500]                           150.13
```

Key LOB metrics:
- **Spread**: best ask - best bid (150.11 - 150.10 = $0.01)
- **Depth at best**: total quantity at best bid/ask
- **Book depth**: total quantity within N ticks of midpoint
- **Book imbalance**: (bid_depth - ask_depth) / (bid_depth + ask_depth)
- **Order arrival rate**: frequency of new limit orders
- **Cancellation rate**: frequency of order cancellations (60-90% of all orders in modern markets)

### Bid-Ask Spread Components

The spread compensates market makers for three costs (Stoll, 1978; Huang and Stoll, 1997):

1. **Adverse Selection** (30-60% of spread): risk of trading with informed counterparties who know the true value. The market maker loses on these trades.

2. **Inventory Risk** (10-30%): cost of holding an unbalanced position. Market makers must adjust quotes to manage inventory.

3. **Order Processing** (10-30%): fixed costs of operating (technology, compliance, exchange fees). This component has shrunk dramatically with electronic trading.

### Price Discovery Models

**Kyle (1985)**: a single informed trader, noise traders, and a competitive market maker.
- Informed trader splits orders to hide information
- Market maker sets price as a linear function of net order flow: P = μ + λ * order_flow
- λ (Kyle's lambda) measures price impact per unit of order flow = market's estimate of information content
- Higher λ = less liquid, more information asymmetry

**Glosten-Milgrom (1985)**: sequential trade model with Bayesian updating.
- Each trade is either informed or uninformed (with known probability)
- Market maker updates beliefs about true value after each trade
- Bid and ask are conditional expectations of true value given a sell/buy
- Spread exists even with competition because of adverse selection

**Glosten (1994)**: limit order book as a discriminatory pricing mechanism.
- Depth at each price level reflects break-even condition for that marginal unit
- Deeper into the book = higher adverse selection per unit (larger trades are more likely informed)

## Methodology

### Step 1: LOB State Representation

```python
import numpy as np
import pandas as pd
from collections import defaultdict

class LimitOrderBook:
    def __init__(self, tick_size=0.01):
        self.tick_size = tick_size
        self.bids = defaultdict(list)  # price -> [order_ids]
        self.asks = defaultdict(list)
        self.orders = {}  # order_id -> {price, size, side, timestamp}

    def add_order(self, order_id, side, price, size, timestamp):
        price = round(price / self.tick_size) * self.tick_size
        self.orders[order_id] = {
            'price': price, 'size': size, 'side': side, 'ts': timestamp
        }
        if side == 'bid':
            self.bids[price].append(order_id)
        else:
            self.asks[price].append(order_id)

    def best_bid(self):
        return max(self.bids.keys()) if self.bids else None

    def best_ask(self):
        return min(self.asks.keys()) if self.asks else None

    def spread(self):
        bb, ba = self.best_bid(), self.best_ask()
        return (ba - bb) if (bb and ba) else None

    def midpoint(self):
        bb, ba = self.best_bid(), self.best_ask()
        return (bb + ba) / 2 if (bb and ba) else None

    def book_imbalance(self, levels=5):
        """
        Bid-ask imbalance at top N levels.
        Positive = more bid depth = buying pressure.
        Strong predictor of short-term price direction.
        """
        bid_prices = sorted(self.bids.keys(), reverse=True)[:levels]
        ask_prices = sorted(self.asks.keys())[:levels]

        bid_depth = sum(
            sum(self.orders[oid]['size'] for oid in self.bids[p])
            for p in bid_prices
        )
        ask_depth = sum(
            sum(self.orders[oid]['size'] for oid in self.asks[p])
            for p in ask_prices
        )

        return (bid_depth - ask_depth) / (bid_depth + ask_depth) if (bid_depth + ask_depth) > 0 else 0

    def depth_at_price(self, price):
        side = self.bids if price  1 means positive autocorrelation (trending)

    return metrics
```

## Examples

### Interpreting Book Imbalance

```python
# Strong positive imbalance (0.6+): much more bid depth than ask depth
# → Price likely to move up in the short term
# → But beware: sophisticated traders "spoof" one side

# Book imbalance as a feature in ML models:
# Cartea, Jaimungal, Penalva (2015) show book imbalance predicts
# next-trade direction with 55-60% accuracy in liquid markets
```

### Kyle's Lambda Across Stocks

```python
# Typical Kyle's lambda values (price impact per $1M of order flow):
# Large-cap (AAPL, MSFT): 0.01-0.05 bps per $1M
# Mid-cap: 0.1-0.5 bps per $1M
# Small-cap: 1-5 bps per $1M
# Micro-cap: 10-50 bps per $1M

# Lambda increases around events (earnings, M&A) as information asymmetry rises
```

## Quality Gate

- [ ] LOB data source quality verified (exchange direct feed vs consolidated, latency)
- [ ] Trade classification method appropriate (Lee-Ready for intraday, tick rule fallback)
- [ ] Spread decomposition uses sufficient data for stable estimates (>1000 trades)
- [ ] Kyle's lambda estimated with appropriate frequency aggregation (too fine = noisy)
- [ ] Permanent vs temporary impact windows calibrated to market speed
- [ ] Book imbalance features tested for spoofing robustness
- [ ] Variance ratio calculated at multiple horizons to characterize price efficiency
- [ ] Market quality metrics compared across venues for the same instrument
- [ ] Off-hours and auction data handled separately from continuous trading
- [ ] Results validated against academic benchmarks for the same asset class

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [brainbytes-dev](https://github.com/brainbytes-dev)
- **Source:** [brainbytes-dev/everything-claude-trading](https://github.com/brainbytes-dev/everything-claude-trading)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-brainbytes-dev-everything-claude-trading-market-microstructure-theory
- Seller: https://agentstack.voostack.com/s/brainbytes-dev
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
