Logo van Market Microstructure

Market Microstructure

OrganisatiePopulair
HKUDS
market-microstructure

Marktmicrostructuur: analyse van bied-laatspreads, maatstaven voor toxiciteit van orderstromen (VPIN / Kyle lambda), liquiditeitsmaatstaven (Amihud / Roll), modellen voor prijseffect, analyse van het limietorderboek en de werking van call auctions / bloktransacties op de Chinese A-share-markt.

Add to TypingMind

Overzicht

UitgeverHKUDS
RepositoryVibe-Trading
Skillnaammarket-microstructure
Sterren
33.6K
Forks
5.5K
Meegeleverde bestanden
Alleen instructies
LicentieMIT
Links
  • Instructies in Markdown

    Het model laadt het bestand SKILL.md alleen als dat nodig is. Dat kost dus alleen tokens als een verzoek daadwerkelijk bij de skill past.

  • Werkt met elk LLM

    AI-skills bestaan uit instructies in gewone Markdown, niet uit aanbiederspecifieke code. Daardoor werken ze met GPT, Claude, Gemini, Grok of een lokaal model.

  • Compleet zonder extra bestanden

    Alles wat het model nodig heeft, staat in de instructies — geen extra bestanden om te synchroniseren.

  • Open source

    Gepubliceerd door HKUDS op GitHub. Bekijk de bronbestanden voordat je de skill installeert.

Installatie

Installeer de AI-skill Market Microstructure in TypingMind om deze met elk LLM te gebruiken, of voeg de skill toe aan een andere agent die SKILL.md kan lezen.

1

Installeren in TypingMind

TypingMind installeert een skill rechtstreeks vanuit de GitHub-map. De app leest SKILL.md, bundelt de bijbehorende bestanden en slaat het resultaat lokaal op.

  1. Open de app en ga naar Plug-ins → Skills.
  2. Kies "Installeren via GitHub".
  3. Plak de onderstaande URL van de skillmap en bevestig.
    https://github.com/HKUDS/Vibe-Trading/tree/main/agent/src/skills/market-microstructure
  4. Schakel de skill in voor elke chat waarin je de skill wilt kunnen gebruiken.
Plug-ins → Skills → Skill toevoegen → Via GitHub-URL. Plak vervolgens de map-URL en druk op Doorgaan.
2

Installeren in een andere agent

Elke agent die het Agent Skills-formaat kan lezen, kan deze skill gebruiken — kopieer de map naar de skillmap van die agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading.git /tmp/Vibe-Trading
mkdir -p .claude/skills
cp -r /tmp/Vibe-Trading/agent/src/skills/market-microstructure .claude/skills/market-microstructure
Start Claude Code na het kopiëren opnieuw op, zodat de nieuwe skill wordt herkend.

Gebruik deze skill in TypingMind

Schakel Market Microstructure in voor een chat naar keuze in TypingMind en het model doet de rest. De naam en beschrijving staan in de systeemprompt. Zodra een verzoek bij de skill past, laadt het model zelf de volledige instructies. Je hoeft de skill nooit handmatig aan te roepen. Pas als het model de skill daadwerkelijk gebruikt, kost dat tokens.

Het model laadt Market Microstructure automatisch zodra een verzoek erbij past.

Werkt met elk AI-model

AI-skills zijn gewone Markdown-instructies in plaats van aanbiederspecifieke code. Daardoor is Market Microstructure niet gebonden aan het model waarvoor de skill is geschreven. Installeer de skill één keer in TypingMind en gebruik deze met GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama of een lokaal model dat je zelf draait — allemaal met je eigen API-sleutels.

  • Alleen geladen wanneer nodig

    De systeemprompt bevat alleen de naam en beschrijving. De instructies worden bij het eerste bijpassende verzoek opgehaald, dus een ongebruikte skill kost niets.

  • Wissel van model tijdens een chat

    Omdat de skill uit instructies bestaat en niet uit code, blijft deze werken als je van model wisselt — het volgende model leest hetzelfde SKILL.md-bestand.

