How Market Making Works: Explanation with Python Pseudocode
Market making is a trading strategy where a participant (the market maker) provides liquidity to a financial market by simultaneously offering to buy (bid) and sell (ask) an asset at slightly different prices. The goal is to profit from the bid-ask spread while managing inventory risk and adapting to market conditions.
Below, I’ll explain the key concepts of market making and illustrate them with Python pseudocode. The pseudocode simulates a basic market-making strategy, focusing on inventory management, spread setting, and trade execution.
Key Concepts of Market Making
-
Bid-Ask Spread:
- The market maker quotes a bid price (price at which they’ll buy) and an ask price (price at which they’ll sell).
- The difference between these prices (spread) is the market maker’s potential profit per trade.
- Example: Bid = 99.90,Ask=100.10 → Spread = $0.20.
-
Liquidity Provision:
- Market makers ensure there’s always a buyer or seller available, reducing price volatility and improving market efficiency.
-
Inventory Management:
- Market makers hold an inventory of the asset (e.g., stocks, crypto, forex).
- They aim to keep inventory balanced to avoid excessive risk (e.g., holding too much of an asset if its price drops).
-
Risk Management:
- Market makers face risks like adverse price movements or unbalanced inventory.
- They adjust spreads or quote sizes to mitigate these risks.
-
Profit Mechanism:
- Profit comes from capturing the spread on many trades.
- Example: Buy at 99.90,sellat100.10 → $0.20 profit per round trip.
Python Pseudocode for Market Making
Below is a simplified pseudocode implementation of a market-making strategy. It includes setting quotes, handling trades, managing inventory, and adjusting spreads dynamically.
class MarketData:
"""Simulated market data (e.g., from an exchange)"""
def __init__(self, best_bid, best_ask):
self.best_bid = best_bid # Highest price someone is willing to pay
self.best_ask = best_ask # Lowest price someone is willing to sell at
class Trade:
"""Simulated trade request from a market participant"""
def __init__(self, trade_type, price, quantity):
self.type = trade_type # 'buy' (market maker sells) or 'sell' (market maker buys)
self.price = price
self.quantity = quantity
class MarketMaker:
def __init__(self, initial_asset, initial_cash, base_spread=0.001):
"""Initialize market maker with starting inventory and parameters"""
self.asset_inventory = initial_asset # Units of asset held
self.cash_inventory = initial_cash # Cash available
self.base_spread = base_spread # Initial spread (e.g., 0.1%)
self.bid_spread = base_spread # Spread for bid price
self.ask_spread = base_spread # Spread for ask price
def calculate_mid_price(self, market_data):
"""Calculate the fair market price (midpoint of best bid and ask)"""
return (market_data.best_bid + market_data.best_ask) / 2
def set_quotes(self, current_price):
"""Generate bid and ask quotes based on current market price"""
bid_price = current_price * (1 - self.bid_spread) # Lower price to buy
ask_price = current_price * (1 + self.ask_spread) # Higher price to sell
return {
'bid_price': bid_price,
'bid_size': self.calculate_bid_size(),
'ask_price': ask_price,
'ask_size': self.calculate_ask_size()
}
def calculate_bid_size(self):
"""Determine how much to bid based on cash inventory"""
# Bid size proportional to available cash (simplified)
return min(self.cash_inventory / 100, 100) # Example: Max 100 units
def calculate_ask_size(self):
"""Determine how much to offer based on asset inventory"""
# Ask size proportional to asset inventory (simplified)
return min(self.asset_inventory, 100) # Example: Max 100 units
def handle_trade(self, trade):
"""Process incoming trades and update inventory"""
if trade.type == 'buy': # Market participant buys → Market maker sells
if trade.quantity <= self.asset_inventory: # Check if enough inventory
self.asset_inventory -= trade.quantity
self.cash_inventory += trade.price * trade.quantity
print(f"Market maker sold {trade.quantity} units at ${trade.price}")
else:
print("Insufficient asset inventory to fulfill buy order")
elif trade.type == 'sell': # Market participant sells → Market maker buys
if trade.price * trade.quantity <= self.cash_inventory: # Check if enough cash
self.asset_inventory += trade.quantity
self.cash_inventory -= trade.price * trade.quantity
print(f"Market maker bought {trade.quantity} units at ${trade.price}")
else:
print("Insufficient cash to fulfill sell order")
# Adjust spreads after trade to manage inventory risk
self.adjust_spread()
def adjust_spread(self):
"""Dynamically adjust spread based on inventory risk"""
# Calculate inventory ratio (proportion of value in assets vs. total)
total_value = self.cash_inventory + self.asset_inventory * current_market_price
if total_value == 0:
return # Avoid division by zero
inventory_ratio = (self.asset_inventory * current_market_price) / total_value
# If inventory is too high (too many assets), widen bid spread to discourage buying
if inventory_ratio > 0.6:
self.bid_spread = self.base_spread * 1.2 # Widen bid spread
self.ask_spread = self.base_spread * 0.8 # Tighten ask spread (encourage selling)
# If inventory is too low (too few assets), widen ask spread to discourage selling
elif inventory_ratio < 0.4:
self.bid_spread = self.base_spread * 0.8 # Tighten bid spread (encourage buying)
self.ask_spread = self.base_spread * 1.2 # Widen ask spread
else:
self.bid_spread = self.base_spread # Reset to base spread
self.ask_spread = self.base_spread
def calculate_profit(self, current_price):
"""Estimate total profit (cash + value of assets)"""
asset_value = self.asset_inventory * current_price
return self.cash_inventory + asset_value
# Simulated market data and trades (for demonstration)
current_market_price = 100.0 # Global variable for simplicity in this example
def fetch_market_data():
"""Simulate fetching market data (best bid/ask)"""
return MarketData(best_bid=99.95, best_ask=100.05)
def simulate_trades():
"""Simulate incoming trades from market participants"""
return [
Trade(trade_type='buy', price=100.10, quantity=50), # Market maker sells
Trade(trade_type='sell', price=99.90, quantity=30) # Market maker buys
]
# Main simulation loop
def market_making_simulation():
# Initialize market maker with starting inventory
market_maker = MarketMaker(initial_asset=1000, initial_cash=100000)
market_active = True
while market_active:
# Step 1: Fetch current market data
current_market_data = fetch_market_data()
current_price = market_maker.calculate_mid_price(current_market_data)
# Step 2: Set and publish quotes
quotes = market_maker.set_quotes(current_price)
print(f"Quotes: Bid ${quotes['bid_price']:.2f} (size {quotes['bid_size']:.2f}), "
f"Ask ${quotes['ask_price']:.2f} (size {quotes['ask_size']:.2f})")
# Step 3: Handle incoming trades
pending_trades = simulate_trades()
for trade in pending_trades:
market_maker.handle_trade(trade)
# Step 4: Display current inventory and profit
profit = market_maker.calculate_profit(current_price)
print(f"Inventory: Assets = {market_maker.asset_inventory}, "
f"Cash = ${market_maker.cash_inventory:.2f}, "
f"Total Value = ${profit:.2f}")
# Simulate one iteration for this example
market_active = False # In a real system, this would loop continuously
# Run the simulation
if __name__ == "__main__":
market_making_simulation()
Explanation of the Pseudocode
1. Core Components
MarketMaker Class: Represents the market maker, managing inventory (assets and cash), setting quotes, handling trades, and adjusting spreads.
MarketData Class: Simulates real-time market data (best bid and ask prices).
Trade Class: Represents incoming trade requests from market participants.
2. Key Functions
calculate_mid_price: Determines the fair market price by averaging the best bid and ask. This is the reference price for setting quotes.
set_quotes: Generates bid and ask prices by applying a spread to the mid-price. It also determines quote sizes based on inventory.
calculate_bid_size / calculate_ask_size: Dynamically adjusts the quantity offered based on available cash (for bids) or assets (for asks).
handle_trade: Processes trades, updating inventory and cash balances. For example:
- If a participant buys, the market maker sells (loses assets, gains cash).
- If a participant sells, the market maker buys (gains assets, loses cash).
adjust_spread: Manages inventory risk by widening or tightening spreads. For example:
- If the market maker holds too many assets, it widens the bid spread (discourages buying) and tightens the ask spread (encourages selling).
calculate_profit: Estimates total value (cash + asset value) to track performance.
3. Simulation Loop
- The
market_making_simulation function simulates a market-making session:
- Fetches market data.
- Sets and publishes quotes.
- Processes incoming trades.
- Updates inventory and displays results.
Real-World Considerations (Not Included in Pseudocode)
-
Latency:
- In high-frequency trading, market makers must minimize latency to stay competitive.
- Real systems use low-latency infrastructure (e.g., co-located servers, FPGA hardware).
-
Advanced Risk Models:
- Real market makers use sophisticated models (e.g., stochastic control, machine learning) to predict price movements and manage risk.
-
Order Book Dynamics:
- Market makers interact with a full order book, not just best bid/ask. They may place limit orders at multiple price levels.
-
Regulatory Compliance:
- Market makers must follow exchange rules (e.g., minimum quote sizes, maximum spreads) and regulations (e.g., SEC, MiFID II).
-
Adverse Selection:
- Market makers risk trading with informed traders (who know the asset’s true value), leading to losses. They mitigate this with dynamic pricing and risk models.
Typical Market Maker Metrics
- Spread Width: How wide the bid-ask spread is (affects profitability vs. competitiveness).
- Inventory Turnover: How quickly inventory is bought and sold.
- Fill Rate: Percentage of quotes that result in trades.
- Profit per Unit Time: Total profit over a trading session.
Example Output (Hypothetical)
Running the simulation might produce output like this:
Quotes: Bid $99.90 (size 100.00), Ask $100.10 (size 100.00)
Market maker sold 50 units at $100.10
Market maker bought 30 units at $99.90
Inventory: Assets = 980, Cash = $100200.00, Total Value = $198200.00
This shows the market maker profiting from the spread while managing inventory.
Conclusion
Market making is a balancing act of providing liquidity, capturing spreads, and managing risk. The pseudocode above illustrates a basic strategy, but real-world implementations are far more complex, involving advanced algorithms, real-time data feeds, and regulatory compliance. If you’d like to dive deeper into any specific aspect (e.g., risk management, high-frequency trading, or order book dynamics), let me know!