Skip to content

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TouchMark

An Explainable, Event-Driven Market Making Simulator for L2 Microstructure, Queue-Aware Execution, Inventory Risk & Post-Fill Markout Analysis

Python FastAPI Tests License

TouchMark is an event-driven quantitative market-making simulator designed to study the interaction between optimal quoting, limit-order-book microstructure, queue position, inventory risk, execution probability, and adverse selection.

Rather than treating a market maker as a black-box strategy that simply produces PnL, TouchMark exposes the mechanisms responsible for every trading outcome.

Every quote, queue transition, fill, inventory change, and post-fill price movement can be traced back to an explicit model or market event.

The central research question is:

When a market maker earns the spread, how much of that spread is actually retained after accounting for queue position, adverse selection, inventory risk, transaction costs, and subsequent mid-price movement?


Screenshot 2026-08-27 at 7 48 54 PM

Why TouchMark?

A simplistic market-making backtest often looks like:

Market Data
     ↓
Generate Bid / Ask
     ↓
Assume Fill
     ↓
Calculate PnL

This can produce attractive results while ignoring the mechanics that determine whether a passive order would actually execute.

TouchMark instead models the execution process explicitly:

              ┌─────────────────────┐
              │   L2 Order Book      │
              │ + Trade Tape         │
              └──────────┬──────────┘
                         │
                         ▼
              ┌─────────────────────┐
              │ Event-Driven Engine │
              └──────────┬──────────┘
                         │
            ┌────────────┼────────────┐
            ▼            ▼            ▼
       Market State   Trade Flow   Queue State
            │            │            │
            └────────────┼────────────┘
                         ▼
              ┌─────────────────────┐
              │  Quoting Model      │
              │ AS / CJ / GLFT /    │
              │ Constant Skew       │
              └──────────┬──────────┘
                         │
                         ▼
              ┌─────────────────────┐
              │ Passive Orders      │
              │ + Queue Position    │
              └──────────┬──────────┘
                         │
                    Fill / No Fill
                         │
                         ▼
              ┌─────────────────────┐
              │ Inventory + Cash    │
              │ + Risk Constraints  │
              └──────────┬──────────┘
                         │
                         ▼
              ┌─────────────────────┐
              │ Markout Engine      │
              │ Spread vs Drift     │
              └──────────┬──────────┘
                         │
                         ▼
              ┌─────────────────────┐
              │ Research Metrics    │
              │ PnL / Sharpe / DD   │
              │ Markouts / Inventory│
              └─────────────────────┘

The objective is not simply to answer "Did the strategy make money?"

It is to answer:

"Why did it make or lose money?"


Core Research Contributions

TouchMark combines several components that are individually important in electronic market making but are often separated in simplified backtests.

1. Optimal Quoting

Multiple mathematical market-making models determine reservation prices and quote distances:

  • Avellaneda–Stoikov
  • Cartea–Jaimungal
  • Guéant–Lehalle–Fernandez-Tapia / GLFT-style closed-form quoting
  • Constant-spread inventory-skew baseline

This allows the simulator to compare how different assumptions about inventory risk, volatility, and order-arrival intensity translate into actual quotes.

2. Queue-Aware Execution

A quote touching the best bid or ask does not imply an immediate fill.

TouchMark maintains explicit queue state and advances an order's position using observed trade volume.

This introduces an important distinction:

Quoted at Best Bid
        ≠
Immediately Executed

Instead:

Quote
  ↓
Queue Position
  ↓
Observed Aggressive Volume
  ↓
Queue Consumption
  ↓
Potential Fill

This makes execution behavior substantially more realistic than backtests based on "touch = fill" assumptions.

3. Inventory-Aware Risk Management

Market making is fundamentally an inventory management problem.

TouchMark tracks:

  • Position
  • Cash
  • Position limits
  • Inventory trajectory
  • Liquidation value
  • Soft risk bounds
  • Hard risk bounds
  • Automated inventory hedging

The quoting model therefore interacts dynamically with the inventory state rather than operating independently from risk.

4. Adverse Selection Analysis

A passive fill is not necessarily profitable.

If a market maker buys at the bid and the mid-price immediately falls, the spread captured by the trade may be overwhelmed by adverse price movement.

TouchMark explicitly separates:

Realized spread

from

Post-fill mid-price drift

allowing the simulator to measure the economic cost of adverse selection.

5. Explainable PnL

Instead of reporting only:

PnL = +$X

