Market

Complete Reference for the PerpetualsMarket Class

Overview

The PerpetualsMarket class is a high-level wrapper around a single perpetuals market that provides convenient access to market data, order book information, pricing, and order placement previews.

Key Features:

  • Lightweight accessors for market properties (prices, parameters, state)

  • Order book snapshots and real-time market data

  • Order placement preview and validation

  • Max order size calculations

  • Price and size rounding to valid tick/lot sizes

  • Margin and collateral calculations

  • 24-hour statistics and historical data

Typical Usage:

import { Aftermath } from "aftermath-ts-sdk";

const afSdk = new Aftermath("MAINNET");
await afSdk.init();

const perps = afSdk.Perpetuals();

// Get a market
const { market } = await perps.getMarket({
	marketId:
		"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
});

// Use market methods
const { orderbook } = await market.getOrderbook();
const stats = await market.get24hrStats();
const maxSize = await market.getMaxOrderSize({
	accountId: 123n,
	side: PerpetualsOrderSide.Bid,
	leverage: 5,
});

Constructor

constructor

Creates a new PerpetualsMarket wrapper instance from raw market data.

Parameters:

  • marketData: PerpetualsMarketData

    • Snapshot of market configuration and state

    • Contains:

      • objectId: Market ID

      • indexPrice: Current index/oracle price

      • collateralPrice: Price of collateral asset

      • collateralCoinType: Collateral coin type

      • marketParams: Static market parameters

      • marketState: Dynamic market state

      • baseCoinType: Base asset type

      • Other market metadata

  • config (optional): CallerConfig

    • Configuration object containing:

      • network: The Sui network ("MAINNET", "TESTNET", "DEVNET", or "LOCAL")

      • accessToken: Optional authentication token

      • Other caller-specific settings

  • Provider (optional): AftermathApi

    • Shared provider instance for advanced operations

    • Used for transaction building and additional functionality

Remarks:

  • This class extends Caller with the "perpetuals" route prefix

  • All HTTP requests resolve under /perpetuals/...

  • Typically obtained via Perpetuals.getMarket() or Perpetuals.getMarkets() rather than direct construction

Example:

Use Cases:

  1. Market Wrapping: Wrap raw market data with convenient methods

  2. Testing: Create market instances with mock data

  3. Custom Initialization: Initialize with specific network configs


Public Properties

marketId

Unique identifier for this perpetuals market (clearing house object ID on-chain).

Example:


indexPrice

Current oracle/index price for the market's underlying asset, typically quoted in USD.

Example:


collateralPrice

Current price of the collateral asset in USD (or the platform's base pricing unit).

Example:


collateralCoinType

Sui type of the collateral coin used by this market.

Example:


marketParams

Static market configuration parameters including lot size, tick size, margins, fees, and other immutable settings.

Available Fields:

  • lotSize: Minimum order size increment (bigint, 9 decimals)

  • tickSize: Minimum price increment (bigint, 9 decimals)

  • marginRatioInitial: Initial margin ratio for opening positions

  • marginRatioMaintenance: Maintenance margin ratio (liquidation threshold)

  • insuranceFundFee: Insurance fund fee percentage

  • makerFee: Maker fee percentage

  • takerFee: Taker fee percentage

  • Other market-specific parameters

Example:


marketState

Dynamic market state including funding rates, open interest, and other time-varying metrics.

Available Fields:

  • cumFundingRateLong: Cumulative funding rate for long positions

  • cumFundingRateShort: Cumulative funding rate for short positions

  • openInterestLong: Total long open interest

  • openInterestShort: Total short open interest

  • nextFundingTime: Timestamp of next funding event

  • Other dynamic state fields

Example:


Market Data Methods

getOrderbookMidPrice

Fetch the mid price for this market's orderbook.

What This Returns:

The midpoint between the best bid and best ask prices. Returns undefined if the orderbook is empty or one side is missing.

Formula:

Returns:

Object containing:

  • midPrice: number | undefined

    • Mid price if orderbook has both sides

    • undefined if orderbook is empty or incomplete

Example:

Use Cases:

  1. Order Placement: Determine competitive limit prices

  2. Spread Analysis: Calculate bid-ask spread

  3. Market Quality: Monitor orderbook depth and liquidity

  4. Trading Signals: Detect price movements


get24hrStats

Fetch 24-hour statistics for this specific market.

What This Provides:

Comprehensive 24-hour market metrics including volume, price changes, high/low prices, and trade count.

Implementation:

Under the hood, this calls Perpetuals.getMarkets24hrStats() with this market's ID and returns the result.

Returns:

PerpetualsMarket24hrStats object containing:

  • marketId: Market identifier

  • volume24h: 24-hour trading volume

  • priceChange24h: Price change percentage

  • priceChangeAbsolute24h: Absolute price change

  • high24h: Highest price in 24h

  • low24h: Lowest price in 24h

  • open24h: Opening price 24h ago

  • close24h: Most recent price

  • trades24h: Number of trades

Example:

Use Cases:

  1. Market Dashboard: Display key market metrics

  2. Performance Tracking: Monitor 24-hour performance

  3. Volatility Analysis: Calculate price ranges and volatility

  4. Trading Signals: Identify momentum and trends


getOrderbook

Fetch the full orderbook snapshot for this market.

What This Returns:

Complete orderbook with all bid and ask levels, including prices, sizes, and order IDs.

Returns:

Object containing:

  • orderbook: PerpetualsOrderbook

    • bids: Array of bid orders (buy orders), sorted by price (high to low)

      • Each entry: { price, size, orderId }

    • asks: Array of ask orders (sell orders), sorted by price (low to high)

      • Each entry: { price, size, orderId }

Example:

Use Cases:

  1. Order Book Display: Show market depth in trading UI

  2. Liquidity Analysis: Assess available liquidity at price levels

  3. Slippage Estimation: Calculate expected execution prices

  4. Market Making: Identify optimal bid/ask placement


getMaxOrderSize

Compute the maximum order size that can be placed by a given account in this market.

What This Calculates:

The maximum position size an account can open based on:

  • Available collateral

  • Existing positions

  • Target leverage

  • Initial margin requirements

  • Optional price (for limit orders)

Common Use Cases:

  • "Max" buttons in trading interfaces

  • Input validation

  • Position size suggestions

  • Risk limit checks

Parameters:

  • accountId: PerpetualsAccountId

    • Perpetuals account ID (bigint)

    • Account to calculate max size for

  • side: PerpetualsOrderSide

    • Order side (Bid = buy/long, Ask = sell/short)

    • Determines direction of position

  • leverage (optional): number

    • Target leverage for the position

    • If omitted, uses maximum available leverage

    • Must be >= 1 and <= max leverage for market

  • price (optional): number

    • Expected execution price

    • For limit orders, use limit price

    • For market orders, can be omitted (uses current index price)

Returns:

Object containing:

  • maxOrderSize: bigint

    • Maximum order size in base asset units

    • Scaled by 1e9 (9 decimal places)

    • Must be converted to float for display

Example:

Use Cases:

  1. Max Button: Auto-fill maximum safe order size

  2. Input Validation: Prevent orders exceeding capacity

  3. Position Calculator: Show maximum position value

  4. Risk Management: Enforce position limits


Order Preview Methods

getPlaceMarketOrderPreview

Market-level preview of placing a market order.

What This Does:

Simulates a market order execution without requiring a specific account's on-chain state. This is useful for:

  • Pre-trade analysis

  • Slippage estimation

  • Position preview

  • UI simulations

circle-info

Difference from PerpetualsAccount.getPlaceMarketOrderPreview:

  • PerpetualsMarket.getPlaceMarketOrderPreview: Generic preview, doesn't account for existing account state

  • PerpetualsAccount.getPlaceMarketOrderPreview: Accounts for existing positions, collateral, and fees

Parameters:

  • side: PerpetualsOrderSide

    • Order side (Bid = buy, Ask = sell)

  • size: bigint

    • Order size in base asset units (scaled by 1e9)

    • Must be multiple of lot size

  • leverage (optional): number

    • Target leverage for position

    • Affects margin requirements

  • collateralChange (optional): number

    • Collateral amount to add/remove with order

    • Positive = add, Negative = remove

  • slippageTolerance (optional): number

    • Maximum acceptable slippage (as fraction)

    • Example: 0.01 = 1%

  • abortSignal (optional): AbortSignal

    • Signal to cancel the request

Returns:

ApiPerpetualsPreviewPlaceOrderResponse which is either:

  • Success: Object containing:

    • updatedPosition: Simulated position after order

    • slippage: Expected slippage

    • filledSize: Amount filled

    • postedSize: Amount posted to orderbook

    • collateralChange: Actual collateral change

    • executionPrice: Average execution price

    • Other preview data

  • Error: { error: string } if preview fails

Example:

Use Cases:

  1. Order Confirmation: Show expected execution before placing

  2. Slippage Warning: Alert users to high slippage

  3. Position Planning: Preview position state after order

  4. Risk Analysis: Evaluate margin requirements


getPlaceLimitOrderPreview

Market-level preview of placing a limit order.

What This Does:

Simulates a limit order placement without requiring a specific account's on-chain state. Similar to market order preview but for limit orders at a specific price.

circle-info

Difference from Market Order Preview:

  • Limit orders specify exact price

  • May be partially or fully posted to orderbook

  • Execution depends on order matching

Parameters:

  • side: PerpetualsOrderSide

    • Order side (Bid = buy, Ask = sell)

  • size: bigint

    • Order size in base asset units (scaled by 1e9)

  • price: number

    • Limit price

    • Must be multiple of tick size

  • leverage (optional): number

    • Target leverage

  • collateralChange (optional): number

    • Collateral to add/remove

  • abortSignal (optional): AbortSignal

    • Signal to cancel request

Returns:

ApiPerpetualsPreviewPlaceOrderResponse (same as market order preview)

Example:

Use Cases:

  1. Limit Order Placement: Preview limit order execution

  2. Order Strategy: Plan multi-order strategies

  3. Price Discovery: Find optimal limit prices

  4. Orderbook Interaction: Understand order matching


getPlaceScaleOrderPreview

Market-level preview of placing a scale order.

What This Does:

Simulates a scale order placement without requiring a specific account's on-chain state. A scale order distributes a total size across multiple limit orders evenly spaced between a start and end price. An optional sizeSkew parameter controls whether the distribution is uniform or weighted toward one end.

circle-info

This preview runs without account context (accountId: undefined), so it cannot factor in existing positions or collateral. Use PerpetualsAccount.getPlaceScaleOrderPreview() for account-specific previews.

Parameters:

  • marketId: PerpetualsMarketId

    • Target market

  • side: PerpetualsOrderSide

    • Order side (Bid = buy, Ask = sell)

  • totalSize: bigint

    • Total size distributed across all orders (scaled by 1e9)

  • startPrice: bigint

    • Starting price of the range (inclusive, scaled by 1e9)

  • endPrice: bigint

    • Ending price of the range (inclusive, scaled by 1e9)

  • numberOfOrders: number

    • Number of limit orders to place across the range

  • orderType: PerpetualsOrderType

    • Order type (e.g. Standard, PostOnly, ImmediateOrCancel, FillOrKill)

  • reduceOnly: boolean

    • If true, orders can only reduce an existing position

  • sizeSkew (optional): number

    • Size ratio between last and first order. 1.0 = uniform distribution, 2.0 = last order is 2x the size of the first

  • leverage (optional): number

    • Target leverage

  • expiryTimestamp (optional): bigint

    • Expiration timestamp in milliseconds since epoch

  • abortSignal (optional): AbortSignal

    • Signal to cancel request

Returns:

ApiPerpetualsPreviewPlaceOrderResponse (same as market/limit order previews)

Example:

Use Cases:

  1. Scale Order Placement: Preview execution before committing to a transaction

  2. Distribution Strategy: Compare uniform vs skewed distributions

  3. Grid Trading: Plan order grids across a price range

  4. DCA Strategies: Simulate dollar-cost averaging with multiple orders


getEstimatedExecutionPrice

Estimate the average execution price for a market order of a given size.

What This Calculates:

Simulates walking the orderbook to determine the average price at which an order would execute, considering available liquidity at each price level.

How It Works:

  1. Fetches current orderbook

  2. Walks through orders on opposite side

  3. Calculates weighted average price

  4. Accounts for partial fills at each level

Parameters:

  • side: PerpetualsOrderSide

    • Order side (Bid = buy from asks, Ask = sell to bids)

  • size: bigint

    • Order size in base asset units (scaled by 1e9)

Returns:

Object containing:

  • estimatedPrice: number

    • Weighted average execution price

    • Returns 0 if insufficient liquidity

Example:

Use Cases:

  1. Order Cost Estimation: Calculate total order cost

  2. Slippage Analysis: Understand price impact

  3. Order Type Selection: Choose between market/limit

  4. Trading Strategy: Optimize order execution


Historical Data Methods

getOrderHistory

Fetch historical filled orders for this market.

What This Returns:

Paginated list of filled orders (trades) for the market, optionally filtered by account.

Parameters:

  • cursor (optional): string

    • Pagination cursor from previous request

    • Omit or pass undefined for first page

  • limit (optional): number

    • Maximum number of orders to return

    • Default/max depends on API settings

  • accountId (optional): PerpetualsAccountId

    • Filter orders by specific account

    • Omit to get all market orders

Returns:

Object containing:

  • orderHistory: PerpetualsFilledOrderData[]

    • Array of filled orders

    • Each order contains:

      • Order details (size, price, side)

      • Execution timestamp

      • Account information

      • Fees paid

  • nextCursor: string | undefined

    • Cursor for next page

    • undefined if no more pages

Example:

Use Cases:

  1. Trade History: Display user's trading history

  2. Volume Analysis: Calculate trading volume metrics

  3. Fee Tracking: Monitor fees paid

  4. Market Analysis: Analyze market trading patterns


Price & Funding Methods

getPrices

Fetch current oracle prices for this market.

What This Returns:

Latest oracle prices for both the base asset (underlying) and collateral asset.

Returns:

Object containing:

  • basePrice: number

    • Current oracle price of base asset (e.g., BTC price in USD)

  • collateralPrice: number

    • Current price of collateral asset (e.g., USDC price in USD)

circle-info

These values are also available as market.indexPrice and market.collateralPrice, but this method fetches the latest values from the API.

Example:

Use Cases:

  1. Price Updates: Get latest oracle prices

  2. Position Valuation: Calculate current position values

  3. Price Monitoring: Track price changes

  4. Liquidation Checks: Verify prices for risk calculations


timeUntilNextFundingMs

Calculate milliseconds until the next funding payment.

What This Returns:

Time remaining until next funding event in milliseconds.

Formula:

Returns:

  • number: Milliseconds until next funding

    • Positive: Time remaining

    • Negative: Funding is overdue (rare)

Example:

Use Cases:

  1. Countdown Display: Show time until funding

  2. Trading Timing: Plan trades around funding

  3. Notifications: Alert users before funding

  4. Position Management: Close positions before funding


estimatedFundingRate

Get the estimated funding rate for this market.

What This Returns:

The current estimated funding rate as a percentage (fraction). Positive rates mean longs pay shorts; negative rates mean shorts pay longs.

Returns:

  • Percentage (number): Funding rate as a fraction

    • Example: 0.01 = 1%

    • Example: -0.005 = -0.5%

Example:

Use Cases:

  1. Funding Display: Show current funding rate

  2. Cost Calculation: Estimate funding costs

  3. Trading Strategy: Identify funding arbitrage

  4. Position Management: Decide when to close positions


Collateral Calculation Methods

calcCollateralUsedForOrder

Calculate the collateral required to support an order given leverage and prices.

What This Calculates:

The amount of collateral needed for the unfilled portion of an order, based on:

  • Order size (initial - filled)

  • Target leverage

  • Current prices

  • Initial margin requirements

Formula:

Parameters:

  • leverage: number

    • Target leverage (>= 1)

    • Higher leverage = less collateral needed

  • orderData: PerpetualsOrderData

    • Order data containing:

      • initialSize: Original order size (bigint, 9 decimals)

      • filledSize: Amount already filled (bigint, 9 decimals)

  • indexPrice: number

    • Current index/oracle price of base asset

  • collateralPrice: number

    • Current price of collateral asset

Returns:

Object containing:

  • collateralUsd: number

    • Required collateral in USD

  • collateral: number

    • Required collateral in collateral coin units

Example:

Use Cases:

  1. Margin Calculation: Determine collateral requirements

  2. Order Validation: Check if user has sufficient collateral

  3. Partial Fill Handling: Calculate remaining collateral needed

  4. Leverage Planning: Compare collateral across leverage levels


Market Parameter Accessors

lotSize

Get the base-asset lot size for this market as a number.

What This Returns:

The minimum increment for order sizes. All orders must be multiples of the lot size.

Returns:

  • number: Lot size in base asset units

Example:

Use Cases:

  1. Order Validation: Check if size is valid

  2. Size Rounding: Round sizes to valid increments

  3. UI Constraints: Set input field step size


tickSize

Get the minimal price tick size for this market as a number.

What This Returns:

The minimum increment for limit prices. All limit prices must be multiples of the tick size.

Returns:

  • number: Tick size in quote units (e.g., USD)

Example:

Use Cases:

  1. Price Validation: Check if price is valid

  2. Price Rounding: Round prices to valid ticks

  3. UI Constraints: Set price input step size


maxLeverage

Get the maximum theoretical leverage for this market.

Formula:

Returns:

  • number: Maximum leverage

Example:

Use Cases:

  1. Leverage Validation: Check if leverage is allowed

  2. UI Constraints: Set maximum leverage slider value

  3. Risk Warnings: Alert users approaching max leverage


initialMarginRatio

Get the initial margin ratio for this market.

What This Is:

The minimum margin required when opening a position, expressed as a fraction.

Formula:

Returns:

  • number: Initial margin ratio (fraction)

    • Example: 0.05 = 5% = 20x leverage

Example:

Use Cases:

  1. Margin Calculation: Calculate required initial margin

  2. Position Sizing: Determine maximum position for capital

  3. Risk Display: Show margin requirements to users


maintenanceMarginRatio

Get the maintenance margin ratio for this market.

What This Is:

The minimum margin required to keep a position open. Falling below this triggers liquidation.

Returns:

  • number: Maintenance margin ratio (fraction)

    • Always less than initial margin ratio

    • Example: 0.03 = 3%

Example:

Use Cases:

  1. Liquidation Monitoring: Check if position is at risk

  2. Margin Calls: Alert users when approaching maintenance

  3. Risk Display: Show safety buffer to users


Rounding & Validation Methods

roundToValidPrice

Round a price to the nearest valid tick for this market.

Rounding Modes:

  • floor: true - Round down

  • ceil: true - Round up

  • Neither - Round to nearest (default)

Parameters:

  • price: number

    • Raw price to round

  • floor (optional): boolean

    • If true, round down

  • ceil (optional): boolean

    • If true, round up

Returns:

  • number: Price snapped to valid tick

Example:

Use Cases:

  1. Order Validation: Ensure prices meet exchange requirements

  2. UI Input: Round user input to valid prices

  3. Slippage Calculation: Adjust limit prices with slippage


roundToValidPriceBigInt

Round a price to the nearest valid tick as a fixed-point bigint (1e9 precision).

What This Returns:

Same as roundToValidPrice but returns a bigint with 9 decimal precision, suitable for on-chain operations.

Parameters:

Same as roundToValidPrice

Returns:

  • bigint: Tick-snapped price scaled by 1e9

Example:

Use Cases:

  1. Transaction Building: Prepare prices for blockchain

  2. Precision Handling: Work with exact on-chain values

  3. Order Submission: Format prices for contract calls


roundToValidSize

Round a base-asset size to the nearest valid lot size for this market.

Rounding Modes:

  • floor: true - Round down

  • ceil: true - Round up

  • Neither - Round to nearest (default)

Parameters:

  • size: number

    • Raw size to round

  • floor (optional): boolean

    • If true, round down

  • ceil (optional): boolean

    • If true, round up

Returns:

  • number: Size snapped to valid lot

Example:

Use Cases:

  1. Order Validation: Ensure sizes meet exchange requirements

  2. UI Input: Round user input to valid sizes

  3. Max Button: Round max size down for safety


roundToValidSizeBigInt

Round a base-asset size to the nearest valid lot as a fixed-point bigint (1e9 precision).

What This Returns:

Same as roundToValidSize but returns a bigint with 9 decimal precision.

Parameters:

Same as roundToValidSize

Returns:

  • bigint: Lot-snapped size scaled by 1e9

Example:

Use Cases:

  1. Transaction Building: Prepare sizes for blockchain

  2. Precision Handling: Work with exact on-chain values

  3. Order Submission: Format sizes for contract calls


Helper Methods

emptyPosition

Construct an "empty" position object for this market.

What This Returns:

A zeroed-out position object that represents no open position in the market. Useful when:

  • An account has no position in a market

  • UI/calculations expect a position object

  • Initializing position state

Returns:

  • PerpetualsPosition: Empty position with:

    • marketId: This market's ID

    • baseAssetAmount: 0 (no position)

    • collateral: 0

    • All other fields zeroed or defaulted

    • cumFundingRateLong/Short: Current market funding rates

Example:

Use Cases:

  1. Default Values: Provide default position when none exists

  2. UI Initialization: Initialize position displays

  3. State Management: Track position state over time

  4. Null Handling: Avoid null checks in position logic


Complete Usage Examples

Example 1: Complete Order Placement Flow

Example 2: Market Monitoring Dashboard

Example 3: Risk Management System

Last updated