CEX Spot Margin Trading System: A Complete Product Design from Lending Pools and Interest Rate Models to the Liquidation Engine

ExchangeInfrastructureWhite Label Solution٤ أغسطس ٢٠٢٦

Spot margin is the third core business line of a centralized exchange after spot and perpetual futures, and the key engine for activating "holders" into "traders." Unlike perpetuals, the underlying asset in spot margin is real coins: users borrow real USDT or real BTC from a lending pool, not nominal contracts. The system matches real buy and sell orders, closes positions through real on-chain transfers, and settles PnL through principal and interest repayment. This makes spot margin in product form much closer to the coupling of a "lender-of-coins market" and a "spot matching engine," whereas a contract system is closer to the coupling of a "central counterparty + insurance fund."

But making spot margin robust is far more complex than it looks. A complete spot margin system must, at minimum, answer the following questions:

  • Where does the funding in the lending pool come from? How are the three sources — the platform's own capital, institutional market makers, and ordinary holders — tiered and interest-bearing?
  • Are interest rates fixed or floating? What curve should be used between utilization and rate? Are different coins and different tenors priced separately?
  • Should the account use isolated margin or cross margin? How do the two modes coexist? Can a user run multiple position groups in the same account?
  • How is the risk ratio defined? How are the initial margin ratio, maintenance margin ratio, liquidation line, and bankruptcy line tiered?
  • How are collateral haircuts set? What are the haircuts and concentration limits for BTC, ETH, stablecoins, and altcoins?
  • Is forced liquidation executed via market sell orders, a Dutch auction, or partial position reduction with risk ratio recalculation?
  • After bankruptcy, how is bad debt handled? Absorbed by the platform insurance fund, the liquidity providers, or apportioned across multiple parties?
  • How is interest income distributed among lenders, the platform, and liquidation penalties? What are the priority and deduction rules for auto-repayment?
  • Under different jurisdictions — Malaysia SC, Indonesia BAPPEBTI / OJK, Thailand SEC, Vietnam, Dubai VARA — how are maximum leverage, suitability tests, and qualified investor thresholds implemented?

This article systematically explains, from both a product and engineering perspective, the complete design of a CEX spot margin trading system, including the fundamental differences from derivatives, lending pools and interest rate models, isolated vs cross margin accounts, risk ratio and margin calculations, collateral haircuts and multi-currency collateral, liquidation engines, bankruptcy and bad debt handling, interest distribution, risk monitoring and circuit breakers, engineering architecture, Southeast Asia compliance considerations, and the delivery playbook that SoonTech has refined across multiple white label exchange projects. Whether you are a product manager building an exchange, a head of risk, or a CTO evaluating exchange system solutions, after reading this article you will have a checklist that can be reviewed directly against your requirements document and engineering implementation.

1. How Spot Margin Fundamentally Differs from Derivatives

1.1 The Underlying Asset in Spot Margin Is Real Coins

Perpetual futures are "price contracts." Internally, the system maintains a mark price and a long-short position table; users do not actually hold BTC spot. PnL is calculated as "entry price vs mark price × quantity," and funding rates anchor the price to the spot index, making perpetuals essentially a zero-sum futures game. The exchange is the central counterparty to all trades and must bear counterparty risk, maintain an insurance fund, and passively handle bankruptcy.

Spot margin is different. The underlying is real coins: a user posts USDT as collateral, borrows real BTC from the lending pool, and sells it on the spot market for USDT. This is essentially a "holder going short with leverage." The borrowed coins move through real on-chain transfers. To close, the user must buy the coins back and return them to the lending pool; the lender receives principal plus interest, and the borrower keeps the price difference. The exchange is not a central counterparty but the combination of a lending matcher and a spot venue; the borrower's counterparty is the lending pool and the ultimate lender, and PnL is borne by the borrower.

This difference drives a series of product design implications: spot margin can go long (borrow quote to buy base) or go short (post base to borrow quote and sell); contract systems usually only support long and short, but the underlying is a unified contract ledger. Spot margin requires a separate lending pool ledger and an independent interest rate system.

1.2 Risk Models Differ: Collateral Ratio vs Maintenance Margin

Contract systems use "maintenance margin ratio" to measure risk. For example, BTCUSDT perpetual at 100x leverage has a maintenance margin ratio of 0.5%; if account equity falls below 0.5% of notional, liquidation is triggered. This model assumes the account has "sufficient equity" and that liquidation only needs to top up to the maintenance margin ratio.

Spot margin uses "risk ratio" to measure risk. The risk ratio = total asset value / (borrowed principal + accrued interest). When the risk ratio falls below 1.0, assets are insufficient to repay principal and interest, and intervention is required immediately. When the risk ratio falls below a threshold (for example, 1.2), the system starts sending margin call notifications. When the risk ratio falls below the maintenance line (for example, 1.1), the forced liquidation flow starts. Collateral is real coins, and the loan-to-value (LTV) ratio = borrowed value / collateral value, which is the core risk metric on the lending side, a different concept from the maintenance margin ratio on the contract side.

1.3 P&L Structure Differs: Maturity vs Perpetual

Contracts have no expiry (perpetual) or expire on a fixed date (dated), and PnL is settled in one shot at close. Spot margin is a lending relationship, with interest accruing per second until the user actively repays. Interest is a continuous cost: the longer the borrowing time, the higher the interest cost. This is similar to but more rigid than the contract funding mechanism — funding settles every 8 hours and can be negative (the platform pays the user), while lending interest can only be positive (the user pays the lender), and is usually calculated by the actual time used, with no free window.

1.4 Regulatory Classification Differs

