# What is Market Making

## Introduction

Market making is a trading strategy where a trader provides liquidity to the market by placing both buy (bid) and sell (ask) orders for a financial asset. **At its core, market making is all about managing inventory risk**—the risk of accumulating too much of one asset over another. For developers looking to implement market-making algorithms, understanding and managing this risk is crucial. **If inventory risk didn't exist, market making would be purely profitable**, as traders would consistently earn the spread between buy and sell prices without exposure to market movements.

This article aims to simplify the concept of market making and highlight the importance of inventory risk management, providing developers with the foundational knowledge to build effective market-making strategies.

***

## What is Market Making

In market making, a trader or algorithm simultaneously places buy and sell orders at different prices around the current market price. The goal is to profit from the **bid-ask spread**—the difference between the prices at which you buy and sell.

#### Example

* **Bid Order**: Buy 1 BTC at $30,000.
* **Ask Order**: Sell 1 BTC at $30,100.
* **Spread**: $100.

If both orders execute, you earn the spread of $100.

***

## The Challenge: Inventory Risk

**Inventory risk** arises when your buy and sell orders don't execute equally. This imbalance leads to accumulating more of one asset than the other, exposing you to market price movements.

#### Definition

* **Inventory Risk**: The risk of financial loss due to holding an unbalanced position in assets, typically resulting from uneven execution of buy and sell orders.

#### Why It Matters

* **Price Fluctuations**: Holding an excess of an asset exposes you to adverse price movements.
* **Capital Allocation**: Accumulating too much of one asset can tie up capital, reducing liquidity.
* **Risk of Loss**: If the market moves against your accumulated position, potential profits from the spread can be wiped out.

## Why Market Making Would be Purely Profitable Without Inventory Risk

In an ideal scenario where every buy order is matched with a sell order instantly:

* **No Accumulation**: You don't accumulate any asset; your inventory remains balanced.
* **Guaranteed Spread Profit**: You consistently earn the bid-ask spread without exposure to market risks.
* **Zero Market Risk**: Price movements don't affect you since you're not holding any net position.

However, in real markets, orders are filled asymmetrically due to market volatility and order flow, introducing inventory risk.

### Strategies for Managing Inventory Risk

To build an effective market-making algorithm, developers need to implement strategies that mitigate inventory risk.

#### 1. Dynamic Pricing

Adjust your bid and ask prices based on your current inventory levels.

* **If Long on Asset** (holding more of the asset):
  * Decrease bid price to discourage more buying.
  * Increase ask price to encourage selling.
* **If Short on Asset** (holding less of the asset):
  * Increase bid price to encourage buying.
  * Decrease ask price to discourage selling.

#### 2. Inventory Limits

Set maximum thresholds for how much of an asset you are willing to hold.

* **Upper Limit**: Maximum asset quantity you can hold.
* **Lower Limit**: Minimum asset quantity you can hold (can be negative if short selling is allowed).

#### 3. Time-Weighted Averages

Use time-weighted averages to adjust orders based on how long they've been pending.

* **Long Pending Orders**: Modify or cancel orders that haven't been filled to reduce risk of accumulation.

#### 4. Hedging

Use other financial instruments to offset potential losses due to inventory risk.

* **Futures Contracts**: Lock in prices to mitigate risk from price movements.
* **Options**: Acquire the right to buy or sell at predetermined prices.

## Avellaneda-Stolkov Model for Market Making

One effective way to manage inventory risk in market making is by using the **Avellaneda-Stoikov model**, a mathematical framework that helps determine optimal bid and ask prices while accounting for inventory risk and market volatility.

#### Overview of the Avellaneda-Stoikov Model

