Back to Simulator

HFT Simulator Documentation

Complete guide from basics to advanced concepts

1. Basics of High-Frequency Trading

What is High-Frequency Trading (HFT)?

High-Frequency Trading is a form of algorithmic trading that uses powerful computers to execute a large number of orders in fractions of a second. HFT firms use complex algorithms to analyze multiple markets and execute orders based on market conditions.

Key Characteristics:

  • Very high speed: trades executed in milliseconds or microseconds
  • High turnover: positions held for very short periods (seconds to minutes)
  • Low latency: minimal delay between signal detection and trade execution
  • High volume: thousands to millions of trades per day
  • Small profit per trade: relies on volume and speed

Market Making Strategy

Market making is a common HFT strategy where traders provide liquidity by simultaneously placing buy and sell orders. The market maker profits from the bid-ask spread - the difference between the price at which they're willing to buy (bid) and sell (ask).

How it works:

  1. Market maker places a bid (buy order) below the current market price
  2. Market maker places an ask (sell order) above the current market price
  3. When both orders are filled, the market maker captures the spread
  4. Profit = (Ask Price - Bid Price) × Size - Fees - Slippage

Risks: Market makers face inventory risk (holding positions) and adverse selection (trading with informed traders).

Key Concepts

Bid-Ask Spread:

Spread = Best Ask Price - Best Bid Price. This is the market maker's primary source of revenue.

Order Book:

A list of buy (bids) and sell (asks) orders showing the depth of the market at different price levels.

Slippage:

The difference between expected execution price and actual execution price, often caused by market movement during order processing.

Market Impact:

The effect of a large trade on the market price. Large orders can move prices against the trader.

2. How the Simulator Works

Simulation Architecture

The simulator runs in discrete time steps, updating prices and executing trades at regular intervals. The main simulation loop performs the following steps:

  1. Price Update: Generate new price using selected model (synthetic) or receive from WebSocket (live)
  2. Order Book Update: Generate synthetic order book or update from live feed
  3. Strategy Execution: Evaluate market making conditions and execute trades if conditions are met
  4. Trade Processing: Apply fees, slippage, market impact, and update cash/position
  5. Statistics Update: Calculate P&L, win rate, and update visualizations

Data Flow

Price Source → Price Model/WebSocket → Strategy Engine → Trade Execution → Cash/Position Update → P&L Calculation → Visualization

The simulator uses React refs to prevent simulation restart when parameters change, allowing real-time parameter adjustment during simulation.

Time Step and Speed

The simulation runs at a configurable speed (5-95ms per step). Each step represents one "tick" in the simulation.

interval = max(8ms, 100ms - speed)

Lower speed values = faster simulation. The minimum interval is 8ms to prevent browser overload.

3. Application Components

Left Sidebar - Controls

  • Data Source: Switch between synthetic data (simulated prices) and live Bitcoin feed from Binance
  • Price Model: Select stochastic model for synthetic price generation (only visible in synthetic mode)
  • Market Making Condition: Choose the logic that determines when to trade
  • Speed Slider: Control simulation speed (5-95ms per tick)
  • Advanced Parameters: Collapsible section with all trading and model parameters

Center Area - Visualizations

  • Price Movement Chart: Area chart showing price over time with gradient fill
  • P&L Over Time: Line chart tracking cumulative profit/loss
  • Position Over Time: Area chart showing inventory changes
  • Order Book Ladder: Real-time display of top 12 bids and asks with depth visualization
  • Market Depth Chart: Area chart showing cumulative bid/ask depth across price levels
  • Trade Volume Chart: Bar chart showing buy/sell volume over time (when trades exist)

Right Sidebar - Trade Log

  • Recent Trades: Scrollable list of last 100 executed trades
  • Trade Details: Shows side (BUY/SELL), price, size, cash flow, and time
  • Color Coding: Green for BUY, Red for SELL; Green for positive cash flow, Red for negative
  • Actions: Clear trades and copy trade data to clipboard

Top Header - Statistics

  • P&L: Real-time mark-to-market profit/loss (cash + position value - initial cash)
  • Trades: Total count of executed trades
  • Position: Current net inventory (positive = long, negative = short)
  • Win Rate: Percentage of trades that improved total equity