Skillinstructies

Dit is de inhoud van SKILL.md die het model laadt. Lees deze vóór de installatie — een skill bestaat uit instructies die je model zal volgen.

Market Microstructure

Overview

Study the micro-level mechanisms of price formation: who is trading, how they are trading, and how trades affect prices. For quantitative strategies, this matters because it improves transaction-cost estimation, identifies informed trading, and optimizes execution.

Applicable scenarios:

  • Precise estimation of strategy trading costs (instead of simply assuming a flat 0.1% fee)
  • Designing large-order execution strategies (TWAP / VWAP / IS)
  • Detecting order-flow toxicity (avoid time windows dominated by informed traders)
  • Quantifying liquidity risk (flash-crash warning)
  • Capturing China A-share-specific microstructure features (call auction / closing auction / block trades)

Core Concepts

Bid-Ask Spread

Three measurements:

MetricFormulaMeaning
Quoted spreadAsk - BidBest spread shown in the limit order book
Effective spread`2 ×trade price - mid price
Realized spread2 × direction × (trade price - mid price 5min later)True market-maker profit
China A-share example:
  Instrument: 600519.SH Kweichow Moutai
  Best bid: 1680.00  Best ask: 1680.50
  Quoted spread: 0.50 RMB = 0.03%

  Instrument: 000001.SZ Ping An Bank
  Best bid: 11.05  Best ask: 11.06
  Quoted spread: 0.01 RMB = 0.09%

Spread decomposition (Roll):
  Spread = adverse-selection cost + inventory cost + order-processing cost
  In China A-shares: adverse selection accounts for 60-70% (mixture of retail and informed traders)

Spread drivers:
  - Larger market cap -> smaller spread (Moutai 0.03% vs small-cap 0.5%)
  - Higher volatility -> wider spread (market-maker risk premium)
  - Higher volume -> narrower spread (greater competition)
  - Higher information asymmetry -> wider spread (adverse selection)

Order-Flow Toxicity Metrics

VPIN (Volume-Synchronized Probability of Informed Trading):

Principle: replace clock time with volume time to measure the probability of informed trading

Calculation steps:
  1. Bucket trades by fixed volume (Volume Bucket)
     Bucket size V = average daily volume / 50 (about 5-10 minutes per bucket)

  2. Classify buy and sell volume in each bucket (Bulk Volume Classification):
     buy_volume = V × Φ(ΔP / σ)  (standard normal CDF)
     sell_volume = V - buy_volume

  3. Compute order-flow imbalance:
     OI_i = |buy_volume_i - sell_volume_i|

  4. VPIN = Σ(OI_i) / (n × V)  (n=50-bucket rolling window)

Interpretation:
  VPIN < 0.3 -> normal, low informed-trading share
  VPIN 0.3-0.5 -> caution, informed trading rising
  VPIN > 0.5 -> dangerous, high probability that major information is about to be released

China A-share usage:
  A sudden VPIN spike in a stock may foreshadow:
  - insider trading ahead of a major announcement
  - institutional position building / distribution
  Before the 2015 China A-share flash crashes, VPIN stayed above 0.6 for a prolonged period

Kyle's Lambda (price impact coefficient):

Model: ΔP = λ × OrderFlow + ε
  where OrderFlow = buy volume - sell volume

Estimation method:
  1. Compute ΔP and OrderFlow in 5-minute windows
  2. Regress ΔP = α + λ × OrderFlow
  3. λ = price change caused by one unit of order flow

Interpretation:
  Large λ -> poor liquidity, high impact
  Small λ -> good liquidity, large orders can be executed cheaply

Typical China A-share values:
  Large cap (CSI 300): λ ≈ 0.001-0.005
  Mid cap (CSI 500): λ ≈ 0.005-0.02
  Small cap (CSI 1000): λ ≈ 0.02-0.1

Liquidity Measures

MetricFormulaAdvantagesDisadvantages
Amihud illiquidity`R_t/ Volume_t`
Roll implied spread2√(-Cov(R_t, R_{t-1}))Requires only daily dataFails when covariance is positive
LOT zero-return ratiozero-return days / total daysIntuitiveToo coarse
Turnover ratiovolume / free floatSimple and intuitiveDoes not reflect price impact
Traded valueaverage daily notionalAbsolute liquidityDoes not reflect relative impact
Amihud calculation (China A-shares):
  ILLIQ = (1/D) × Σ(|R_d| / VOL_d)  (D=trading days, monthly)

  Normalization: ILLIQ × 10^6 (for readability)

  Screening rules:
    ILLIQ < 0.5 -> high liquidity (large-cap blue chips)
    ILLIQ 0.5-5 -> medium liquidity
    ILLIQ > 5 -> low liquidity (trade cautiously)

  Strategy application:
    - Liquidity factor: low-liquidity stocks tend to earn long-run excess return (liquidity premium)
    - Liquidity monitor: sudden rise in ILLIQ -> warning of liquidity drying up

Analysis Framework

1. Price-Impact Models

Power-law impact:

Naming. This is the concave impact term from the Almgren-Chriss literature, and it is neither linear (the exponent is 0.6, not 1) nor Almgren-Chriss optimal execution — no trading trajectory, no permanent/temporary split and no risk-aversion parameter is computed here or anywhere in this repo. The tested implementation is src.quantlib.impact.sqrt_impact; call it rather than retyping the formula.

Model: impact = η × σ × (Q / V)^0.6
  η: impact coefficient, about 0.5-1.5 for China A-shares
  σ: daily volatility
  Q: traded quantity (shares)
  V: average daily volume (shares)

Example:
  Sell 100,000 shares of Kweichow Moutai
  Average daily volume 5,000,000 shares, daily volatility 1.8%
  impact = 1.0 × 0.018 × (100000/5000000)^0.6
         = 0.018 × 0.0085
         = 0.015% (1.5bp, acceptable)

  Sell 100,000 shares of a small-cap stock
  Average daily volume 500,000 shares, daily volatility 3.0%
  impact = 1.0 × 0.03 × (100000/500000)^0.6
         = 0.03 × 0.076
         = 0.23% (23bp, should be executed in slices)

Execution-splitting methods:
  TWAP: uniform in clock time -> simple but ignores market state
  VWAP: volume-profile execution -> better matches market rhythm
  IS: minimize Implementation Shortfall -> optimal but requires real-time optimization

Nonlinear impact (square-root model):

impact = σ × √(Q / (ADV × T))
  σ: daily volatility
  Q: total trade size
  ADV: average daily traded value
  T: execution days

Applicable to: large trades (Q/ADV > 5%)

2. Limit Order Book Analysis

Depth metrics:
  Level 1 depth: queue size at the best bid and best ask
  Level 5 depth: total queue size across the first 5 levels
  Depth asymmetry: (Bid depth - Ask depth) / (Bid depth + Ask depth)
    > 0 -> stronger bid side, price tends to rise
    < 0 -> stronger ask side, price tends to fall

Resilience:
  The speed at which the book recovers after a large-order impact
  Fast recovery -> good liquidity, temporary impact
  Slow recovery -> poor liquidity, persistent impact

China A-share LOB characteristics:
  - The shallowest depth is in the 15 minutes before the open (highest information asymmetry)
  - Depth improves from 10:00-10:30 (institutions begin participating)
  - Best depth is from 14:00-14:57 (most intraday information has been digested)
  - During the 14:57-15:00 closing auction, depth changes sharply (late-day grabbing / dumping)

Order-book imbalance signal:
  OIR = (Bid_vol - Ask_vol) / (Bid_vol + Ask_vol)
  Rolling 5-minute OIR > 0.3 -> short-term bullish signal (accuracy about 55-60%)
  Note: in China A-shares, large orders are often rapidly added and canceled (icebergs / spoofing), so OIR signals need filtering

3. Flash-Crash Mechanism and Prevention

Flash-crash characteristics:
  1. Price drops more than 5% within minutes
  2. Volume first expands, then collapses (liquidity evaporates)
  3. Bid-ask spread widens sharply (market makers pull quotes)
  4. Followed by a V-shaped rebound (not always fully recovered)

Triggers:
  - Large market order + thin liquidity -> punches through multiple levels instantly
  - Stop-loss chain -> initial selloff triggers more stop orders
  - Algo resonance -> multiple trend-following algos sell simultaneously
  - ETF discount arbitrage -> ETF redemption and constituent selling intensify the drop

Preventive measures:
  1. Use limit orders instead of market orders: specify the maximum acceptable price
  2. Monitor VPIN: if VPIN breaks above 0.5 -> stop trading
  3. Liquidity threshold: exclude instruments with Amihud > 10
  4. Spread monitor: if spread widens suddenly to >5x normal -> pause orders
  5. Time avoidance: do not execute large orders in the first 15 minutes after open or the last 5 minutes before close

China A-share flash-crash cases:
  2015 Jun-Jul: thousands of stocks hit limit-down, with VPIN staying elevated
  2020-07-13: Shanghai Composite plunged and then rebounded in a V-shape
  Pattern: liquidity dries up -> limit-down locking (China-specific) -> next-day panic selling

4. China A-Share-Specific Microstructure

Call-auction strategy:
  9:15-9:20: orders can be entered and canceled, mostly probing quotes (low reference value)
  9:20-9:25: orders can be entered but not canceled, so real intent is revealed
  Signal: after 9:20, buy orders far exceed sell orders -> likely gap-up open

  Execution: place orders at 9:24:50 (last 10 seconds of the call auction)
  Risk: cannot cancel, and the final execution price may deviate from expectation

Closing call auction (14:57-15:00):
  Feature: closing price is decided within 3 minutes, with concentrated institutional rebalancing and index-fund flows
  Signal: closing-auction volume > 10% of the whole day -> institutions are rebalancing

  Strategy application:
  - VWAP algos should finish most of execution before 14:50, leaving a small residual for the close
  - Avoid placing large orders after 14:57 (high price uncertainty)

Block-trade discount signal:
  Discount = (block-trade price - closing price) / closing price
  Discount < -5%: seller is eager to exit -> short-term bearish
  Discount > -2%: traded near market price -> may be turnover rather than reduction

  Buyer identity:
  Well-known institutional seat buys -> positive signal
  Same broker on both sides -> may be wash trading (neutral)

Output Format

Microstructure analysis report:

=== Liquidity Diagnosis ===
Instrument: 000858.SZ Wuliangye
Date: 2026-03-28
Average daily traded value: 2.8 billion RMB  Turnover ratio: 0.85%
Amihud: 0.32 (high liquidity)
Effective spread: 0.05% (2.5bp)
Kyle Lambda: 0.003

=== Order-Flow Analysis ===
VPIN: 0.28 (normal)
Order-book imbalance (OIR): +0.12 (mild bid-side bias)
Net large-order buying: +230 million RMB (institutional buying bias)

=== Trading-Cost Estimate ===
Planned trade size: 500,000 shares (about 40 million RMB)
Estimated impact cost: 0.08% (32k RMB)
Commission: 0.025% (10k RMB)
Stamp duty: 0.05% (20k RMB, sell side)
Total one-way transaction cost: about 0.16%

=== Execution Suggestion ===
Recommended strategy: VWAP
Execution window: 10:00-14:50 (avoid the open and the close)
Number of slices: 5-8 (about 60k-100k shares per slice)
Time sensitivity: low (VPIN is normal, no urgency to execute)

Notes

  1. Data requirement is high: microstructure analysis requires tick-level / Level-2 data, while ordinary daily data only supports rough measures such as Amihud / Roll
  2. China A-share Level-2 data: ten-level depth data from SSE / SZSE requires a paid subscription, costing roughly 50k-200k RMB per year
  3. High-frequency trading restrictions: China A-shares strictly prohibit programmatic quote-cancel manipulation (spoofing), so microstructure signals are for analysis only, not for HFT strategies
  4. VPIN calibration: bucket size has a large impact on results and must be adjusted for instrument liquidity; one parameter does not fit all
  5. Cross-market differences: China A-share T+1 settlement and daily price limits make its microstructure significantly different from textbook US-equity models
  6. Illusion of liquidity: high turnover in some China A-shares comes from speculative matched trading and does not represent true liquidity

Dependencies

bash
pip install pandas numpy scipy

Veelgestelde vragen

Wat doet de AI-skill Market Microstructure?

Marktmicrostructuur: analyse van bied-laatspreads, maatstaven voor toxiciteit van orderstromen (VPIN / Kyle lambda), liquiditeitsmaatstaven (Amihud / Roll), modellen voor prijseffect, analyse van het limietorderboek en de werking van call auctions / bloktransacties op de Chinese A-share-markt.

Waarom Market Microstructure gebruiken in TypingMind?

Omdat je deze skill één keer installeert en met elk model kunt gebruiken. Market Microstructure bestaat uit gewone Markdown in plaats van aanbiederspecifieke code. Dezelfde skill werkt dus met GPT-5, Claude, Gemini, Grok of een lokaal model. Ook als je midden in een chat van model wisselt, blijft de skill werken. TypingMind werkt met je eigen API-sleutels, dus je betaalt aanbieders rechtstreeks in plaats van een abonnement per gebruikersplek af te sluiten. Je skills en chats blijven in je eigen opslag.

Hoe installeer ik Market Microstructure in TypingMind?

Open Plug-ins → Skills → Installeren vanaf GitHub in TypingMind en plak https://github.com/HKUDS/Vibe-Trading/tree/main/agent/src/skills/market-microstructure. TypingMind leest het bestand SKILL.md en installeert het als een skill die je per chat kunt inschakelen.

Welke AI-modellen kunnen Market Microstructure gebruiken?

Elk model dat je in TypingMind koppelt. AI-skills bestaan uit gewone Markdown-instructies in plaats van aanbiederspecifieke code. GPT, Claude, Gemini, Grok en lokale modellen kunnen deze skill dus allemaal laden wanneer een verzoek erbij past.

Hoeveel AI-modellen kan ik met Market Microstructure gebruiken?

Zoveel als je wilt. Je kunt Market Microstructure gebruiken met elk model dat skills ondersteunt, zoals GPT, Claude, Gemini, Grok, DeepSeek, Mistral of Llama. Allemaal in TypingMind met je eigen API-sleutels.

Is de AI-skill Market Microstructure gratis?

Ja. Deze skill is door HKUDS op GitHub gepubliceerd onder de licentie MIT. Je betaalt alleen je eigen AI-aanbieder voor de tokens die je gebruikt.

Wat zijn AI-skills?

Een AI-skill is een herbruikbare bundel instructies die een AI-model leert hoe het één specifieke taak moet uitvoeren. De skill volgt het open Agent Skills-formaat: het bestand SKILL.md bevat de naam en beschrijving van de skill. Daarnaast kan de skill scripts, sjablonen of referentiebestanden bevatten die het model nodig heeft. Het model leest de instructies alleen als je verzoek bij de skill past. Een geïnstalleerde skill kost dus niets zolang deze niet wordt gebruikt.

Waarin verschillen AI-skills van plug-ins of MCP-servers?

Een plug-in of MCP-server geeft een model nieuwe tools om aan te roepen: code die ergens wordt uitgevoerd en een resultaat teruggeeft. Een AI-skill geeft het model juist kennis en een werkwijze: hoe het een taak moet aanpakken, welke stappen het moet volgen en hoe goede uitvoer eruitziet. Skills bestaan uit gewone Markdown en hebben dus geen server, API-sleutel of runtime nodig. Ze werken met elk model.

Bekijk alles

Maak nu je eigen AI-werkruimte

Schrijf je in voor onze nieuwsbrief en blijf op de hoogte van nieuwe functies en toekomstige weggeefacties 👇