Liquidation logic

Describes the logic used for liquidations, and handling liquidation cascades

Liquidation Trigger Condition

Accounts are liquidated when equity falls below maintenance:

fn is_liquidatable(account, markets) -> bool {
    let equity = calculate_equity(account, markets)
    let maintenance = calculate_maintenance_margin(account, markets)
    let reserved = account.reserved_margin.max(0)

    equity < maintenance + reserved
}

The inclusion of reserved_margin ensures pending orders don't create hidden risk.

Liquidation Detection Process

The check_liquidations function scans all accounts:

fn check_liquidations(state, mark_prices) -> Vec<Order> {
    let mut liquidation_orders = Vec::new()
    let mut liquidation_id = 1 << 63  // Bit 63 marks liquidation orders

    for (account_id, account) in state.margin_accounts {
        let equity = calculate_equity(account, markets)
        let maintenance = calculate_maintenance_margin(account, markets)

        if equity >= maintenance + reserved {
            continue  // Account is healthy
        }

        // Generate liquidation orders for all positions
        for (market_id, position) in account.positions {
            if position.base_position == 0 {
                continue
            }

            liquidation_orders.push(Order {
                order_id: OrderId(liquidation_id),
                market_id,
                account_id,
                side: if position.base_position > 0 { Sell } else { Buy },
                price: mark_price,
                quantity: abs(position.base_position),
                timestamp: mark_price_timestamp,
            })

            liquidation_id += 1
        }
    }

    liquidation_orders
}

Liquidation Order Properties

Property
Value
Reason

Order ID

≥ 1 << 63

Bit 63 set to identify as liquidation

Side

Opposite to position

Closes the position

Price

Current mark price

Market order semantics

Quantity

Full position size

Complete liquidation

Timestamp

Mark price timestamp

Deterministic ordering

Liquidation Execution Flow

PnL Realization on Liquidation

When liquidation orders fill, PnL is realized:

The collateral balance is adjusted by realized_pnl, which may be negative.

Fill Classification

The system classifies each fill to determine accounting treatment:

Last updated