4. Price Models (Synthetic Data)

The simulator implements several stochastic differential equations (SDEs) for price dynamics. Each model is discretized using appropriate numerical methods. These models are used when "Synthetic Data" is selected.

1. Geometric Brownian Motion (GBM)

Continuous SDE:

dSt = μSt dt + σSt dWt

Discrete form (exponential Euler):

St+1 = St · exp((μ - 0.5σ²)Δt + σ√Δt · Z)

Where: μ = drift, σ = volatility, Z ~ N(0,1), Δt = time step

Use case: Standard model for stock prices, assumes constant volatility

2. Ornstein-Uhlenbeck (Mean Reversion)

Continuous SDE:

dSt = θ(μ - St)dt + σ dWt

Discrete form (Euler-Maruyama):

St+1 = St + θ(μ - St)Δt + σ√Δt · Z

Where: θ = mean reversion speed, μ = long-term mean, σ = volatility

Use case: Assets that revert to a mean (e.g., interest rates, spreads)

3. Heston Stochastic Volatility

Two-factor model:

dSt = μSt dt + √vt St dW1,t

dvt = κ(θ - vt)dt + σv√vt dW2,t

Discrete form:

vt+1 = vt + κ(θ - vt)Δt + σv√vt√Δt · W2

St+1 = St · exp((μ - 0.5vt)Δt + √vt√Δt · W1)

Where: κ = vol mean reversion, θ = long-run variance, σv = vol of vol, Corr(W1, W2) = ρ

Use case: Modeling volatility clustering and smile effects

4. GARCH-like (Variance Persistence)

Variance update (GARCH(1,1)):

ht = ω + αr²t-1 + βht-1

Price evolution:

St+1 = St · exp((μ - 0.5ht)Δt + √ht√Δt · Z)

Where: rt-1 = log return, ω = base variance, α = ARCH term, β = GARCH term

Use case: Modeling volatility clustering observed in financial markets

5. Jump Diffusion

Combines continuous diffusion with jumps:

St+1 = St · (1 + J) · exp((μ - 0.5σ²)Δt + σ√Δt · Z)

Where: J = jump component (with probability λ), J ~ N(μj, σ²j) when jump occurs

Use case: Modeling sudden price movements (news events, flash crashes)

6. Elastic Volatility

Volatility scales with recent returns:

σt = σ0 · (1 + η · |rt-1|)

St+1 = St · exp((μ - 0.5σ²t)Δt + σt√Δt · Z)

Where: η = elasticity parameter, rt-1 = recent return

Use case: Modeling volatility that responds to recent price movements

5. Market Making Conditions

Market making conditions determine when and which side to trade. Each condition uses different market signals to trigger trades.

1. Random

Trades randomly with probability based on trading frequency. This is the simplest condition and serves as a baseline.

P(trade) = tradingFrequency

side = random(BUY, SELL) with bias toward reducing large positions

Use case: Testing basic execution mechanics, understanding fee impact

Parameters: tradingFrequency (0-1, probability of trading each tick)

2. Inventory-Based

Trades to maintain target inventory level. This is a key risk management technique in real market making - traders need to avoid accumulating too much inventory in one direction.

deviation = position - inventoryTarget

if |deviation| > max(rebalanceThreshold · maxPosition, 10):

side = SELL if deviation > 0, BUY if deviation < 0

Parameters: inventoryTarget (desired position), rebalanceThreshold (sensitivity %), maxPosition (limit)
Use case: Managing inventory risk, maintaining neutral position

How it works: When position deviates from target by more than threshold, trades in opposite direction to rebalance.

3. Spread-Based

Trades when the bid-ask spread is wide enough to be profitable after fees. In live mode, uses actual spread from order book.

effectiveSpread = (liveSpread OR spread · spreadMultiplier · price)

if effectiveSpread > minSpread: trade

Parameters: spread (base spread %), spreadMultiplier (adjustment factor), minSpread (minimum to trade)
Use case: Only trading when spread is profitable, optimizing for wider spreads

