Market Making Explained with Python Pseudocode
Market making is the process of providing liquidity to financial markets by continuously quoting both buy (bid) and sell (ask) prices for an asset. Here's a conceptual implementation with Python pseudocode:
import random
from collections import deque
class MarketMaker:
def __init__(self, asset, initial_inventory=1000, initial_capital=100000):
self.asset = asset
self.inventory = initial_inventory # Current position
self.capital = initial_capital # Available funds
self.spread = 0.005 # 0.5% spread
self.max_inventory = 2000 # Risk management limit
self.min_inventory = 0
self.order_book = {
'bids': deque(maxlen=100),
'asks': deque(maxlen=100)
}
self.trade_history = []
def get_mid_price(self):
"""Calculate current mid-market price from order book"""
if not self.order_book['bids'] or not self.order_book['asks']:
return None
best_bid = self.order_book['bids'][0]['price']
best_ask = self.order_book['asks'][0]['price']
return (best_bid + best_ask) / 2
def calculate_quotes(self):
"""Generate bid and ask quotes based on current market"""
mid_price = self.get_mid_price()
if mid_price is None:
return None
# Adjust spread based on inventory position
inventory_ratio = self.inventory / self.max_inventory
adjusted_spread = self.spread * (1 + 0.2 * (1 - inventory_ratio))
bid_price = mid_price * (1 - adjusted_spread/2)
ask_price = mid_price * (1 + adjusted_spread/2)
# Adjust order sizes based on inventory
bid_size = max(1, int(self.capital * 0.01)) # 1% of capital
ask_size = max(1, int(self.inventory * 0.01)) # 1% of inventory
return {
'bid': {'price': bid_price, 'size': bid_size},
'ask': {'price': ask_price, 'size': ask_size}
}
def execute_trade(self, trade_type, price, size):
"""Process a trade execution"""
if trade_type == 'buy':
# Someone bought from our ask
self.capital -= price * size
self.inventory += size
elif trade_type == 'sell':
# Someone sold to our bid
self.capital += price * size
self.inventory -= size
# Update trade history
self.trade_history.append({
'type': trade_type,
'price': price,
'size': size,
'timestamp': time.time()
})
# Rebalance if inventory is too extreme
if self.inventory > self.max_inventory * 0.9 or self.inventory < self.min_inventory * 1.1:
self.rebalance()
def rebalance(self):
"""Adjust inventory to stay within risk limits"""
if self.inventory > self.max_inventory * 0.9:
# Sell some inventory
sell_size = int((self.inventory - self.max_inventory) * 0.5)
self.execute_trade('sell', self.get_mid_price(), sell_size)
elif self.inventory < self.min_inventory * 1.1:
# Buy more inventory
buy_size = int((self.min_inventory - self.inventory) * 0.5)
self.execute_trade('buy', self.get_mid_price(), buy_size)
def update_order_book(self, new_orders):
"""Update our view of the market order book"""
for order in new_orders:
if order['type'] == 'bid':
self.order_book['bids'].appendleft(order)
elif order['type'] == 'ask':
self.order_book['asks'].appendleft(order)
def calculate_pnl(self, current_price):
"""Calculate profit and loss"""
unrealized_pnl = (self.inventory * current_price) + self.capital
realized_pnl = sum(
trade['price'] * trade['size'] * (1 if trade['type'] == 'sell' else -1)
for trade in self.trade_history
)
return unrealized_pnl, realized_pnl
# Example Market Simulation
def run_market_simulation():
mm = MarketMaker('BTC/USD')
# Simulate market data
for i in range(1000):
# Get current market state
current_price = get_market_price() # Would call real API in production
# Update our view of the order book
mm.update_order_book(get_order_book_snapshot())
# Generate new quotes
quotes = mm.calculate_quotes()
if quotes:
# Submit quotes to market
submit_order(quotes['bid'])
submit_order(quotes['ask'])
# Process any trades that occurred
for trade in get_executed_trades():
mm.execute_trade(trade['type'], trade['price'], trade['size'])
# Periodically rebalance
if i % 100 == 0:
mm.rebalance()
# Log performance
if i % 10 == 0:
pnl = mm.calculate_pnl(current_price)
print(f"Step {i}: Inventory={mm.inventory}, PnL={pnl}")
Key Market Making Concepts Illustrated:
-
Order Book Management
- Maintains a view of current bid/ask prices
- Uses deque for efficient order book updates
-
Dynamic Pricing
- Calculates mid-market price from order book
- Adjusts spread based on inventory position
- Wider spreads when inventory is unbalanced
-
Inventory Risk Management
- Sets maximum/minimum inventory limits
- Automatically rebalances when limits are approached
- Adjusts order sizes based on available capital
-
Trade Execution
- Processes both buy and sell executions
- Updates capital and inventory positions
- Maintains trade history for PnL calculation
-
Profit Mechanism
- Earns small spreads on each trade
- Manages inventory risk to prevent large losses
- Continuously provides liquidity to market
Real-World Considerations Not Shown:
-
Latency Optimization
- Ultra-low latency connections to exchanges
- Co-location near exchange servers
-
Advanced Risk Models
- Volatility-based spread adjustment
- Position limits per asset
- Correlation analysis across assets
-
Regulatory Compliance
- Market maker registration requirements
- Best execution obligations
- Reporting requirements
-
Advanced Strategies
- Statistical arbitrage
- Triangular arbitrage
- Market impact models
This pseudocode provides a conceptual foundation that could be adapted for real market making systems, though production implementations would require much more sophisticated risk management and execution logic.