Spot margin is treated in many jurisdictions as a combination of "lending + spot" and does not constitute a derivatives trade, so it is subject to relatively lighter regulation than contracts. For example, Malaysia SC classifies spot margin as a "digital asset lending service" and perpetuals as "digital futures contracts." Singapore MAS is similar: spot margin falls under a PSA license, while derivatives fall under a CMS or specific derivatives license. These differences have practical impact on product design, user suitability testing, and marketing language.

2. Lending Pool and Interest Rate Model Design

2.1 Sources of Lending Pool Funds

A spot margin lending pool typically has three sources of funds:

SourceRoleInterest RateLiquidityRiskPlatform Own Capital

Backstop, market making, rate control

Set by platform

High

Platform bears bad debt

Institutional Market Makers

Large, stable funds

Negotiated, usually below retail

Medium

Negotiation cost and credit risk

Ordinary Holders (Earn Users)

Small, retail funds

Floating, market-driven

Variable

Lent funds cannot be redeemed until maturity

In practice, a "tiered pool" structure is usually adopted: each coin maintains a master pool, with multiple sub-pools inside by fund attribute, with sub-pools potentially having different rates. Institutional market maker sub-pools have lower rates, larger quotas, and more stability; ordinary Earn user sub-pools have higher rates, floating with the market. When a sub-pool runs short, the platform can auto-advance from the master pool or its own capital pool and repay later. This layered structure allows the platform to flexibly adjust funding structure and rates at different periods.

2.2 Floating Rate Model and Utilization Curve

The core of the lending pool is "rate floats with utilization" — the more borrowing, the higher the rate, automatically pushing demand back. There are three mainstream utilization-IR curves:

Curve TypeBehavior at KneeUse CaseProsConsLinear Segmented

Slope steepens after knee

General, simple and explainable

Easy to understand

Jump at the knee

Non-Linear Smooth

Smooth transition near knee

Complex markets, institutional pools

Continuous rate

Parameter tuning complex

Two-Segment Jump

Direct jump to high rate at knee

Extreme tightening moments

Demand suppression is strong

Sudden UX change

Taking the most common "two-segment" curve as an example, set knee utilization K = 80%, slope before knee a = 0.05, slope after knee b = 1.5. When utilization U < K, rate I = a × U / K; when U ≥ K, I = a + b × (U − K) / (1 − K). At U = 0.5, I = 0.05 × 0.5 / 0.8 = 3.125%; at U = 0.95, I = 0.05 + 1.5 × 0.15 / 0.2 = 1.175, far above the pre-knee level. The purpose is to push borrowing costs up sharply after utilization reaches 80%, preventing the pool from being drained and unable to meet subsequent withdrawals.

In practice, the platform also overlays a "base rate" and a "term premium." The base rate is set by the platform with reference to external benchmark rates (SOFR, Compound on-chain rates, CeFi industry average); the term premium is priced differently by tenor — 7 days, 30 days, 90 days, flexible — with the flexible tier usually having the highest rate to compensate the lender for liquidity risk.

2.3 Multi-Currency and Multi-Tenor

The lending pool must support multiple coins and multiple tenors. By coin dimension, BTC, ETH, mainstream stablecoins, and the platform token each operate as independent pools; altcoin lending demand is small and liquidity is poor, so the platform can limit the number of coins opened. Each coin maintains independent utilization, rate, and collateral haircut.

By tenor dimension, at least the following tiers should be supported:

  • Flexible: Borrow and repay at any time, lowest rate, strongest liquidity.
  • 7 / 30 / 90 Days: Fixed tenor, repay principal and interest before maturity; rate tiers increase with duration.
  • 180 / 365 Days: Long tenor, highest rate, locks long-term funds for the platform.

Fixed tenor funds are more valuable to the platform because future liquidity demand can be predicted; lenders also get clear expected returns. The flexible tier serves retail users' "redeem at any time" need.

2.4 Borrow Quota and Available Inventory Control

Borrow quota is not unlimited. The system must control in three layers:

  • Pool Available Supply: The remaining un-borrowed funds in the pool, a hard cap. On lending, the corresponding amount of available supply is frozen; on repayment, it is released.
  • Per-User Borrow Cap: Set per the user's VIP tier, holdings, historical credit, and KYC level. For example, ordinary users can borrow up to USD 50,000 equivalent per coin, and VIP3 users can borrow up to USD 1,000,000 equivalent.
  • Risk Cap: Set a total exposure cap per the platform's lending concentration to avoid over-borrowing of a single coin. For example, BTC pool total exposure is capped at USD 500M, ETH pool at USD 300M.

In practice, "borrowable inventory" is typically shown in the UI as "Max Borrowable" — the minimum of the user's current collateral value, the maximum allowed LTV, and the pool's available supply. Borrow requests are coordinated between the matching layer and the lending layer: when an order is placed, the matching layer first checks whether the lending layer has frozen the corresponding funds; on execution, the lending layer deducts.

3. Account Modes: Isolated Margin vs Cross Margin

3.1 Isolated Margin

Isolated margin treats each trading pair (or each position group) as an independent "small account," with independent collateral, independent borrowing, and independent PnL. The BTC/USDT isolated margin position blowing up does not affect the ETH/USDT position; the loss of one coin is strictly limited to the collateral of that position and does not contaminate other positions.

In practice, the isolated margin account data structure usually contains: margin_account_id (account ID), user_id (owning user), symbol (trading pair, e.g., BTCUSDT), base_assetquote_assetbase_borrowed (base borrowed quantity), quote_borrowedbase_collateralquote_collateralliquidation_price. Each group of isolated margin positions is fully independent.

Isolated margin's advantages are risk isolation and the ability to run multiple position groups in different directions in one trading account without interfering with each other. The downsides are low capital utilization and complex UX with each position requiring its own collateral and liquidation price.

3.2 Cross Margin