How it works: Compares current spread (real or synthetic) against minimum threshold. Only trades when spread is wide enough.

4. Price Change (Mean Reversion)

Trades against price movements, assuming prices will revert to mean. This is a contrarian strategy that profits from price reversals.

ΔP = |Pt - Pt-1|

ΔP% = ΔP / Pt-1

if (ΔP > threshold OR ΔP% > threshold%):

side = SELL if Pt > Pt-1 (sell high), BUY if Pt < Pt-1 (buy low)

Parameters: priceChangeThreshold (minimum price movement to trigger)
Use case: Mean-reversion strategies, profiting from temporary price dislocations

How it works: Detects price movements and trades in opposite direction, betting on reversion.

5. Volatility-Based

Trades when recent volatility exceeds threshold. High volatility often means more trading opportunities and wider spreads.

volt = (1/n) · Σ|ri| for i in [t-n, t]

where ri = (Pi - Pi-1) / Pi-1

if volt > volatilityThreshold: trade

Parameters: volatilityThreshold (minimum volatility %), uses last 5 price points
Use case: Trading during volatile periods, capturing wider spreads in volatile markets

How it works: Calculates recent volatility from price returns. Trades when volatility exceeds threshold.

6. Live Data Integration

Binance WebSocket Integration

When "Live Crypto Feed" is selected, the simulator connects to Binance WebSocket streams for real-time Bitcoin (BTC/USDT) data.

Two WebSocket connections:

  • Price Ticker Stream: wss://stream.binance.com:9443/ws/btcusdt@ticker
    Provides last price updates in real-time
  • Order Book Depth Stream: wss://stream.binance.com:9443/ws/btcusdt@depth20@100ms
    Provides top 20 bid/ask levels, updates every 100ms

Execution in Live Mode:

  • BUY orders execute at best ask price (market buy)
  • SELL orders execute at best bid price (market sell)
  • Slippage and market impact are still applied
  • Order book visualization shows real Binance depth data

Connection Status

The WebSocket status indicator shows:

  • Connected (Green): Successfully receiving live data
  • Connecting (Yellow): Establishing connection
  • Disconnected (Red): No connection (start simulation to connect)
  • Error (Red): Connection failed (check internet connection)

7. P&L and Trade Accounting

Understanding how profits, losses, and statistics are calculated is crucial for interpreting simulation results.

Mark-to-Market P&L

P&L is calculated using mark-to-market accounting, which values your current position at the current market price.

P&L = cash + (position × currentPrice) - initialCash

Components:

  • cash: Current cash balance (starts at $10,000)
  • position: Net inventory (positive = long, negative = short)
  • currentPrice: Latest market price
  • initialCash: Starting capital ($10,000)

Note: This is unrealized P&L. Realized P&L would only count closed positions.

Trade Execution Flow

  1. Determine Execution Price:

    Live: execPrice = bestAsk (BUY) or bestBid (SELL)
    Synthetic: execPrice = midPrice ± spreadAdjustment

  2. Apply Slippage:

    slippage = min(maxSlippage, slippagePct × price × random[-1, 1])

  3. Apply Market Impact:

    impact = marketImpact × size × direction

  4. Final Price:

    finalPrice = execPrice + slippage + impact

Fees and Costs

Each trade incurs multiple cost components:

totalFee = commissionPerTrade + (commissionPct × |price × size|) + transactionCost

  • commissionPerTrade: Fixed fee per trade (e.g., $0.05)
  • commissionPct: Percentage of trade value (e.g., 0.05% = 0.0005)
  • transactionCost: Additional fixed cost per trade

Cash Flow Calculation

When a trade executes:

BUY Trade:

cashFlow = -(price × size + fees)

position += size

SELL Trade:

cashFlow = +(price × size - fees)

position -= size

Win Rate Calculation

Win rate measures how many trades improved your total equity (cash + position value).

For each trade (after the first):

  1. Calculate equity before trade: cash + position × price
  2. Execute trade and update cash/position
  3. Calculate equity after trade: newCash + newPosition × price
  4. If equityAfter > equityBefore: count as win