TouchMark decomposes trading performance into interpretable components:

                    Trading Performance
                           │
             ┌─────────────┴─────────────┐
             │                           │
       Spread Capture              Price Drift
             │                           │
     "What I earned"            "What moved against me"
             │                           │
             └─────────────┬─────────────┘
                           ▼
                    Net Markout

This allows individual fills to be investigated rather than treating strategy PnL as an opaque aggregate.


Mathematical Framework

Avellaneda–Stoikov

TouchMark implements the classical inventory-aware market-making framework of Avellaneda and Stoikov.

The reservation price is:

$$ r(s,q,t)

s-q\gamma\sigma^2(T-t) $$

where:

Variable Meaning
$s$ Current mid-price
$q$ Market-maker inventory
$\gamma$ Inventory risk aversion
$\sigma$ Volatility
$T-t$ Remaining trading horizon

The key intuition is that the market maker's fair price changes with inventory.

If inventory is excessively long, the reservation price moves downward, encouraging more aggressive selling and discouraging additional buying.

The model's optimal quote distances are represented as:

$$ \delta

\frac{1}{\gamma} \ln \left(1+\frac{\gamma}{\kappa}\right) $$

with bid and ask quotes constructed around the reservation price.

This creates a direct relationship between:

Inventory
    ↓
Reservation Price
    ↓
Quote Skew
    ↓
Future Fill Probabilities
    ↓
Inventory Evolution

Cartea–Jaimungal

TouchMark also incorporates an inventory-risk formulation inspired by the Cartea–Jaimungal framework.

The model introduces an explicit running inventory penalty:

$$ \phi q^2 $$

with quote adjustments of the form:

$$ \delta_{\text{ask}}(q)

\frac{1}{\gamma} \ln \left(1+\frac{\gamma}{\kappa}\right) + \frac{2q+1}{2} \sqrt{ \frac{\phi\sigma^2}{2\kappa} } $$

and

$$ \delta_{\text{bid}}(q)

\frac{1}{\gamma} \ln \left(1+\frac{\gamma}{\kappa}\right)

\frac{2q-1}{2} \sqrt{ \frac{\phi\sigma^2}{2\kappa} } $$

This allows the simulator to study how explicit inventory penalties modify quoting behavior.


GLFT

TouchMark includes a closed-form quoting model based on the Guéant–Lehalle–Fernandez-Tapia family of market-making solutions.

This provides an additional model against which the inventory-skewed Avellaneda–Stoikov and Cartea–Jaimungal approaches can be compared.

The purpose is not to declare one model universally superior.

Instead, the simulator creates a controlled environment in which researchers can investigate:

How do different assumptions about risk, volatility, inventory, and order-arrival dynamics affect execution and realized profitability?


Constant-Skew Baseline

A quantitative model should have a baseline.

TouchMark therefore includes a deliberately simple fixed-spread inventory-skew strategy.

This provides a useful control:

Sophisticated model
        vs
Simple baseline

Without a baseline, improvements from a complex model are difficult to interpret.


Queue Position & Execution Model

One of the central design principles of TouchMark is:

Being at the touch does not guarantee execution.

For a passive order, the simulator tracks its position in the relevant FIFO queue.

A simplified execution sequence is:

Initial Queue
──────────────────────────────
Existing Orders
Existing Orders
Your Order
──────────────────────────────

Aggressive Trade Arrives
          ↓
Queue Volume Consumed
          ↓
Your Queue Position Advances
          ↓
Sufficient Volume Reaches Your Order
          ↓
Fill

The engine processes:

  • L2 book state
  • Trade events
  • Quote placement
  • Queue depth
  • Queue consumption
  • Order fills
  • Inventory changes

This creates a more realistic link between market activity and execution probability.


Event-Driven Architecture

TouchMark is designed around an event-driven simulation loop.

Conceptually:

Market Event
     │
     ▼
Update Market State
     │
     ▼
Update Queue State
     │
     ▼
Generate / Refresh Quotes
     │
     ▼
Evaluate Executions
     │
     ▼
Update Inventory
     │
     ▼
Evaluate Risk
     │
     ▼
Hedge if Required
     │
     ▼
Record Ledger Event
     │
     ▼
Continue

This architecture makes the simulator suitable for studying path-dependent phenomena where the order of events matters.


Quoter Contract

The quoter layer acts as the interface between mathematical models and execution.

