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
constructorCreates a new PerpetualsMarket wrapper instance from raw market data.
Parameters:
marketData:PerpetualsMarketDataSnapshot of market configuration and state
Contains:
objectId: Market IDindexPrice: Current index/oracle pricecollateralPrice: Price of collateral assetcollateralCoinType: Collateral coin typemarketParams: Static market parametersmarketState: Dynamic market statebaseCoinType: Base asset typeOther market metadata
config(optional):CallerConfigConfiguration object containing:
network: The Sui network ("MAINNET", "TESTNET", "DEVNET", or "LOCAL")accessToken: Optional authentication tokenOther caller-specific settings
Provider(optional):AftermathApiShared provider instance for advanced operations
Used for transaction building and additional functionality
Remarks:
This class extends
Callerwith the"perpetuals"route prefixAll HTTP requests resolve under
/perpetuals/...Typically obtained via
Perpetuals.getMarket()orPerpetuals.getMarkets()rather than direct construction
Example:
Use Cases:
Market Wrapping: Wrap raw market data with convenient methods
Testing: Create market instances with mock data
Custom Initialization: Initialize with specific network configs
Public Properties
marketId
marketIdUnique identifier for this perpetuals market (clearing house object ID on-chain).
Example:
indexPrice
indexPriceCurrent oracle/index price for the market's underlying asset, typically quoted in USD.
Example:
collateralPrice
collateralPriceCurrent price of the collateral asset in USD (or the platform's base pricing unit).
Example:
collateralCoinType
collateralCoinTypeSui type of the collateral coin used by this market.
Example:
marketParams
marketParamsStatic 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 positionsmarginRatioMaintenance: Maintenance margin ratio (liquidation threshold)insuranceFundFee: Insurance fund fee percentagemakerFee: Maker fee percentagetakerFee: Taker fee percentageOther market-specific parameters
Example:
marketState
marketStateDynamic market state including funding rates, open interest, and other time-varying metrics.
Available Fields:
cumFundingRateLong: Cumulative funding rate for long positionscumFundingRateShort: Cumulative funding rate for short positionsopenInterestLong: Total long open interestopenInterestShort: Total short open interestpremiumTwap: Premium TWAP used to derive the live funding ratenextFundingTime: Timestamp of next funding eventOther dynamic state fields
Example:
Market Data Methods
getOrderbookMidPrice
getOrderbookMidPriceFetch 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 | undefinedMid price if orderbook has both sides
undefinedif orderbook is empty or incomplete
Example:
Use Cases:
Order Placement: Determine competitive limit prices
Spread Analysis: Calculate bid-ask spread
Market Quality: Monitor orderbook depth and liquidity
Trading Signals: Detect price movements
get24hrStats
get24hrStatsFetch 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 identifiervolume24h: 24-hour trading volumepriceChange24h: Price change percentagepriceChangeAbsolute24h: Absolute price changehigh24h: Highest price in 24hlow24h: Lowest price in 24hopen24h: Opening price 24h agoclose24h: Most recent pricetrades24h: Number of trades
Example:
Use Cases:
Market Dashboard: Display key market metrics
Performance Tracking: Monitor 24-hour performance
Volatility Analysis: Calculate price ranges and volatility
Trading Signals: Identify momentum and trends
getOrderbook
getOrderbookFetch 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:PerpetualsOrderbookbids: 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:
Order Book Display: Show market depth in trading UI
Liquidity Analysis: Assess available liquidity at price levels
Slippage Estimation: Calculate expected execution prices
Market Making: Identify optimal bid/ask placement
getMaxOrderSize
getMaxOrderSizeCompute 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:PerpetualsAccountIdPerpetuals account ID (bigint)
Account to calculate max size for
side:PerpetualsOrderSideOrder side (Bid = buy/long, Ask = sell/short)
Determines direction of position
leverage(optional):numberTarget leverage for the position
If omitted, uses maximum available leverage
Must be >= 1 and <= max leverage for market
price(optional):numberExpected execution price
For limit orders, use limit price
For market orders, can be omitted (uses current index price)
Returns:
Object containing:
maxOrderSize:bigintMaximum order size in base asset units
Scaled by 1e9 (9 decimal places)
Must be converted to float for display
Example:
Use Cases:
Max Button: Auto-fill maximum safe order size
Input Validation: Prevent orders exceeding capacity
Position Calculator: Show maximum position value
Risk Management: Enforce position limits
Order Preview Methods
getPlaceMarketOrderPreview
getPlaceMarketOrderPreviewMarket-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
Difference from PerpetualsAccount.getPlaceMarketOrderPreview:
PerpetualsMarket.getPlaceMarketOrderPreview: Generic preview, doesn't account for existing account statePerpetualsAccount.getPlaceMarketOrderPreview: Accounts for existing positions, collateral, and fees
Parameters:
side:PerpetualsOrderSideOrder side (Bid = buy, Ask = sell)
size:bigintOrder size in base asset units (scaled by 1e9)
Must be multiple of lot size
leverage(optional):numberTarget leverage for position
Affects margin requirements
collateralChange(optional):numberCollateral amount to add/remove with order
Positive = add, Negative = remove
slippageTolerance(optional):numberMaximum acceptable slippage (as fraction)
Example: 0.01 = 1%
abortSignal(optional):AbortSignalSignal to cancel the request
Returns:
ApiPerpetualsPreviewPlaceOrderResponse which is either:
Success: Object containing:
updatedPosition: Simulated position after orderslippage: Expected slippagefilledSize: Amount filledpostedSize: Amount posted to orderbookcollateralChange: Actual collateral changeexecutionPrice: Average execution priceOther preview data
Error:
{ error: string }if preview fails
Example:
Use Cases:
Order Confirmation: Show expected execution before placing
Slippage Warning: Alert users to high slippage
Position Planning: Preview position state after order
Risk Analysis: Evaluate margin requirements
getPlaceLimitOrderPreview
getPlaceLimitOrderPreviewMarket-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.
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:PerpetualsOrderSideOrder side (Bid = buy, Ask = sell)
size:bigintOrder size in base asset units (scaled by 1e9)
price:numberLimit price
Must be multiple of tick size
leverage(optional):numberTarget leverage
collateralChange(optional):numberCollateral to add/remove
abortSignal(optional):AbortSignalSignal to cancel request
Returns:
ApiPerpetualsPreviewPlaceOrderResponse (same as market order preview)
Example:
Use Cases:
Limit Order Placement: Preview limit order execution
Order Strategy: Plan multi-order strategies
Price Discovery: Find optimal limit prices
Orderbook Interaction: Understand order matching
getPlaceScaleOrderPreview
getPlaceScaleOrderPreviewMarket-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.
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:PerpetualsMarketIdTarget market
side:PerpetualsOrderSideOrder side (
Bid= buy,Ask= sell)
totalSize:bigintTotal size distributed across all orders (scaled by 1e9)
startPrice:bigintStarting price of the range (inclusive, scaled by 1e9)
endPrice:bigintEnding price of the range (inclusive, scaled by 1e9)
numberOfOrders:numberNumber of limit orders to place across the range
orderType:PerpetualsOrderTypeOrder type (e.g.
Standard,PostOnly,ImmediateOrCancel,FillOrKill)
reduceOnly:booleanIf true, orders can only reduce an existing position
sizeSkew(optional):numberSize ratio between last and first order.
1.0= uniform distribution,2.0= last order is 2x the size of the first
leverage(optional):numberTarget leverage
expiryTimestamp(optional):bigintExpiration timestamp in milliseconds since epoch
abortSignal(optional):AbortSignalSignal to cancel request
Returns:
ApiPerpetualsPreviewPlaceOrderResponse (same as market/limit order previews)
Example:
Use Cases:
Scale Order Placement: Preview execution before committing to a transaction
Distribution Strategy: Compare uniform vs skewed distributions
Grid Trading: Plan order grids across a price range
DCA Strategies: Simulate dollar-cost averaging with multiple orders
getEstimatedExecutionPrice
getEstimatedExecutionPriceEstimate 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:
Fetches current orderbook
Walks through orders on opposite side
Calculates weighted average price
Accounts for partial fills at each level
Parameters:
side:PerpetualsOrderSideOrder side (Bid = buy from asks, Ask = sell to bids)
size:bigintOrder size in base asset units (scaled by 1e9)
Returns:
Object containing:
estimatedPrice:numberWeighted average execution price
Returns 0 if insufficient liquidity
Example:
Use Cases:
Order Cost Estimation: Calculate total order cost
Slippage Analysis: Understand price impact
Order Type Selection: Choose between market/limit
Trading Strategy: Optimize order execution
Historical Data Methods
getOrderHistory
getOrderHistoryFetch 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):stringPagination cursor from previous request
Omit or pass
undefinedfor first page
limit(optional):numberMaximum number of orders to return
Default/max depends on API settings
accountId(optional):PerpetualsAccountIdFilter 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 | undefinedCursor for next page
undefinedif no more pages
Example:
Use Cases:
Trade History: Display user's trading history
Volume Analysis: Calculate trading volume metrics
Fee Tracking: Monitor fees paid
Market Analysis: Analyze market trading patterns
Price & Funding Methods
getPrices
getPricesFetch 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:numberCurrent oracle price of base asset (e.g., BTC price in USD)
collateralPrice:numberCurrent price of collateral asset (e.g., USDC price in USD)
These values are also available as market.indexPrice and market.collateralPrice, but this method fetches the latest values from the API.
Example:
Use Cases:
Price Updates: Get latest oracle prices
Position Valuation: Calculate current position values
Price Monitoring: Track price changes
Liquidation Checks: Verify prices for risk calculations
timeUntilNextFundingMs
timeUntilNextFundingMsCalculate milliseconds until the next funding payment.
What This Returns:
Time remaining until next funding event in milliseconds.
Formula:
Returns:
number: Milliseconds until next fundingPositive: Time remaining
Negative: Funding is overdue (rare)
Example:
Use Cases:
Countdown Display: Show time until funding
Trading Timing: Plan trades around funding
Notifications: Alert users before funding
Position Management: Close positions before funding
estimatedFundingRate
estimatedFundingRateGet the SDK's estimatedFundingRate field for this market.
What This Returns:
This accessor exposes the raw estimatedFundingRate value carried in the market snapshot. It can be useful for parity with the API response, but for trading logic and canonical live funding calculations you should derive funding from market.marketState.premiumTwap / market.indexPrice instead.
Returns:
Percentage(number): Funding rate as a fractionExample:
0.01= 1%Example:
-0.005= -0.5%
Example:
Use Cases:
Funding Display: Show current funding rate
Cost Calculation: Estimate funding costs
Trading Strategy: Identify funding arbitrage
Position Management: Decide when to close positions
Collateral Calculation Methods
calcCollateralUsedForOrder
calcCollateralUsedForOrderCalculate 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:numberTarget leverage (>= 1)
Higher leverage = less collateral needed
orderData:PerpetualsOrderDataOrder data containing:
initialSize: Original order size (bigint, 9 decimals)filledSize: Amount already filled (bigint, 9 decimals)
indexPrice:numberCurrent index/oracle price of base asset
collateralPrice:numberCurrent price of collateral asset
Returns:
Object containing:
collateralUsd:numberRequired collateral in USD
collateral:numberRequired collateral in collateral coin units
Example:
Use Cases:
Margin Calculation: Determine collateral requirements
Order Validation: Check if user has sufficient collateral
Partial Fill Handling: Calculate remaining collateral needed
Leverage Planning: Compare collateral across leverage levels
Market Parameter Accessors
lotSize
lotSizeGet 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:
Order Validation: Check if size is valid
Size Rounding: Round sizes to valid increments
UI Constraints: Set input field step size
tickSize
tickSizeGet 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:
Price Validation: Check if price is valid
Price Rounding: Round prices to valid ticks
UI Constraints: Set price input step size
maxLeverage
maxLeverageGet the maximum theoretical leverage for this market.
Formula:
Returns:
number: Maximum leverage
Example:
Use Cases:
Leverage Validation: Check if leverage is allowed
UI Constraints: Set maximum leverage slider value
Risk Warnings: Alert users approaching max leverage
initialMarginRatio
initialMarginRatioGet 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:
Margin Calculation: Calculate required initial margin
Position Sizing: Determine maximum position for capital
Risk Display: Show margin requirements to users
maintenanceMarginRatio
maintenanceMarginRatioGet 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:
Liquidation Monitoring: Check if position is at risk
Margin Calls: Alert users when approaching maintenance
Risk Display: Show safety buffer to users
Rounding & Validation Methods
roundToValidPrice
roundToValidPriceRound a price to the nearest valid tick for this market.
Rounding Modes:
floor: true- Round downceil: true- Round upNeither - Round to nearest (default)
Parameters:
price:numberRaw price to round
floor(optional):booleanIf true, round down
ceil(optional):booleanIf true, round up
Returns:
number: Price snapped to valid tick
Example:
Use Cases:
Order Validation: Ensure prices meet exchange requirements
UI Input: Round user input to valid prices
Slippage Calculation: Adjust limit prices with slippage
roundToValidPriceBigInt
roundToValidPriceBigIntRound 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:
Transaction Building: Prepare prices for blockchain
Precision Handling: Work with exact on-chain values
Order Submission: Format prices for contract calls
roundToValidSize
roundToValidSizeRound a base-asset size to the nearest valid lot size for this market.
Rounding Modes:
floor: true- Round downceil: true- Round upNeither - Round to nearest (default)
Parameters:
size:numberRaw size to round
floor(optional):booleanIf true, round down
ceil(optional):booleanIf true, round up
Returns:
number: Size snapped to valid lot
Example:
Use Cases:
Order Validation: Ensure sizes meet exchange requirements
UI Input: Round user input to valid sizes
Max Button: Round max size down for safety
roundToValidSizeBigInt
roundToValidSizeBigIntRound 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:
Transaction Building: Prepare sizes for blockchain
Precision Handling: Work with exact on-chain values
Order Submission: Format sizes for contract calls
Helper Methods
emptyPosition
emptyPositionConstruct 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 IDbaseAssetAmount: 0 (no position)collateral: 0All other fields zeroed or defaulted
cumFundingRateLong/Short: Current market funding rates
Example:
Use Cases:
Default Values: Provide default position when none exists
UI Initialization: Initialize position displays
State Management: Track position state over time
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