Futures Trading System Development
Futures trading is trading contracts on future asset price with leverage. For exchange this is technically most complex product: margin engine, liquidation system, funding rate mechanism, risk management — each component requires performance, precision and resistance to edge cases. Error in margin calculations can lead to socializing losses or exchange insolvency.
Types of Futures Contracts
| Type | Expiry | Settlement | Application |
|---|---|---|---|
| Quarterly futures | Fixed date | Cash or physical | CME, Deribit |
| Perpetual swaps | None | Mark price + funding | Binance, Bybit, dYdX |
| Inverse perpetuals | None | In base asset | Bitmex legacy, Bybit |
| Linear perpetuals | None | In stablecoin | Most CEX |
Perpetual swaps dominate crypto market. No expiration convenient for traders, funding rate mechanism keeps contract price close to spot.
Margin System
Isolated margin: separate margin for each position. Loss limited to allocated collateral. User won't lose entire account due to one position.
Cross margin: all positions use common balance as collateral. Unrealized PnL from profitable positions covers losses of others. More efficient capital use, but risk of total account drain.
CREATE TABLE margin_accounts (
user_id UUID NOT NULL,
currency VARCHAR(10) NOT NULL,
balance NUMERIC(30, 18) NOT NULL DEFAULT 0,
margin_mode VARCHAR(10) NOT NULL DEFAULT 'cross',
PRIMARY KEY (user_id, currency)
);
CREATE TABLE positions (
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
symbol VARCHAR(20) NOT NULL,
side VARCHAR(5) NOT NULL, -- 'long' | 'short'
size NUMERIC(30, 18) NOT NULL,
entry_price NUMERIC(30, 18) NOT NULL,
leverage SMALLINT NOT NULL,
isolated_margin NUMERIC(30, 18),
liquidation_price NUMERIC(30, 18),
unrealized_pnl NUMERIC(30, 18) DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT NOW()
);
Liquidation Price Calculation
For long position in linear perpetual:
Liquidation price = Entry price * (1 - 1/leverage + maintenance_margin_rate)
For short:
Liquidation price = Entry price * (1 + 1/leverage - maintenance_margin_rate)
Where maintenance_margin_rate (MMR) is minimum margin level at which position is forcefully closed. Usually 0.5% for low leverage, up to 5% for 100x leverage.
Liquidation price recalculated on each position change and must be atomic with margin update.
Funding Rate Mechanism
Purpose
Funding rate is periodic payment between long and short holders. If perpetual trades above spot (contango), longs pay shorts. If below (backwardation), shorts pay longs. This anchors perpetual price to spot without expiration.
Binance-Style Formula
Funding Rate = clamp(
(Premium Index) + clamp(Interest Rate - Premium Index, -0.05%, 0.05%),
-0.75%, 0.75%
)
Premium Index = (Max(0, Impact Bid Price - Mark Price) - Max(0, Mark Price - Impact Ask Price)) / Spot Price
Impact Bid/Ask Price — volume-weighted price for $200k nominal order in current order book.
Mark Price — manipulation-protected price for unrealized PnL and liquidations calculation.
Funding rate calculated every 8 hours (standard) or 1 hour (Bybit).
Liquidation Engine
Protection Levels
Level 1: Partial liquidation — close part of position to raise margin. Bybit uses this for large positions.
Level 2: Full liquidation — position fully closed by liquidation engine at mark price.
Level 3: Insurance fund — if liquidation price worse than bankruptcy price, difference covered.
Level 4: Auto-Deleveraging (ADL) — if insurance fund insufficient, profitable opposite-direction positions forcefully closed.
Architecture
Liquidation engine monitors all positions in real time. Performs ~10,000+ open positions checks in <100ms.
Optimizations:
- Positions stored in Redis sorted set, sorted by distance to liquidation price
- On mark price change only delta updated — O(1) vs O(N) full scan
- Liquidation orders go to separate priority queue
Risk Management System
Position Limits
def get_max_leverage(notional_value_usd: float) -> int:
tiers = [
(50_000, 100),
(500_000, 50),
(2_000_000, 20),
(10_000_000, 10),
(50_000_000, 5),
]
for max_notional, max_leverage in tiers:
if notional_value_usd <= max_notional:
return max_leverage
return 2
Tiered leverage — standard practice. Large positions can't use high leverage: too high insurance fund risk during liquidation.
Risk Concentration
| Metric | Threshold | Action |
|---|---|---|
| Net open interest imbalance | >70% one side | Raise funding rate |
| Gross open interest | >$X per symbol | Limit new positions |
| Single user concentration | >20% total OI | Manual review |
| Insurance fund drawdown | >50% per day | Lower max leverage |
Development Timeline
Full perpetual futures system: minimum 6-9 months for team of 4-6 backend engineers. Main risks: errors in liquidation price calculation, race conditions in margin updates, price feed delays during high volatility.