It handles:

  • Model selection
  • Bid/ask generation
  • Tick-size rounding
  • Minimum spread enforcement
  • Quote refresh logic
  • Price-drift triggers
  • Inventory-change triggers
  • Time-based refresh
  • Adverse-flow filtering

This separation allows mathematical models to remain independent from execution mechanics.


Adverse Selection Filter

TouchMark includes a flow-toxicity filter designed to pull quotes when market conditions become unusually dangerous.

The filter can respond to signals such as:

  • Short-term volatility
  • Order-flow imbalance
  • Rapid market movement
  • Potentially toxic aggressive flow

The conceptual logic is:

Normal Flow
    ↓
Provide Liquidity

Toxic / Unstable Flow
    ↓
Reduce Exposure
    ↓
Pull / Refresh Quotes

This introduces a practical market-making question:

When is providing liquidity no longer worth the adverse-selection risk?


Inventory & Hedging Engine

Inventory is treated as a first-class state variable.

The inventory engine tracks:

$$ \text{Inventory} $$

$$ \text{Cash} $$

$$ \text{Mark-to-Market Value} $$

and

$$ \text{Liquidation Value} $$

The hedge engine operates around configurable soft and hard inventory boundaries.

Conceptually:

              Inventory
                  │
        ┌─────────┼─────────┐
        │         │         │
       Long     Neutral    Short
        │         │         │
        ▼         │         ▼
   Sell / Hedge   │    Buy / Hedge

This allows the simulator to study the trade-off between:

  • earning passive spread
  • controlling inventory risk
  • paying taker fees to reduce exposure

Trade Ledger

Every execution is recorded in a cost-aware ledger.

A fill contains information such as:

  • Timestamp
  • Side
  • Price
  • Quantity
  • Fee
  • Mid-price at execution
  • Inventory before/after execution
  • Cash impact
  • Markout reference

This makes individual executions auditable.

A researcher can therefore move from:

Strategy PnL

to:

Fill #137
    ↓
Why did it execute?
    ↓
What was the queue position?
    ↓
What was the mid-price?
    ↓
What spread was captured?
    ↓
What happened 1 second later?
    ↓
What happened 5 seconds later?
    ↓
Was the fill actually economically attractive?

Post-Fill Markout Decomposition

This is one of the core research components of TouchMark.

For a fill occurring at time $t$, the simulator calculates the realized spread relative to the prevailing mid-price:

$$ S_{\text{realized}}

\text{side} \times (P_{\text{fill}}-P_{\text{mid},t}) $$

where the side convention is chosen so that favorable passive execution contributes positively.

The subsequent mid-price movement is:

$$ \text{Drift}(h)

\text{side} \times (P_{\text{mid},t+h}-P_{\text{mid},t}) $$

The resulting markout is:

$$ \text{Markout}(h)

S_{\text{realized}}

\text{Drift}(h) $$

This produces an interpretable decomposition:

                 Passive Fill
                      │
          ┌───────────┴───────────┐
          │                       │
     Spread Captured         Mid Drift
          │                       │
          ▼                       ▼
      Immediate                Adverse
       Benefit                 Selection
          │                       │
          └───────────┬───────────┘
                      ▼
                 Net Markout

Why Markout Matters

Suppose the market maker buys at:

Bid = 100.00
Mid  = 100.05

The trade initially appears attractive because the market maker captured approximately half the spread.

But if the mid-price becomes:

99.80

shortly afterward, the economics of the trade are very different.

The simulator therefore evaluates multiple horizons:

1s
5s
10s
30s

This helps distinguish:

  • genuine liquidity provision
  • temporary spread capture
  • adverse selection
  • toxic fills
  • inventory-driven losses

The resulting markout curve is one of the most useful diagnostics for evaluating a market-making strategy.


Synthetic Market Generator

TouchMark is designed to run without requiring proprietary market data.

The built-in generator produces synthetic:

  • L2 order-book snapshots
  • Trade tape events
  • Mid-price evolution
  • Volatility dynamics
  • Order-flow behavior
  • Jump events

The generator incorporates jump-diffusion-style price dynamics and self-exciting trade activity inspired by Hawkes-process behavior.

This makes the simulator:

  • reproducible
  • self-contained
  • easy to demonstrate
  • suitable for unit testing
  • runnable without large market-data files

Custom CSV and Parquet market data can also be supplied.


Research Workflow