winRate = (wins / (totalTrades - 1)) × 100%

Note: First trade is excluded as there's no "before" state to compare.

8. Market Microstructure

Market microstructure refers to the mechanics of how trades are executed, including price rounding, order sizing, and execution frictions.

Tick Size

The minimum price increment allowed. All prices are rounded to the nearest tick.

roundedPrice = round(price / tickSize) × tickSize

Example: If tickSize = 0.01, price $100.123 becomes $100.12

Lot Size

The minimum trade size increment. All order sizes are rounded down to the nearest lot multiple.

roundedSize = floor(size / lotSize) × lotSize

Example: If lotSize = 10, order size 23 becomes 20

Slippage

The difference between expected and actual execution price. Can be positive (favorable) or negative (unfavorable).

slippage = min(maxSlippage, slippagePct × price × random[-1, 1])

slippagePct: Base slippage percentage (e.g., 0.1% = 0.001)
maxSlippage: Maximum slippage cap to prevent extreme values

Market Impact

Large orders move prices. Market impact models this effect - larger orders have more impact.

impact = marketImpact × size × direction

direction: +1 for BUY (pushes price up), -1 for SELL (pushes price down)
marketImpact: Impact per unit of size (e.g., 0.001 = $0.001 per unit)

Latency

Simulates network/system delays. With latency > 0, some ticks are randomly skipped.

if random() < latency: skip this tick

latency: Probability of skipping a tick (0 = no latency, 1 = always skip)

9. Advanced Topics

Position Limits and Risk Management

The simulator enforces position limits to prevent unlimited accumulation:

if |position| >= maxPosition: block new trades

Inventory Management: The inventory-based condition helps maintain target inventory levels, reducing directional risk. This is critical in real market making to avoid large losses from adverse price movements.

Real vs Synthetic Data

Synthetic Data: Uses mathematical models to generate prices. Useful for:

  • Testing strategies in controlled environments
  • Understanding model behavior
  • Backtesting without historical data

Live Data: Uses real Bitcoin prices from Binance. Useful for:

  • Testing with real market conditions
  • Observing actual order book dynamics
  • Understanding real spread behavior

Parameter Sensitivity

Understanding how parameters affect trading behavior:

  • Trading Frequency: Higher values = more trades, but may increase costs
  • Spread Multiplier: Higher values = wider effective spread, fewer but more profitable trades
  • Max Position: Higher values = more inventory risk, but more trading capacity
  • Slippage: Higher values = more realistic but less profitable execution
  • Market Impact: Higher values = large orders move prices more (realistic for illiquid markets)

Limitations and Simplifications

This simulator makes several simplifications compared to real HFT systems:

  • No order queue: Trades execute immediately (no order book matching simulation)
  • Simplified market impact: Linear impact model (real markets are more complex)
  • No partial fills: Orders execute fully or not at all
  • Single asset: Only trades one instrument (real HFT often trades multiple)
  • No latency modeling: Basic latency simulation (real systems have complex latency distributions)
  • Simplified fees: Fixed fee structure (real exchanges have maker/taker fees, rebates, etc.)

Despite simplifications, the simulator captures key aspects of market making: spread capture, inventory management, and the impact of fees and slippage on profitability.

10. Usage Guide

Getting Started

  1. Select data source (Synthetic or Live)
  2. Choose market making condition
  3. Adjust parameters in Advanced Parameters section
  4. Click "Start" to begin simulation
  5. Observe trades, P&L, and visualizations

Interpreting Results

  • Positive P&L: Strategy is profitable (after fees and slippage)
  • High Win Rate: Most trades improve equity (good for market making)
  • Position near zero: Good inventory management
  • Many trades: High activity (check if profitable after fees)
  • Negative P&L: Fees/slippage exceed spread capture (adjust parameters)

Tips for Effective Simulation

  • Start with Random condition to understand basic mechanics
  • Use Inventory-Based for realistic risk management
  • In live mode, observe how real spreads affect profitability
  • Adjust trading frequency to balance activity vs. costs
  • Monitor position to avoid exceeding limits
  • Compare synthetic vs. live results to understand model limitations