Developed by Marco Avellaneda and Sasha Stoikov in 2008 ([link for the paper](https://math.nyu.edu/~avellane/HighFrequencyTrading.pdf)), this model provides a strategy for market makers to maximize their expected profit while controlling for inventory risk over a given time horizon.

#### Key Concepts

* **Mid-Price** $$( S_t )$$: The average of the best bid and ask prices in the market at time tt.
* **Inventory Position** $$( q_t )$$: The net amount of the asset you hold at time tt.
* **Risk Aversion** $$( \gamma )$$: A parameter representing how much you wish to avoid inventory risk. A higher γγ means you are more risk-averse.
* **Volatility** $$( \sigma )$$: The expected volatility of the asset's price.
* **Time Horizon** $$( T )$$: The remaining time over which you are optimizing your strategy.

#### Calculating Optimal Bid and Ask Prices

The model adjusts your bid and ask prices based on your current inventory and market conditions.

**1. Compute the Reservation Price** $$( r_t )$$

The reservation price is your personal estimate of the asset's fair price, adjusted for inventory risk.

$$r_t = S_t - q_t \gamma \sigma^2 (T - t)$$

* If you have a positive inventory $$( q_t  > 0)$$ , the reservation price decreases to encourage selling.
* If you have a negative inventory $$( q_t < 0 )$$, the reservation price increases to encourage buying.

**2. Determine the Optimal Spread** $$( k )$$

The optimal half-spread around the reservation price balances the trade-off between profit and the probability of order execution.

$$k = \frac{\gamma \sigma^2 (T - t)}{2} + \frac{1}{\gamma} \ln\left(1 + \gamma k_0\right)$$

* **Market Depth Parameter** $$( k_0 )$$: Represents how sensitive the order execution probability is to price changes. It needs to be estimated based on market conditions.

**3. Set Optimal Bid and Ask Prices**

*   **Optimal Bid Price (pbpb​)**:

    $$p_b = r_t - k$$
*   **Optimal Ask Price (papa​)**:

    $$p_a = r_t + k$$

#### Implementing the Model in Your Algorithm

Here's how you can incorporate the Avellaneda-Stoikov model into your market-making bot:

**Step 1: Initialize Parameters**

* **Risk Aversion** $$( \gamma )$$: Choose based on how much inventory risk you are willing to take.
* **Volatility** $$( \sigma )$$: Estimate using historical price data.
* **Market Depth** $$( k_0 )$$: Estimate based on how the market responds to price changes.
* **Time Horizon** $$( T )$$: Set the period over which you are optimizing (e.g., one trading day).

**Step 2: Monitor Market Data**

* Continuously update the mid-price $$( S_t )$$ from market data.
* Keep track of your current inventory $$( q_t )$$.

**Step 3: Calculate Reservation Price** $$( r_t )$$

* Use the formula provided to adjust the mid-price based on your inventory.

**Step 4: Calculate Optimal Spread** $$( k )$$

* Compute the optimal half-spread considering your risk aversion and market parameters.

**Step 5: Set Bid and Ask Prices**

* **Bid Price (pbpb​)**: $$p_b = r_t - k$$
* **Ask Price (papa​)**: $$p_a = r_t + k$$

**Step 6: Place Orders**

* Place limit orders at the calculated bid and ask prices.

**Step 7: Update Parameters and Orders**

* As time progresses and your inventory changes, recalculate rtrt​ and kk, and adjust your orders accordingly.

#### Advantages of the Avellaneda-Stoikov Model

* **Dynamic Adjustment**: Prices adjust in real-time based on inventory and market conditions.
* **Risk Management**: Explicitly accounts for inventory risk through the risk aversion parameter.
* **Profit Optimization**: Aims to maximize expected profit over the time horizon.

#### Simplified Example

Suppose:

* $$S_t$$ ​ =$100
* $$q_t = 10$$ units (you are long)
* $$γ=0.1$$
* $$\sigma= 0.02$$ (2% daily volatility)
* $$T−t=1$$ hour remaining (out of an 8-hour trading day)
* $$k_0=1$$

1.  **Calculate Reservation Price**:

    $$r_t = 100 - 10 \times 0.1 \times (0.02)^2 \times 1 = 99.996$$
2.  **Calculate Optimal Spread**:

    $$k = \frac{0.1 \times (0.02)^2 \times 1}{2} + \frac{1}{0.1} \ln(1 + 0.1 \times 1) \approx 0.0104$$
3. **Set Bid and Ask Prices**:
   * $$p_b = 99.996 - 0.0104 = 99.9856$$
   * $$p_a = 99.996 + 0.0104 = 100.0064$$

You would place a bid at $$ $99.9856 $$ and an ask at $$ $100.0064 $$.

#### Considerations for Developers

* **Parameter Estimation**: Accurate estimation of σσ and $$k0$$​ is crucial.
* **Computational Efficiency**: Ensure your algorithm can handle real-time calculations.
* **Risk Aversion Tuning**: Adjust $$γ$$ to find a balance between profitability and acceptable risk.

#### Tips for Implementation

* **Start Simple**: Begin with conservative parameters and gradually adjust as you become more comfortable with the model's behavior.
* **Backtesting**: Test your implementation extensively using historical data to evaluate performance and adjust parameters.
* **Monitoring**: Implement real-time monitoring to adjust for sudden market changes.

> **Note:** _The Avellaneda-Stoikov model was originally designed for traditional stock markets, which have specific trading hours and close at the end of each trading day. In these markets, the time horizon_ $$T$$ _represents the finite period until the market closes, after which trading halts until the next session._

***

## Key Takeaways for Developers

* **Inventory Risk Management Is Essential**: The Avellaneda-Stoikov model provides a systematic way to manage this risk.
* **Dynamic Strategies Outperform Static Ones**: Adjusting orders based on real-time data leads to better risk control.
* **Understand the Model's Assumptions**: Be aware of the model's limitations and the market conditions under which it performs best.
* **Testing Is Crucial**: Backtest your implementation thoroughly before deploying it in live markets.

***

## Conclusion

Market making can be a profitable strategy if inventory risk is effectively managed. The Avellaneda-Stoikov model offers a mathematically grounded approach to dynamically adjust your trading strategy based on inventory levels and market volatility. For developers, integrating this model into your algorithm can help balance the consistent capture of bid-ask spreads with the minimization of exposure to market volatility. **By understanding that inventory risk arises from accumulating one asset over another and using models like Avellaneda-Stoikov to manage this risk, market making becomes a viable and profitable endeavor**.