Cross margin treats all coins in the account as a joint collateral pool; all borrowing and all positions share one risk ratio. For example, a user in a cross margin account holds 1 BTC + 10,000 USDT, borrows 8,000 USDT to buy ETH, and holds a long ETH position. The total account collateral value = 1 BTC × BTC price + 10,000 USDT + ETH × ETH price; total borrowed principal = 8,000 USDT, plus accrued interest. Any coin dropping that causes the risk ratio to fall allows the platform to call for additional collateral on the entire account.

Cross margin's advantages are high capital utilization and dispersed liquidation risk across the entire asset portfolio. The downside is that the user has weaker perception of single-coin risk, and "one coin blowing up can drag down the entire account" can occur. In practice, the platform usually allows the user to set a "sub-stop-loss" on a single-coin position — when a coin's price triggers the sub-stop-loss, part of that position is automatically sold to protect the overall account.

3.3 Comparison of the Two Modes

DimensionIsolated MarginCross MarginRisk Scope

Per-position independent

Whole account joint

Capital Utilization

Low

High

Collateral Management

Per position

Account-shared

Suitable Audience

Advanced traders, multi-strategy

Large capital long-term holders, portfolio hedgers

Liquidation Granularity

Per position

Whole account

UX Complexity

High

Medium

System Complexity

Medium (per-position ledger)

High (joint collateral calculation)

Most mainstream exchanges support both modes simultaneously, letting users choose freely based on strategy. SoonTech in delivery typically builds separate ledgers for the two modes; isolated and cross accounts are two independent account types that do not contaminate each other.

3.4 Fund Transfers Between Accounts

Fund transfers between isolated and cross accounts, and between margin and spot accounts, go through a dedicated "internal transfer" channel. This channel does not go on-chain and arrives instantly, but must pass risk checks:

  • The transfer amount cannot exceed the destination account's available balance.
  • After the transfer, the source account's risk ratio cannot fall below the warning line.
  • Large transfers may require secondary confirmation (SMS / email / Google Authenticator).

A common UX pitfall in practice is "transferring too much at once from the spot account to the margin account, leaving the spot account itself with insufficient funds." The UI should prompt "after this transfer, X USDT equivalent of available balance will remain."

4. Risk Ratio Calculation and Margin Monitoring

4.1 Risk Ratio and LTV

The core formula of risk ratio is: risk ratio = total asset value / total liability. Where:

  • Total Asset Value: The USDT equivalent of all collateral in the account at the current mark price.
  • Total Liability: All borrowed principal plus accrued interest.

LTV (Loan-to-Value) = total liability / total asset value = 1 / risk ratio. Lower LTV (higher risk ratio) is safer; higher LTV (lower risk ratio) is closer to liquidation.

In practice, the "risk ratio" for a single coin and the "isolated account" differ slightly. An isolated account looks only at that position's assets and liabilities; a cross account looks at the joint value of all coins. Different coin collaterals apply different haircuts in risk ratio calculation (see Section 5).

4.2 Risk Threshold Tiers

Changes in the risk ratio trigger different actions in several tiers:

Risk Ratio TierRisk StateAction> 2.0

Healthy

Normal trading, can continue borrowing

1.5 – 2.0

Attention

Can continue trading but new borrowing banned

1.3 – 1.5

Warning

In-site message / app push for margin call

1.1 – 1.3

Danger

Open position restricted, prompt to reduce or add

1.05 – 1.1

Maintenance Line

Liquidation preparation, partial reduction

< 1.05

Liquidation Line

Start forced liquidation

Different exchanges set thresholds differently. Binance spot margin maintenance line is 1.1, OKX is similar, Bybit is more aggressive at 1.05. SoonTech in delivery typically uses a "1.3 / 1.1 / 1.05" three-tier standard, with operations allowed to fine-tune per coin and per account type in the back office.

4.3 Mark Price and Price Sources

Risk ratio calculation depends on accurate "current price." But the spot price fluctuates rapidly, and using the last price can be exploited by wick attacks. In practice, the mark price is used:

Mark price = spot index price × weight + mid-prices from multiple mainstream exchanges × (1 − weight). The spot index price is a weighted average of mid-prices from Binance / OKX / Coinbase / Kraken, avoiding manipulation by a single exchange. When the deviation between spot index and mark price is too large (> 0.5%), a circuit breaker should be triggered, mark price updates paused, and operations alerted.

4.4 Real-Time Monitoring and Async Notifications

Risk ratio calculation must be frequent enough — the mainstream approach is to recalculate the user's risk ratio every 200ms to 1s. The calculation result is written to Redis cache; the risk engine subscribes to Redis change events, and accounts falling below thresholds trigger notifications immediately:

  • In-site message: async sent, with a "add margin" button link.
  • App push: mobile users via FCM / APNs.
  • Email / SMS: high-net-worth users and high-risk accounts also receive email or SMS.

The key to async notification is "delivery rate," but more importantly "can the user quickly add margin." The "add margin" button on the UI should go directly to the deposit or internal transfer page, in no more than 2 steps.

5. Collateral Management and Haircuts

5.1 Haircut Design Logic

Different coins have different volatility, liquidity, concentration, and credit risk, and the platform's acceptance of them as collateral differs. Mainstream coins like BTC and ETH can be given 80%–90% haircut (collateral value × haircut is counted into total assets); altcoins may only be 30%–50%; newly listed coins may not be supported as collateral at all.

The core formula for haircut is: collateral counted value = collateral quantity × mark price × haircut. The haircut reflects three dimensions of risk:

  • Volatility: Higher 30-day / 90-day volatility, lower haircut.
  • Liquidity: 24-hour volume, bid-ask spread, order book depth. Worse liquidity, lower haircut.
  • Concentration: The proportion of a single user's collateral in the total pool. Higher concentration, lower haircut.

5.2 Reference Haircuts for Common Coins

Coin CategoryRepresentative CoinsHaircutMax ConcentrationNotesMainstream

BTC, ETH

80% – 90%

50% per user, 30% platform

Best liquidity, controllable volatility

Mainstream Alt

SOL, BNB, TON

60% – 75%

30% per user, 20% platform

Acceptable liquidity, higher volatility

Long-Tail Alt

DOGE, PEPE, SHIB

30% – 50%

10% per user, 5% platform

Poor liquidity, dramatic volatility

Stablecoins

USDT, USDC, DAI

90% – 95%

80% per user, 60% platform

Pegged asset, almost no volatility

Platform Token

OKB, BNB (own)

50% – 70%

20% per user, 10% platform

Price affected by platform actions

Derivative LP Tokens

Uniswap LP, AAVE aToken

50% – 70%

15% per user

Compound risk

Haircuts are not static. The system should dynamically adjust weekly or monthly based on volatility, liquidity, and other data, and "reassess" all accounts using that collateral before adjustment — collateral counted value is recalculated at the new haircut, which may cause some users' risk ratio to fall below the warning line.

5.3 Net Calculation for Multi-Currency Collateral

In a cross account, the user may hold BTC + ETH + USDT + multiple altcoins. The system sums the collateral value of all coins at their respective haircuts, deducts total liabilities, and gets the risk ratio.

In practice, several details need to be handled:

  • Stablecoin Combination: USDT + USDC is treated as one stablecoin combination, but a single coin's concentration cannot exceed 80% of total stablecoins (preventing the entire combination from imploding when USDC depegs).
  • Negative Asset Handling: For coins that may temporarily fall below the marginal value corresponding to the haircut, count as 0.
  • Cross-Account Collateral: Can coins in a spot account be directly used as margin account collateral? In practice, "internal transfer" into the margin account is usually required first; direct cross-account collateral is not allowed.

5.4 Collateral Concentration Limits

In addition to haircuts, the platform should also set concentration limits:

  • Single-User Collateral Concentration: A single user's collateral of a certain coin cannot exceed X% of that coin's lending pool total scale, preventing concentrated risk from a large user.
  • Single-Coin Pool Total Scale: The platform sets a total exposure cap per coin, beyond which new borrowing is not accepted.
  • Stablecoin Reserve Ratio: The platform must maintain a certain proportion of stablecoins as "liquidity buffer," for example, 20% of total collateral must be in stablecoins.

6. Liquidation Engine and Forced Liquidation Flow

6.1 Liquidation Trigger Conditions

When the account risk ratio falls below the maintenance line (for example, 1.1) and exceeds the grace period (in practice usually 0 seconds, i.e., real-time trigger), the system starts the liquidation flow. Liquidation is not simply placing a market sell order, but follows this flow:

  1. Risk Determination: The liquidation engine subscribes to risk ratio change events. When a user's risk ratio falls below 1.1, the user is added to the liquidation queue.
  2. Pre-Check: Check whether the user has a "delayed liquidation" whitelist (VIP customers, high-net-worth users); if so, only notify without immediate liquidation.
  3. Position Selection: Based on the user's holding structure and risk source, determine the coin and quantity to liquidate. The principle is to prioritize selling the collateral with the largest drop (accelerate risk reduction), followed by the borrowed coin (directly repay liability).
  4. Execute Reduction: Call the matching engine to place a market sell order (Risk Liquidation Order); price protection mechanism prevents bankruptcy.
  5. Recalculate Risk Ratio: After reduction, recalculate the user's risk ratio; if still below the maintenance line, continue reducing until the risk ratio recovers above 1.1 or all sellable positions are sold out.

6.2 Liquidation Price Protection

Liquidation cannot smash the market without limits. Mainstream practice is to set a "liquidation protection price" that allows market orders to execute within a reasonable range:

  • Max Slippage Protection: Actual execution price vs mark price deviation cannot exceed X% (usually 1%–3%).
  • Circuit Breaker Protection: When the target pair's bid-ask spread exceeds Y bp, pause liquidation and wait for the spread to narrow.
  • Limit Order Protection: First try a limit order (0.5%–1% above market); if it does not execute, switch to market order.
  • ADL Fallback: When the market order cannot execute (insufficient depth), enter the ADL (Auto-Deleveraging) stage, forcibly reducing counterparty positions (this is a contract system concept; spot margin generally does not introduce ADL).

6.3 Dutch Auction Mode

For large or illiquid positions, some exchanges introduce a "Dutch auction" mechanism:

  • Starting Price: Mark price × 110% at the moment of liquidation trigger.
  • Price Drop Speed: Drop 0.1% every 100ms.
  • Bidders: Liquidators (can be the platform's market making team, institutional liquidators, external professional liquidation companies) take the order at the current price; execution on bid.
  • Completion Time: Usually must execute within 60 seconds, otherwise fall back to market liquidation.

This model's advantage is to marketize the liquidation price, with professional liquidators competing for bids, achieving a better average execution price than market liquidation. The downside is increased system complexity and the need to build a liquidator network. SoonTech in institutional-customer exchanges typically enables Dutch auction by default; in retail-focused small exchanges, it is disabled by default.

6.4 Cross Account Liquidation Sequence

Cross account liquidation is far more complex than isolated account, because it must decide "which coin to sell." In practice, the order is:

  1. Prioritize Selling the Collateral with the Largest Drop: The larger the drop, the higher the priority to sell, accelerating risk recovery.
  2. Prioritize Repaying High-Interest Borrowing: Reduce interest costs.
  3. Maintain Minimum Stablecoin Reserve: Unless the risk ratio is extremely low, do not sell stablecoins.
  4. Avoid Triggering Single-Coin Concentration Alert: If selling a coin causes its collateral concentration to exceed X%, temporarily stop selling that coin and switch to other coins.

In practice, this set of rules requires real-time calculation and trade-offs, and the system is complex. SoonTech provides a "liquidation policy engine" where operations can configure the weight and threshold of each rule in the back office.

7. Bankruptcy, Bad Debt, and Risk Reserves

7.1 How Bankruptcy Occurs

Bankruptcy occurs when the account risk ratio falls below 1.0, i.e., total asset value is insufficient to repay total liabilities. The account is "insolvent" and the platform and lending pool both face losses.

Typical bankruptcy scenarios:

  • Extreme Market Conditions: BTC drops 30% in 1 hour; all BTC long accounts are instantly blown up; liquidation orders cannot all execute.
  • Wick Price: Mark price is manipulated by an illiquid exchange, causing the account to be liquidated at the wrong price.
  • System Failure: Matching engine down, liquidation queue backs up; after recovery, prices have changed dramatically.
  • Collateral Implosion: A long-tail coin goes to zero in 24 hours; collateral value is zero, but the borrowing still needs to be repaid.

7.2 Bad Debt Allocation Mechanism

Who bears the loss (bad debt) from bankruptcy? Three mainstream models:

ModelBad Debt BearerProsConsPlatform Insurance Fund

Platform

Lenders unaware, good UX

Large platform exposure

Lending Pool Apportionment

All lenders in proportion

Risk shared, platform neutral

Lender returns decline

Platform + Lenders in Proportion

Both share

Balance risk and return

Rules complex

In practice, the mainstream approach is "platform insurance fund priority + lending pool apportionment when insufficient." The platform extracts the insurance fund from trading fees and lending spreads in proportion, managed in a separate account; when the insurance fund is insufficient, the future interest income of the lending pool is deducted in proportion to "the bankrupt account's borrowings as a share of that coin's pool total." Lender returns decline but do not lose principal, and the platform is not under one-time pressure.

7.3 Insurance Fund Scale

The reasonable scale of the insurance fund depends on the platform's lending scale, user structure, and coin distribution. Empirical formula:

Insurance fund target = maximum expected single-day bankruptcy loss × 10.

The maximum expected single-day bankruptcy loss can be calculated by the VaR (Value at Risk) method. In practice, the platform usually maintains the insurance fund at no less than 3%–5% of the lending pool's total scale, providing a basic buffer against extreme markets.

7.4 Bankruptcy Processing Flow

When the account risk ratio falls below 1.0:

  1. Record Bankruptcy Event: The liquidation engine records the bankruptcy time, account, loss amount, and remaining collateral.
  2. Recover Remaining Collateral: The remaining assets in the account are sold at market price, and the proceeds are returned to the lending pool.
  3. Insurance Fund Deduction: The loss amount is deducted from the platform insurance fund.
  4. Lender Apportionment: When the insurance fund is insufficient, it is deducted from the future interest income of the lending pool in proportion.
  5. Operations Notification: Finance and operations teams receive bankruptcy event notifications and enter the bad debt ledger.
  6. Legal Recovery (Optional): For large bankruptcies, the platform can pursue legal recovery, but in practice the recovery rate is very low, and the main reliance is on the insurance fund backstop.

SoonTech's liquidation engine, by default, enables "automatic posting of bankruptcy events + automatic insurance fund deduction" without manual intervention.

8. Engineering Architecture and System Decoupling

8.1 Service Decomposition

A robust spot margin system is usually divided into the following microservices:

ServiceResponsibilityKey APIsAccount Service

Spot accounts, margin accounts, isolated/cross ledgers

Query balance, transfer

Lending Service

Borrow, repay, interest accrual, pool fund scheduling

Borrow, repay, query borrowings

Rate Service

Interest rate curve, utilization calculation, rate update broadcast

Query rate, utilization

Risk Engine

Real-time risk ratio calculation, threshold monitoring, notification

Subscribe risk ratio, query risk state

Liquidation Service

Liquidation queue, position reduction execution, auction engine

Trigger liquidation, query liquidation state

Risk Control Service

Quota, allocation, anti-cheating, circuit breaker

Check order/borrowing

Matching Service

Spot matching, liquidation order routing

Place order, cancel order

Wallet Service

On-chain deposit/withdrawal, internal transfer

Withdraw, deposit, internal transfer

Post-Trade Service

Fund settlement, trade回报, fees

Subscribe trade events

Event Bus

Kafka / RocketMQ cross-service message distribution

Broadcast, subscribe

8.2 Core Data Flow

A complete borrow + trade + liquidate + repay flow involves the following events:

  1. User places an order (buy BTC): matching service receives the order → risk engine checks account state → matching executes → post-trade service broadcasts TradeEvent.
  2. Trade回报 reaches lending service: lending service updates account holdings → recalculates risk ratio → writes to Redis.
  3. Risk engine subscribes to holding change: recalculates risk ratio → triggers notification event when below threshold.
  4. Risk ratio falls below maintenance line: liquidation service receives event → joins liquidation queue → matching service places market order → post-trade service broadcasts new TradeEvent.
  5. Lending service receives repayment event: deducts borrowed principal and accrued interest → releases pool available supply.
  6. Interest Accrual: Scheduled task scans all borrowing records every hour → accrues interest by second → writes to accrued interest account.
  7. User Repayment: User actively calls repayment API → lending service deducts borrowing and interest → releases collateral.

The entire flow is event-driven; each service only cares about its own inputs and outputs and does not directly call the internal state of other services.

8.3 Database Sharding

A spot margin system has huge data volumes (a mid-sized exchange may have millions of borrowing records and tens of millions of trade records) and must be sharded:

  • Account Table (account): Sharded by user_id hash.
  • Borrowing Table (loan): Sharded by user_id hash.
  • Trade Table (trade): Sharded by trade_id hash.
  • Risk Ratio Cache (risk_snapshot): Stored with Redis Cluster.
  • Liquidation Event Table (liquidation_event): Sharded by event_id hash.
  • Cold Data Archiving: Borrowing details and trade details older than 6 months are archived to object storage or a cold database.

8.4 Consistency and Idempotency

The spot margin system involves money calculations and must guarantee strong consistency and idempotency:

  • Strong Consistency: Borrowing, repayment, and interest accrual must use database transactions to avoid concurrent deduction causing over-borrowing or duplicate repayment.
  • Idempotency: When the event bus replays, the lending service deduplicates by loan_id + event_id to avoid duplicate deduction.
  • Reconciliation Compensation: Every early morning, the lending service reconciles with the post-trade service and wallet service, and generates compensation tasks when inconsistencies are found.

SoonTech's lending service uses an "Event Sourcing" pattern, where all state changes are persisted as events, and reconciliation and rollback are implemented through event replay.

8.5 High Availability and Monitoring

The production spot margin system must meet:

  • RPO ≤ 1 Second: Achieved through master-slave replication and WAL logs.
  • RTO ≤ 30 Seconds: Liquidation service, risk engine, and risk control service are deployed in multiple replicas, and single-node failure auto-switches.
  • Circuit Breaker Protection: Pause new borrowing when lending pool utilization exceeds 95%; pause new borrowing of a coin when its liquidation volume exceeds the insurance fund.
  • Alerting: Key metrics such as the number of accounts with risk ratio below threshold, liquidation count, bankruptcy amount, insurance fund balance, and liquidation delay are wired into Prometheus + Grafana + alerting.

9. Compliance and Suitability Management

9.1 Maximum Leverage Limits

Different jurisdictions have different requirements for maximum spot margin leverage:

  • Malaysia SC: Spot margin maximum 5x.
  • Singapore MAS: Spot margin maximum 2x (some institutional clients up to 5x).
  • Indonesia BAPPEBTI: Spot margin maximum 3x, requires all leveraged products to be pre-registered.
  • Thailand SEC: Spot margin maximum 4x, requires platform to maintain minimum insurance fund scale.
  • Vietnam: No clear spot margin regulatory framework; platforms usually self-limit to 2–3x.
  • Dubai VARA: Spot margin maximum 5x, requires platform to hold a virtual asset service provider license.
  • Hong Kong SFC: Spot margin maximum 2x, professional investors up to 5x.

Platforms should dynamically adapt the leverage cap based on the user's registered country (KYC country). For cross-border clients, the stricter of "user nationality + residence" may apply.

9.2 Suitability Testing

Spot margin is not "open an account and use it"; users usually need to pass a suitability test before enabling margin functions. The test should include at least:

  • The user's awareness of leverage risk (concepts such as liquidation, margin call, bankruptcy).
  • The user's financial situation and risk tolerance (annual income, investable assets, debt situation).
  • The user's trading experience (whether they have had futures, FX, or margin trading experience).
  • The user's investment objective (short-term trading / long-term holding / hedging).

The test results are divided into several tiers: C1 (conservative) cannot enable margin; C2 (steady) can enable up to 2x; C3 (balanced) can enable up to 3–5x; C4 (aggressive) can enable up to 5–10x. Users need to retake the test each quarter, and the tier can be proactively adjusted when account or financial situation changes.

9.3 KYC and AML

Spot margin users' KYC requirements are usually the same as spot users, but the following are recommended:

  • Margin users add a "financial questionnaire" and "risk questionnaire" on top of KYC.
  • High leverage (> 5x) users must complete KYC2 (enhanced identity verification) + source-of-funds proof.
  • Large borrowing (> USD 100,000 equivalent) requires manual review and suspicious transaction investigation.
  • The fund flow of borrowing is continuously monitored, and accounts are immediately frozen if suspicious paths are found.

9.4 User Agreement and Disclosure

Compliance points for spot margin also include:

  • Risk Disclosure: Users must confirm they have read and understood risks such as "liquidation may lose all collateral," "interest accrues continuously," "extreme markets may cause bankruptcy."
  • Product Sheet: The platform should provide a product sheet clearly stating the maximum leverage, rate range, liquidation rules, and bankruptcy handling.
  • Agreement Version Control: Any changes to the user agreement and product sheet should be notified to users via in-site messages and require the user to reconfirm.
  • Tax Reporting: Some regions (e.g., Australia ATO) require platforms to report users' borrowing activities to tax authorities; the platform should support generating tax reports at the system level.

9.5 Cross-Border and Regulatory Sandbox

For platforms operating in multiple jurisdictions, a "regulatory sandbox first" strategy is recommended:

  • Pilot in new markets (Vietnam, Philippines) through the regulatory sandbox with leverage capped at the lowest level.
  • After a 3–6 month pilot, gradually relax based on user feedback and regulatory comments.
  • For jurisdictions with unclear regulation (parts of South America, Africa), maintain the lowest leverage + fast liquidation + thick insurance fund conservative strategy.

10. SoonTech Spot Margin System Implementation

10.1 Product Module Overview

The spot margin system that SoonTech has refined across multiple CEX white label projects includes the following modules:

  1. Lending Pool Center: Multi-coin, multi-tenor, tiered fund pool (institutional / retail / platform), configurable utilization-rate curve.
  2. Account and Position: Three account types — spot account, isolated margin account, cross margin account — one-stop fund transfer and internal transfer.
  3. Borrow and Repay: Real-time borrowing, per-second interest accrual, flexible and fixed tenors, auto-repayment, interest distribution.
  4. Rate Engine: Two-segment / smooth utilization-IR curve, multi-coin independent pricing, rate update broadcast.
  5. Collateral and Haircut: Multi-coin collateral management, dynamic haircut, concentration limits, real-time collateral value assessment.
  6. Risk Engine: Real-time risk ratio calculation, threshold monitoring, margin call notifications, cross-account joint risk assessment.
  7. Liquidation Service: Liquidation queue, price protection, Dutch auction engine, automatic bankruptcy event posting, automatic insurance fund deduction.
  8. Risk Control Center: Borrowing limit, per-user quota, pool exposure, circuit breaker, anti-cheating rules.
  9. Compliance and Suitability: Leverage limit, suitability test, product sheet, user agreement, KYC enhancement.
  10. Back Office and Dashboard: Operations back office (lending pool management, rate configuration, threshold configuration, bad debt ledger), user back office (borrowing detail, risk ratio, add margin), BI dashboard (pool utilization, liquidation rate, bad debt rate, interest income).
  11. Data Middle Platform: Tracking, data warehouse, ROI dashboard, user portrait, risk event analysis.

10.2 Typical Delivery Path

For a new exchange client, from signing to launching spot margin, SoonTech typically delivers on the following path:

  • Week 1: Business discovery, confirm target markets, compliance boundaries, leverage caps, coin range, rate strategy.
  • Week 2: Lending pool and rate model configuration, collateral haircut and limits, risk control rules configuration.
  • Week 3: Isolated / cross account integration, joint integration of matching engine and lending service, end-to-end flow working.
  • Week 4: Liquidation engine, insurance fund, bad debt allocation mechanism deployment and testing.
  • Week 5: Compliance and suitability module integration (KYC, risk questionnaire, user agreement).
  • Week 6: Canary testing, stress testing, security audit, operations training.
  • Week 7: Go live, 7×24 operations support and data review.

For clients with special needs (for example, custom Dutch auction, institutional client white label, cross-platform lending, on-chain lending integration), SoonTech provides source-level customization and private deployment.

10.3 Three Real Deployment Scenarios

Scenario 1: Spot Margin Cold Start of a Southeast Asian Emerging Exchange

The client is a new exchange targeting Indonesia and Vietnam, with no perpetual contract license at the start but wanting to activate holders. We helped design a "BTC + ETH + USDT three-coin lending pool," with leverage cap of 3x (compliant with Bappebti requirements), two-segment rate curve (knee at 80%), isolated and cross dual-mode in parallel; collateral haircuts BTC 85% / ETH 80% / USDT 95%; risk ratio thresholds using 1.3 / 1.1 / 1.05 three-tier. Three months after launch, the lending pool's total scale reached USD 120M, with an average daily borrowing of USD 8M equivalent, and interest income accounting for 18% of total platform revenue.

Scenario 2: Middle East Institutional Client White Label

The client is a Dubai family office wanting to provide spot margin services to high-net-worth clients, regulated by VARA. We deployed a "tiered lending pool" (institutional pool rate 6%–9% / retail pool 8%–15%), an institutional-grade Dutch auction engine, and an insurance fund scale of USD 10M equivalent. 70% of the lending pool's funds came from institutional clients, 30% from the platform's own funds. Professional liquidation companies were the liquidators, requiring a bid within 60 seconds; otherwise the system automatically fell back to market liquidation.

Scenario 3: Latin American Long-Tail Coin Lending

The client wanted to support Latin American users using local stablecoins (e.g., BRL, ARS-pegged stablecoins) as collateral to borrow USDT to go long BTC. We configured a multi-currency collateral model: long-tail stablecoin haircut 70%, concentration limit 30%, 24-hour volatility monitoring. The rate model uses a non-linear smooth curve to avoid sudden rate changes at the knee causing user complaints. After launch, user activity increased 35%, but the bad debt rate was controlled within 0.3%.

11. Enterprise Implementation Recommendations

11.1 Phased Build Cadence

  • MVP (0–2 Months): Single-coin lending pool (USDT) + isolated margin + simple rate (linear) + risk ratio 1.3 / 1.1 two tiers + basic liquidation (market order) + insurance fund backstop. First run the "borrow → trade → liquidate → bad debt handling" flow end-to-end.
  • Growth Phase (3–6 Months): Multi-coin lending pool + cross margin + floating rate curve (two-segment) + multi-tier risk ratio thresholds + reduction protection + interest distribution.
  • Maturity Phase (6–12 Months): Tiered lending pool + Dutch auction + cross-account collateral + multi-currency collateral + dynamic haircut + automatic insurance fund deduction + suitability test + multi-jurisdiction adaptation.

Do not jump to the "max coins, max modes, global jurisdictions" maximum solution on day one. 90% of new exchanges at the MVP stage only need USDT + BTC two coins, isolated + cross two modes, and 1–2 jurisdictions.

11.2 Organization and Process

The spot margin system is not a pure tech project; it needs cross-functional collaboration:

  • Product: Account modes, rate models, collateral haircuts, risk thresholds.
  • Tech: Matching, lending, risk, liquidation, risk control, data warehouse.
  • Operations: Lending pool management, campaigns, customer service.
  • Risk Control: Rules, cases, appeals.
  • Finance: Bad debt ledger, insurance fund, reconciliation.
  • Legal: Compliance opinions, user agreements, cross-border compliance.

The recommendation is to set up a virtual "Margin Product Group," led by the product owner, syncing requirements and data weekly. Early in launch, risk control and operations should review daily, adjusting rates and limits quickly.

11.3 Core Metrics for Success

  • Total Value Locked (TVL): The lending pool's total fund scale, reflecting user trust in the platform.
  • Utilization Rate: Borrowed funds / total pool scale, reflecting pool activity.
  • Net Interest Income: The platform's net income from the lending spread.
  • Bad Debt Ratio: Bankruptcy amount / total borrowed principal, with a healthy industry level < 0.5%.
  • Liquidation Success Rate: The proportion of accounts successfully liquidated at a reasonable price, target > 95%.
  • User Activity: Number of margin users, active borrowing users, average borrowing per user.
  • Risk Ratio Health: Platform-wide average risk ratio, proportion of accounts with risk ratio < 1.5.

FAQ

Q1: How should we choose between spot margin and perpetual contracts?

A: If you target "holders wanting to amplify returns," prefer spot margin — the underlying is real coins, no central counterparty risk, and compliance pressure is light. If you target "high-frequency traders needing long / short + high leverage + funding rate arbitrage," prefer perpetuals — better depth, higher leverage, richer product categories. Both can be operated simultaneously, but the product and risk control teams should be separated to avoid risk models contaminating each other.

Q2: How should the lending pool's interest rate be set?

A: The core is the "utilization → rate" elastic curve. The most common is the two-segment model: knee at 80%, slope before knee 5% (i.e., rate is 5% at full borrowing), slope after knee rises steeply by 10–20 times. BTC and ETH mainstream coin rates can be lower (market reference rate 4%–8%), and altcoin rates should be higher (10%–20%) to compensate for liquidity risk. Floating rates should "update by second" to ensure fund use and billing are in sync, but the front-end display can refresh hourly or daily.

Q3: What formula should the risk ratio use?

A: Risk ratio = total asset value (collateral after haircut) / total liability (borrowed principal + accrued interest). LTV is its reciprocal. Risk ratio 1.0 is the bankruptcy line, 1.1 is the maintenance line, and 1.3 is the warning line. Each coin's haircut reflects its volatility, liquidity, and concentration; mainstream coins 80%–90%, altcoins 30%–60%, stablecoins 90%–95%. The maintenance and warning lines can be fine-tuned by user VIP tier.

Q4: Should liquidation use market orders or Dutch auction?

A: Market orders are sufficient for small accounts and liquid trading pairs, with 1%–3% slippage protection added. For large accounts (> USD 50,000), illiquid trading pairs, and long-tail coins, a Dutch auction is recommended, with professional liquidators competing for bids. The auction engine should set a maximum execution time (usually 60 seconds), and fall back to market liquidation if it times out. Dutch auction can achieve a better average execution price than market orders by 0.5%–2%, a win-win for both the platform and liquidators.

Q5: How is bad debt allocated after bankruptcy?

A: Priority is the platform insurance fund, with the platform extracting from trading fees and lending spreads in proportion. When the insurance fund is insufficient, all lenders in the lending pool share in proportion to "the bankrupt account's borrowings as a share of the pool's total scale," and lender returns decline but do not lose principal. In rare cases, the platform can pursue legal recovery from the bankrupt user. The healthy industry bad debt rate is < 0.5%, and the platform should control bad debt within a reasonable range through limits, risk ratio monitoring, and liquidation quality.

Q6: How should leverage multiples be set in Southeast Asian markets?

A: Malaysia SC maximum 5x, Singapore MAS maximum 2x (institutional 5x), Indonesia Bappebti maximum 3x, Thailand SEC maximum 4x, Vietnam recommends 2–3x self-limit. Platforms should dynamically adapt by user KYC country, maintaining the lowest multiple + fast liquidation + thick insurance fund for high-risk jurisdictions. New exchanges are recommended to launch at 2–3x first, verify the risk model, and then gradually relax.

Conclusion

Spot margin is the most easily underestimated and most accident-prone business line in CEX. It does not have the spectacular blowups and highlights of perpetual contracts, but it connects four high-complexity subsystems — lending, matching, liquidation, and compliance — and is the touchstone for testing an exchange's risk control foundation and engineering depth. A well-designed spot margin system can turn holders into active traders, make the lending spread a stable source of revenue, and let the platform's risk control model iterate continuously in real scenarios; a poorly designed system may blow up a huge amount of bad debt in one extreme market, leaving the exchange devastated.

This article has systematically walked through the fundamental differences between spot margin and contracts, lending pools and interest rate models, isolated and cross margin accounts, risk ratio and margin calculations, collateral haircuts and multi-currency collateral, liquidation engines and auction strategies, bankruptcy and bad debt handling, interest distribution, engineering architecture and system decoupling, Southeast Asia compliance considerations, and rollout cadence, in the hope of helping teams building or optimizing an exchange build a complete mental framework. Technology is only the foundation; what really decides whether the spot margin system succeeds is whether product, operations, risk control, finance, and legal can collaborate tightly around the shared goal of "real lending relationships + real market risk + real compliance boundaries."

The SoonTech team has deep experience across CEX, DEX, prediction markets, and lending protocols, and the spot margin system is one of the most complex modules in our CEX suite, validated across multiple exchange projects in Southeast Asia, the Middle East, and Latin America. If your team is planning a spot margin system, wants to upgrade the existing margin experience, or wants to launch compliantly across multiple jurisdictions, feel free to talk to us. Based on your target market and business model, we can deliver an end-to-end solution from product design to technical delivery.

Let holders use it with more confidence, let lending funds flow more safely, let the platform grow steadily within a compliance framework — that is the only correct design goal for a spot margin system.

🌐 Build secure and scalable Web3 platforms with SoonTech.

Explore our solutions for White Label Crypto Exchanges, Prediction Markets, MPC Wallets, Matching Engines, Liquidity Integration, and Compliance.

ابدأ رحلة blockchain الخاصة بك

سيقدم لك الفريق المحترف استشارة مجانية حول الحلول

اتصل بنا