TouchMark is designed around a research loop rather than simply a backtest:

                 Hypothesis
                     │
                     ▼
              Choose Model
                     │
                     ▼
             Configure Risk
                     │
                     ▼
             Replay Market
                     │
                     ▼
            Observe Executions
                     │
                     ▼
          Decompose Markouts
                     │
                     ▼
             Analyze Inventory
                     │
                     ▼
             Evaluate PnL
                     │
                     ▼
              Refine Model

This makes it possible to investigate questions such as:

Quoting

  • How does increasing $\gamma$ change quote aggressiveness?
  • How sensitive is the strategy to $\kappa$?
  • How does volatility alter optimal spreads?
  • How does inventory skew affect fill asymmetry?

Execution

  • How much performance disappears when queue position is modeled?
  • How frequently does touching the best price actually result in execution?
  • How does queue depth affect realized fill rates?

Adverse Selection

  • Are profitable fills followed by unfavorable mid-price movements?
  • At which horizons does adverse selection dominate spread capture?
  • Does an adverse-flow filter improve post-fill markouts?

Risk

  • How does inventory evolve under different quoting policies?
  • How frequently are risk limits breached?
  • What is the trade-off between passive spread capture and active hedging?

Interactive Dashboard

TouchMark includes a lightweight FastAPI web dashboard designed for interactive research and model exploration.

Launch the dashboard with:

PYTHONPATH=. ./venv/bin/uvicorn mmsim.web.app:app --host 127.0.0.1 --port 8000 --reload

Then open:

http://localhost:8000

The dashboard provides interactive visualization of:

Market Microstructure

  • Mid-price trajectory
  • Bid/ask quotes
  • Quote placement

Inventory

  • Inventory trajectory
  • Position limits
  • Risk excursions

PnL

  • Cumulative PnL
  • Spread capture
  • Adverse-selection contribution

Markouts

  • 1-second markout
  • 5-second markout
  • 10-second markout
  • 30-second markout

Model Parameters

Interactive controls expose parameters such as:

  • $\gamma$
  • $\kappa$
  • $\phi$
  • $\sigma$
  • Inventory limits
  • Spread controls
  • Risk thresholds

The dashboard is intentionally dependency-light:

FastAPI
   +
Vanilla JavaScript
   +
Chart.js

No heavyweight frontend framework is required.


Project Architecture

Market_maker_sim/
│
├── mmsim/
│   │
│   ├── models/
│   │   ├── base.py
│   │   ├── avellaneda_stoikov.py
│   │   ├── cartea_jaimungal.py
│   │   ├── glft.py
│   │   └── constant_skew.py
│   │
│   ├── sim/
│   │   ├── engine.py
│   │   ├── queue.py
│   │   └── inventory.py
│   │
│   ├── quoter/
│   │   ├── quoter.py
│   │   └── adverse_filter.py
│   │
│   ├── hedge/
│   │   └── hedge.py
│   │
│   ├── ingest/
│   │   ├── generator.py
│   │   └── loader.py
│   │
│   ├── ledger/
│   │   └── ledger.py
│   │
│   ├── markout/
│   │   └── markout.py
│   │
│   ├── cli/
│   │   └── main.py
│   │
│   └── web/
│       ├── app.py
│       └── static/
│           ├── index.html
│           └── app.js
│
├── tests/
│
├── run_sim.py
├── requirements.txt
└── README.md

Installation

Clone the repository:

git clone https://github.com/Gradient-7788/TouchMark.git
cd TouchMark

Create a virtual environment:

python3 -m venv venv
source venv/bin/activate

Install dependencies:

pip install -r requirements.txt

Running a Simulation

The simplest way to run TouchMark is through the provided driver:

python run_sim.py --model avellaneda --steps 500

Alternative models:

python run_sim.py --model cartea --steps 500
python run_sim.py --model glft --steps 500
python run_sim.py --model constant-skew --steps 500

JSON output:

python run_sim.py --model cartea --steps 500 --json

A typical research workflow is therefore:

Generate / Load Data
        ↓
Select Quoting Model
        ↓
Configure Parameters
        ↓
Replay Events
        ↓
Track Queue + Inventory
        ↓
Record Fills
        ↓
Calculate Markouts
        ↓
Analyze Performance

Using Custom Market Data

TouchMark supports CSV and Parquet ingestion.

The loader is designed around standard market-data concepts including:

timestamp
bid_price
ask_price
bid_size
ask_size
trade_price
trade_size
trade_side

This allows synthetic experiments to transition naturally into historical replay research.


Verification

The project includes automated tests covering core quantitative and simulation components.

