Creating a profitable market-making algorithm for crypto perpetual swaps using Geometric Brownian Motion (GBM) in Python is an interesting and practical exercise. Below, I'll walk you through:
- Understanding the problem
- Designing a basic market making strategy
- Modeling asset price with GBM
- Simulating trades
- Implementing profit calculation
- Python code
🔍 1. Understanding Market Making
A market maker provides liquidity by placing limit orders on both sides of the order book — bids (buy) and asks (sell) — slightly away from the mid-price.
- Goal: Capture spread while managing inventory risk.
- Risks:
- Adverse price movement
- Inventory imbalance
- Latency & slippage
We’ll simplify this to focus on capturing bid-ask spread using simulated prices.
📈 2. Using Geometric Brownian Motion (GBM)
GBM is a common model for stock/crypto prices:
dSt=μStdt+σStdWt
Where:
- St: price at time t
- μ: drift (trend)
- σ: volatility
- W: Wiener process (Brownian motion)
In discrete form:
St+1=St⋅
Where ϵ∼N(0,1)
💡 3. Basic Strategy Assumptions
Let’s define a simple version of a market-making bot:
- It posts:
- One buy order at
mid_price - spread
- One sell order at
mid_price + spread
- Each trade has a fixed size (
order_size)
- It keeps track of its inventory (number of contracts held)
- It stops trading if inventory exceeds a threshold (to avoid directional risk)
We will simulate price using GBM and run the strategy over time steps.
🧪 4. Simulation Parameters
| Parameter | Value |
|---|
| Initial price | $10,000 |
| Drift (μ) | 0.0 |
| Volatility (σ) | 0.2 |
| Time horizon | 1 day |
| Timesteps | 1000 |
| Spread | 0.001 (0.1%) |
| Order size | 0.01 BTC |
| Transaction cost | 0.0002 (0.02%) |
🧠 5. Profitability Considerations
Profit comes from:
- Capturing the bid-ask spread
- Managing inventory effectively
Losses can come from:
- Trending markets (inventory bias)
- High volatility
We’ll track total PnL and plot performance.
🐍 6. Python Code
import numpy as np
import matplotlib.pyplot as plt
# --- Parameters ---
initial_price = 10000
mu = 0.0
sigma = 0.2
time_horizon = 1 # in days
dt = time_horizon / 1000
steps = int(time_horizon / dt)
spread = 0.001 # 0.1%
order_size = 0.01 # BTC
transaction_cost = 0.0002 # 0.02%
# --- State variables ---
price_history = [initial_price]
inventory = 0
cash = 0
pnl_history = []
# --- GBM simulation and market making logic ---
np.random.seed(42)
for i in range(steps):
epsilon = np.random.normal()
current_price = price_history[-1]
# GBM step
next_price = current_price * np.exp((mu - 0.5 * sigma**2) * dt + sigma * np.sqrt(dt) * epsilon)
price_history.append(next_price)
# Market making logic
bid = next_price * (1 - spread)
ask = next_price * (1 + spread)
# Simulate whether orders are filled
tick_size = next_price * 0.0001 # small random noise
mid_price = (bid + ask) / 2
market_move = next_price - price_history[-2]
# Random fill logic (simplified)
buy_filled = np.random.rand() < 0.5
sell_filled = np.random.rand() < 0.5
# Buy order filled
if buy_filled and inventory > -1: # limit short position
cash -= bid * order_size
inventory += order_size
# Sell order filled
if sell_filled and inventory < 1: # limit long position
cash += ask * order_size
inventory -= order_size
# Calculate PnL: cash + inventory * mark price
pnl = cash + inventory * next_price
pnl_history.append(pnl)
# --- Results ---
print(f"Final PnL: ${pnl_history[-1]:,.2f}")
print(f"Final inventory: {inventory:.4f}")
# Plotting
plt.figure(figsize=(12, 6))
plt.plot(pnl_history, label='PnL')
plt.title('Market Maker PnL Over Time')
plt.xlabel('Time Step')
plt.ylabel('PnL ($)')
plt.grid(True)
plt.legend()
plt.show()
📊 Sample Output Interpretation
- If the PnL trend is upward and stable → your strategy is profitable in sideways markets.
- If it trends downward during volatile/trending periods → need improvements (e.g., dynamic spread, hedging).
- The final inventory should be close to zero (no directional risk).
🛠️ Enhancements (Optional Next Steps)
- Dynamic Spread Adjustment based on volatility or inventory.
- Inventory Risk Management: Penalize large net positions.
- Hedging with Futures or Spot: Reduce directional exposure.
- Order Book Simulation: Replace random fills with real order matching.
- Backtesting Framework: Use historical data instead of GBM.
✅ Summary
You now have a working market-making simulation using GBM, which:
- Models crypto price movements
- Implements a basic market maker strategy
- Tracks profitability and inventory
- Visualizes PnL over time
This is a starting point — in production, you’d use real data, manage latency, and add robust risk controls.
Would you like me to help implement this with real Binance data or expand into multi-level order books?