Skip to main content

calculate_market_price

Function calculate_market_price 

Source
pub fn calculate_market_price(
    book_levels: &[ClobBookLevel],
    amount: Decimal,
    side: PolymarketOrderSide,
) -> Result<MarketPriceResult>
Expand description

Calculates the market-crossing price and expected base quantity by walking the order book.

Sorts levels deterministically before walking:

  • BUY (asks): ascending by price, best (lowest) ask first
  • SELL (bids): descending by price, best (highest) bid first

This ensures correct results regardless of the CLOB API’s response ordering.

For BUY: walks asks best-first, accumulates size * price (pUSD) until >= amount. Also accumulates the exact shares at each level for precise base qty. For SELL: walks bids best-first, accumulates size (shares) until >= amount.

Returns the crossing price and expected base quantity. If insufficient liquidity, uses all available levels. If the book side is empty, returns an error.