Run:

python -m unittest discover -s tests

Current verification:

........
Ran 8 tests in 0.026s

OK

The test suite covers areas including:

  • Mathematical quoting models
  • Queue-position logic
  • Inventory accounting
  • Markout calculations
  • Core simulation behavior

Design Philosophy

TouchMark follows four principles.

1. Explainability over Black Boxes

Every important quantity should have an interpretable mathematical or market-microstructure explanation.

The simulator should allow a researcher to answer:

"Why did this happen?"

rather than simply:

"What happened?"


2. Execution Realism over Convenient Assumptions

A passive order is not automatically filled because the market touched its price.

Queue position, trade flow, inventory, and market state influence execution.


3. Decomposition over Aggregate PnL

A strategy's PnL is not sufficient to understand market-making performance.

TouchMark decomposes performance into components such as:

Spread Capture
+/- Mid-Price Drift
- Trading Costs
- Hedging Costs
= Economic Outcome

4. Research Reproducibility

The simulator is designed so experiments can be reproduced from:

Market Data
+
Model
+
Parameters
+
Simulation Configuration

rather than relying on opaque manual interaction.


What This Project Demonstrates

TouchMark is deliberately designed to demonstrate competency across multiple areas of quantitative finance and quantitative engineering.

Quantitative Finance

  • Optimal market making
  • Inventory-risk modeling
  • Stochastic price dynamics
  • Order-arrival intensity
  • Liquidity provision
  • Adverse selection
  • Markout analysis
  • Risk-adjusted performance

Market Microstructure

  • Limit order books
  • Bid/ask dynamics
  • Trade tape
  • FIFO queue mechanics
  • Passive execution
  • Order-flow imbalance
  • Liquidity toxicity

Quantitative Engineering

  • Event-driven simulation
  • Modular model interfaces
  • Deterministic replay
  • Data ingestion
  • Trade ledgers
  • Automated testing
  • CLI tooling
  • Interactive visualization

Software Engineering

  • Separation of concerns
  • Pluggable model architecture
  • Testable components
  • Type-safe interfaces
  • Reproducible experiments
  • Lightweight web architecture

Future Research Extensions

TouchMark is structured to support further research beyond the current simulator.

Potential extensions include:

  • Empirical calibration of $\kappa$ from historical order arrivals
  • Hawkes-process calibration from real trade data
  • More sophisticated queue-reactive models
  • Latency modeling
  • Partial fills
  • Order cancellation dynamics
  • Multi-level order-book simulation
  • Transaction-cost calibration
  • Walk-forward evaluation
  • Parameter sensitivity analysis
  • Monte Carlo experiment framework
  • Statistical significance testing
  • Permutation-based performance tests
  • Cross-asset market making
  • Multi-leg inventory management
  • Rust implementation for high-performance simulation

These extensions would allow the simulator to evolve from a research demonstrator into a more comprehensive market-microstructure research framework.


Key Takeaway

Traditional strategy backtests often reduce market making to:

$$ \text{Quote} \rightarrow \text{Fill} \rightarrow \text{PnL} $$

TouchMark models the considerably richer process:

$$ \boxed{ \text{Market State} \rightarrow \text{Quote} \rightarrow \text{Queue Position} \rightarrow \text{Execution} \rightarrow \text{Inventory} \rightarrow \text{Adverse Selection} \rightarrow \text{Markout} \rightarrow \text{PnL} } $$

The result is an explainable market-making research environment in which profitability can be investigated at the level of individual fills, queue behavior, inventory decisions, and subsequent price dynamics.

The goal is not merely to build a market-making strategy.

It is to build an experimental framework capable of answering why a market maker makes or loses money.


References

The mathematical and conceptual foundations draw upon established market-making and market-microstructure research, including:

  • Avellaneda & Stoikov — High-frequency trading in a limit order book
  • Cartea & Jaimungal — optimal market-making and inventory-risk frameworks
  • Guéant, Lehalle & Fernandez-Tapia — closed-form solutions for optimal market making
  • Queue-position and limit-order-book execution literature
  • Research on adverse selection and post-fill markouts

TouchMark was also developed with inspiration from the architecture and research direction of the open-source quant-mm-simulator ecosystem.


License

MIT License.


Author

Yesh Lohchab

Quantitative Finance • Market Microstructure • Algorithmic Trading • Optimization • Quantitative Research


TouchMark — because touching the market is not the same as making money from it.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages