Skip to Content
VPerpDocs

Matching Engine, Order Book & Pricing

FIFO price-time priority CLOB, 12-step atomic fill settlement, tick & lot precision, Oracle & Mark Price formula, price bands, and Self-Trade Prevention.

Matching
Price-Time (FIFO)
100% on-chain CLOB
Min Notional
10 USDC
Full RO closes exempt
Price Bands
0.05×–20× · ±5%
Resting vs IOC/Market
Mark Guard
±5% · 10% Step
10s stale → reduce-only
Key Takeaways
  • Orders match deterministically on-chain using strict Price-Time Priority (FIFO); aggressive takers always receive the resting maker price (price improvement goes to the taker).
  • Before any fill settles, VCore re-verifies the resting Maker’s live margin, live VIP fee rate, and unsettled funding—preventing bad debt even after adverse moves or UTC 00:00 VIP downgrades.
  • Mark Price is a 3-input median clamped within ±5% of Oracle Index and ±10% per block, ensuring single-orderbook wicks cannot trigger false stop-losses or liquidations.
  • Self-Trade Prevention (STP) defaults to cancelOldest and supports cross-sub-account Entity STP; same-family fills never earn referral discounts or VIP/MM volume.

VPerp operates a fully on-chain Central Limit Order Book (CLOB) for both perpetual futures and spot markets.


1. Price-Time Priority (FIFO) Matching

  1. Price Priority: Higher bids fill ahead of lower bids; lower asks fill ahead of higher asks.
  2. Time Priority: Among orders resting at the exact same price level, earlier orders (oid ascending) fill first.
  3. Price Improvement: Aggressive incoming orders always execute at the resting maker's quoted price.
  4. Modify Queue Rule: Changing an order's price or increasing its size loses time priority (treated as cancel-and-replace).

2. Atomic 12-Step Fill Lifecycle (Taker vs Maker)

Every fill runs inside the transaction's atomic savepoint across three deterministic phases:

Phase 1 — Prepare & Taker Pre-Check (Steps 1–3)

StepAction
1Auto-redeem available USDC (Unified/PM); validate tick/lot grid, price bands, reduceOnly capacity, and OI/position limits.
2Taker Margin Check: Deduct unsettled hourly funding; verify cross equity (equity - unsettled_funding >= Σpos_IM + open_im) or isolated margin using undiscounted base fees + Builder Fee.
3Check per-account open_order_cap, confirm Alo does not cross BBO, check cloid uniqueness, and load live Taker fee rates.

Phase 2 — Matching & Live Maker Authorization (Steps 4–6)

StepAction
4Walk opposing book levels in FIFO order; apply Self-Trade Prevention (STP); batch candidate makers into authorize_batch.
5Live Maker Risk Re-Check: Re-evaluate each resting Maker against their current VIP/MM fee rate, resting Builder Fee (bld/<oid>), and unsettled funding. Unaffordable isolated makers trim to max affordable whole lots; unaffordable cross makers cancel cleanly (MarginCanceled).
6Intersect Taker margin/OI capacity with authorized Maker sizes and commit final fills + order-book state.

Phase 3 — Atomic Settlement & Accounting (Steps 7–12)

StepAction
7Lazy Funding Settlement: Settle all pending hourly funding ticks for Taker and each matched Maker before writing position deltas (cross → perp_usdc; isolated → pos.margin).
8Positions, PnL & Exchange Fees: Detect same-family self_cross, compute exact Taker fee (ceil) and Maker fee/rebate (-floor, hard-clamped <= taker_fee), and update positions & balances.
9Referrals & Operator Split: Accrue 10% referral rewards (positive net exchange fees only) and advance referee volume (crossing 25,000,000 USDC immediately drops the 4% discount on Fill #2 of the same sweep).
10Balance clearing-house PnL and update market Open Interest (open_size).
11Builder Fees: Collect Taker Builder Fee and resting Maker Builder Fee (bld/<oid>) into REWARDS_ESCROW (clamped to prevent negative cash if no cross position remains).
12Accumulate block VIP/MM volume (excluding same-family self_cross), reconcile Reduce-Only capacity (ro_orders), and store bld/<oid> if any remainder rests on the book.

3. Tick Precision, Lot Precision & Price Bands

  • Lot Size (szDecimals): Sizes must be exact multiples of 10−szDecimals10^{-\text{szDecimals}} from meta / spotMeta.
  • Tick / Price Precision:
    • Up to 5 significant figures (whole integer prices of any length are always accepted).
    • Maximum decimal places: 6 - szDecimals for perpetuals and 8 - szDecimals for spot markets.
    • Strip insignificant trailing zeros ("98420.5", never "98420.50").
Valid vs Rejected Price & Size Strings
Precision Check

Suppose BTC-PERP has szDecimals = 5 (max perp decimals = 6 - 5 = 1) and a Spot token has szDecimals = 2 (max spot decimals = 8 - 2 = 6):

  • "98420" → Valid (whole integer prices of any length are always accepted)
  • "9842.5" → Valid (5 significant figures and 1 decimal place on BTC-PERP)
  • "9842.55" → Rejected (2 decimal places exceeds 6 - 5 = 1 max perp decimals)
  • "0.001234" → Valid (4 significant figures and 6 decimal places on Spot with szDecimals = 2)
  • "0.0012345" → Rejected (7 decimal places exceeds 8 - 2 = 6 max spot decimals)
  • "100.50" → Rejected (trailing zero violates canonical string formatting; send "100.5")

Order Size & Price Band Protections

ProtectionSpecification
Minimum Order Notional10 USDC at tradeable price (min(limit, best_ask) for buys; max(limit, best_bid) for sells); full-position reduceOnly closes exempt
Resting Limit / ALO Price Band0.05× – 20× reference index/oracle price (px × 20 >= ref and px <= ref × 20)
Aggressive IOC / Market BandDefault ±5% (500 bps, configurable 1% – 20%). Aggressive prices beyond the band clamp inward to the nearest valid tick inside the band
Max Immediate Perp Order>= 25×: 30M USDC · 20–24×: 5M USDC · 10–19×: 2M USDC · < 10×: 500k USDC (maxMarketOrderNtls)
Open Interest CapMarkets listed in perpsAtOpenInterestCap accept risk-reducing orders only

4. Oracle Index & Mark Price Protection

Unrealized PnL, margin health, conditional TP/SL triggers, and liquidations evaluate strictly against Mark Price (never raw Last Trade price):

  1. Validator Oracle Index: Validators filter external venue outliers beyond deviation_cap_bps (default ±5%) and publish signed quotes; consensus takes the stake-weighted median (u128 widening arithmetic at 10^-18 USDC fine precision) requiring > 2/3 counted stake and >= 50% fresh stake (3 s freshness).
  2. Aligned Mark Price: Recomputed whenever the oracle aggregate moves (at most once per second) as the median of three independent inputs:
MarkPrice=median⁡ ⁣(Oracle+EMA⁡150s(BookMid−Oracle), median⁡(BestBid, BestAsk, LastTrade), Oracle)\text{MarkPrice} = \operatorname{median}\!\Big( \text{Oracle} + \operatorname{EMA}_{150\text{s}}(\text{BookMid} - \text{Oracle}),\ \operatorname{median}(\text{BestBid},\ \text{BestAsk},\ \text{LastTrade}),\ \text{Oracle} \Big)

(When a book has no quote/trade, the 30-second book EMA enters as the third input.)

  1. Three Hard Safety Clamps:
    • Oracle Band Clamp: Final Mark Price is clamped within ±5% (deviation_cap_bps = 500) of Oracle Index.
    • Single-Block Step Clamp: Mark Price cannot jump more than ±10% (1,000 bps) in a single block.
    • Stale Oracle Circuit Breaker: If oracle quotes go stale beyond stale_after_ms (default 10 s), the market enters Reduce-Only automatically (exchangeStatus reports oracleStale).
How Mark Price Neutralizes a Flash Wick
Anti-Manipulation

Suppose BTC Oracle Index = 100,000 USDC and 150 s premium EMA is +40 USDC (Input 1 = 100,040), while a thin-book sweep spikes BestBid / BestAsk / LastTrade to 112,000 USDC (Input 2 = 112,000):

  • The three inputs are [100,000, 100,040, 112,000].
  • MarkPrice=median⁡(100,000, 100,040, 112,000)=100,040 USDC\text{MarkPrice} = \operatorname{median}(100{,}000,\ 100{,}040,\ 112{,}000) = \mathbf{100{,}040\text{ USDC}}.
  • Result: Zero false short liquidations and zero false stop-loss triggers from the transient 112,000 wick.

5. Self-Trade Prevention (STP)

Configure via setStpMode (or per-order/quote "stp" override):

ModeSuppose Resting Sell = 2 BTC @ 100k and Incoming Buy = 1.5 BTC @ 100k
cancelOldest (Default)Cancels the resting 2 BTC sell; incoming 1.5 BTC buy continues matching or rests
cancelNewestCancels the incoming 1.5 BTC buy; resting 2 BTC sell stays untouched on book
cancelBothCancels both orders immediately (0 fill)
decrementAndCancelReduces both by min(2.0, 1.5) = 1.5 BTC: resting sell shrinks to 0.5 BTC, incoming buy cancels (0 fill)
  • Entity STP (setEntityStp): Enable "enabled": true on a master account so the master and all sub-accounts share one STP domain.
  • Anti-Wash Guarantee: Even with Entity STP disabled, same-family cross fills strip the 4% referral discount, pay zero referral rebate, and never count toward VIP or MM volume.

Frequently Asked Questions

On this page