Margin Trading System Development
Margin trading is trading with borrowed funds. Trader deposits collateral (margin), gets leverage (2×, 5×, 10×), and can trade larger volume. Exchange earns on funding rate / interest. Task: build system that won't allow losses greater than collateral (otherwise exchange bears risk).
Types of Margin Trading
Isolated Margin
Each position has its own collateral. Risk limited to specific position collateral — other positions unaffected during liquidation.
Cross Margin
All user positions use common collateral pool. Profitable positions support losing ones. Liquidation occurs when entire balance goes negative.
Liquidation Price Calculation
For Long position with isolated margin:
func CalculateLiquidationPrice(pos IsolatedPosition, config MarginConfig) Decimal {
maintenanceMarginAmount := pos.EntryPrice.Mul(pos.Quantity).Mul(config.MaintenanceMarginRate)
lossAtLiquidation := pos.InitialMargin.Sub(maintenanceMarginAmount)
priceDropAllowed := lossAtLiquidation.Div(pos.Quantity)
if pos.Side == Long {
return pos.EntryPrice.Sub(priceDropAllowed)
} else {
return pos.EntryPrice.Add(priceDropAllowed)
}
}
Example: Long BTC, entry $42,000, leverage 10x
- Initial Margin: $42,000 / 10 = $4,200
- Maintenance Margin Rate: 0.5%
- Liquidation price: $38,010
Liquidation Engine
Liquidation must happen quickly: during sharp market moves multiple users' positions can hit liquidation price simultaneously.
Levels of protection:
- Level 1: Partial liquidation — close part of position to raise margin
- Level 2: Full liquidation — position fully closed by liquidation engine
- Level 3: Insurance fund — if liquidation price worse than bankruptcy price, difference covered by insurance fund
- Level 4: Auto-Deleveraging (ADL) — if insurance fund insufficient, profitable positions forcefully closed
Insurance Fund
When sharp moves cause liquidation at worse price than liquidation price, remaining loss covered by Insurance Fund — pool formed from liquidation fees.
ADL (Auto-Deleveraging): if Insurance Fund exhausted, forcefully close most profitable positions to cover loss. Harsh measure used as last resort.
Funding Rate for Perpetual Contracts
Perpetual futures don't have expiration. Price pegged to spot through funding rate mechanism:
func (fe *FundingEngine) CalculateRate(pair string) Decimal {
markPrice := fe.getMarkPrice(pair)
indexPrice := fe.getIndexPrice(pair) // spot price from major exchanges
// Premium = (mark - index) / index
premium := markPrice.Sub(indexPrice).Div(indexPrice)
// Funding Rate = Premium + clamp(InterestRate - Premium, -0.05%, 0.05%)
interestRate := Decimal("0.0001") // 0.01% base rate
clampedDiff := Clamp(
interestRate.Sub(premium),
Decimal("-0.0005"),
Decimal("0.0005"),
)
return premium.Add(clampedDiff)
}
Long pays if rate > 0 (mark > index), receives if rate < 0.
Mark Price vs Last Price
Liquidation based on mark price (aggregated price from multiple exchanges), not last trade price. Otherwise possible manipulation: large trader makes small trade at extreme price and triggers liquidations.
func (fe *FundingEngine) GetMarkPrice(pair string) Decimal {
// Median price from Binance, OKX, Bybit
prices := []Decimal{
fe.binanceFeed.GetPrice(pair),
fe.okxFeed.GetPrice(pair),
fe.bybitFeed.GetPrice(pair),
}
sort.Slice(prices, func(i, j int) bool { return prices[i].LessThan(prices[j]) })
return prices[1] // median of 3
}
Development Timeline
| Component | Timeline |
|---|---|
| Isolated margin engine | 4–5 weeks |
| Liquidation engine | 3–4 weeks |
| Cross margin | 3–4 weeks |
| Perpetual funding rate | 2–3 weeks |
| Insurance fund + ADL | 2–3 weeks |
| Mark price oracle | 1–2 weeks |
| UI for margin trading | 4–6 weeks |
Full margin trading system: 4–6 months.







