Account

Complete Reference for the PerpetualsAccount Class

Overview

The PerpetualsAccount class is a high-level wrapper around a single Perpetuals account or vault account that provides transaction builders and data access methods for trading and general account management.

Key Features:

  • Transaction Builders for:

    • Collateral management (deposit, withdraw, allocate, deallocate, transfer)

    • Order placement (market, limit, scale orders, stop orders, SL/TP)

    • Order management (cancel, edit, cancel-and-place)

    • Leverage adjustment

  • Preview Methods for:

    • Market, limit, and scale order simulations

    • Cancel order effects

    • Leverage changes

    • Collateral adjustments

  • Data Query Methods for:

    • Order and stop order data

    • Collateral change history

    • Order history

    • Margin history

  • Helper Methods for:

    • Position lookups

    • SL/TP order categorization

    • Account metadata access

circle-exclamation

Typical Usage:


Constructor

constructor

Creates a new PerpetualsAccount wrapper instance.

circle-exclamation

Parameters:

  • account: PerpetualsAccountObject

    • Raw account object containing:

      • positions: Array of open positions

      • availableCollateral: Free collateral

      • totalEquity: Total account equity

      • Other account state fields

  • accountCap: PerpetualsAccountCap | PerpetualsPartialVaultCap

    • Account cap or partial vault cap object containing:

      • accountId: Numeric account ID

      • accountObjectId: On-chain account object ID

      • collateralCoinType: Collateral type

      • walletAddress (for direct accounts) or ownerAddress (for vaults)

      • vaultId (only for vault accounts)

  • config (optional): CallerConfig

    • Configuration object containing network settings

  • Provider (optional): AftermathApi

    • Shared provider instance for transaction building

Remarks:

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

  • Automatically detects whether the account is vault-backed by checking for vaultId in the cap

  • Routes API calls to /perpetuals/account/... or /perpetuals/vault/... accordingly

Example:

Use Cases:

  1. Account Wrapping: Wrap raw account data with convenient methods

  2. Testing: Create account instances with mock data

  3. Custom Initialization: Initialize with specific configs


Public Properties

account

Raw account object containing the current snapshot of account state.

Available Fields:

  • positions: Array of PerpetualsPosition objects for each market

  • availableCollateral: Free collateral not allocated to markets

  • totalEquity: Total account equity (collateral + unrealized PnL)

  • Other account state fields

Example:


accountCap

Account cap or vault cap containing ownership and identification metadata.

For Direct Accounts (PerpetualsAccountCap):

  • objectId: Cap object ID

  • accountId: Numeric account ID

  • accountObjectId: Account object ID

  • collateralCoinType: Collateral type

  • walletAddress: Owner address

For Vault Accounts (PerpetualsPartialVaultCap):

  • vaultId: Vault object ID

  • accountId: Vault's trading account ID

  • accountObjectId: Account object ID

  • collateralCoinType: Collateral type

  • ownerAddress: Vault owner address

Example:


Agent Wallet Methods

circle-info

Want to find out more about Agent Wallets? Read more.

getGrantAgentWalletTx

Build a transaction that grants Agent Wallet (assistant permissions) for this perpetuals account.

What This Does:

Grants trading permissions to another wallet address, allowing it to execute trading operations on behalf of this account without being able to withdraw funds. This is useful for:

  • Automated trading bots

  • Portfolio managers

  • Trading assistants

  • Third-party trading services

Important:

  • Only supported for direct accounts, NOT vault accounts

  • Transaction must be signed by the account admin wallet

  • Agent wallets can perform all trading actions EXCEPT:

    • Withdrawing collateral

    • Granting or revoking other agent wallets

  • Throws error if called on a vault account

Parameters:

  • recipientAddress: SuiAddress

    • Wallet address to receive agent permissions

    • This wallet will be able to trade on behalf of the account

  • tx (optional): Transaction

    • Existing transaction to extend

Returns:

Object containing:

  • tx: Transaction - Transaction ready to sign and execute

Example:

Use Cases:

  1. Trading Bots: Grant permissions to automated trading systems

  2. Portfolio Management: Allow managers to trade on behalf of users

  3. Trading Services: Integrate with third-party trading platforms

  4. Team Trading: Enable team members to execute trades

  5. Testing: Create test agents for strategy development


getRevokeAgentWalletTx

Build a transaction that revokes Agent Wallet (assistant capability) from this perpetuals account.

What This Does:

Removes trading permissions from an agent wallet, immediately terminating its ability to trade on behalf of the account. Use this to:

  • Disable compromised agent wallets

  • Remove inactive trading bots

  • Revoke portfolio manager access

  • Clean up unused permissions

Important:

  • Only supported for direct accounts, NOT vault accounts

  • Transaction must be signed by the account admin wallet

  • Revoked wallet immediately loses all delegated permissions

  • Agent wallet can no longer execute any trading operations

  • Throws error if called on a vault account

Parameters:

  • accountCapId: ObjectId

    • Object ID of the assistant capability to revoke

    • This is the capability object that was created when granting agent permissions

  • tx (optional): Transaction

    • Existing transaction to extend

Returns:

Object containing:

  • tx: Transaction - Transaction ready to sign and execute

Example:

Use Cases:

  1. Security: Revoke compromised or suspicious agent wallets

  2. Lifecycle Management: Remove inactive or retired trading bots

  3. Access Control: Update permissions when roles change

  4. Emergency Response: Quickly disable all agents in case of issues

  5. Rotation: Regularly rotate agent credentials for security


Collateral Transaction Methods

getDepositCollateralTx

Build a deposit-collateral transaction to add collateral to this account.

What This Does:

Deposits collateral from the wallet into the Perpetuals account, increasing available collateral for trading.

Important:

  • Only supported for direct accounts, not vault accounts

  • For vaults, use PerpetualsVault.getAdminDepositTx() instead

  • Throws error if called on a vault account

Parameters:

  • tx (optional): Transaction

    • Existing transaction to extend

    • If omitted, creates new transaction

  • isSponsoredTx (optional): boolean

    • Whether transaction is gas-sponsored

  • Deposit Amount (choose one):

    • depositAmount: Balance (bigint)

      • Amount to deposit in collateral units

      • API will select/merge coins as needed

    • depositCoinArg: TransactionObjectArgument

      • Transaction coin argument from previous commands

      • Use when building complex transactions

Returns:

Object containing:

  • tx: Transaction - Transaction ready to sign and execute

Example:

Use Cases:

  1. Initial Funding: Fund new account for trading

  2. Margin Top-Up: Add collateral to avoid liquidation

  3. Position Scaling: Increase collateral before opening larger positions

  4. Batch Funding: Deposit multiple times in single transaction


getWithdrawCollateralTx

Build a withdraw-collateral transaction to remove collateral from this account.

What This Does:

Withdraws free collateral from the Perpetuals account back to a wallet or makes it available as a transaction output.

Important:

  • Only supported for direct accounts, not vault accounts

  • For vaults, use PerpetualsVault.getAdminWithdrawTx() instead

  • Can only withdraw available (unallocated) collateral

  • Throws error if called on a vault account

Parameters:

  • withdrawAmount: Balance (bigint)

    • Amount of collateral to withdraw

    • Must not exceed available collateral

  • recipientAddress (optional): SuiAddress

    • Address to receive withdrawn coins

    • If provided: coins automatically transferred

    • If omitted: coins exposed as coinOutArg for further use

  • tx (optional): Transaction

    • Existing transaction to extend

Returns:

Object containing:

  • tx: Transaction - Transaction to sign and execute

  • coinOutArg (optional): TransactionObjectArgument

    • Transaction argument for withdrawn coins

    • Only present if recipientAddress not provided

    • Can be used in subsequent transaction commands

Example:

Use Cases:

  1. Profit Taking: Withdraw profits after successful trades

  2. Portfolio Rebalancing: Move funds between accounts

  3. Margin Reduction: Reduce collateral when over-capitalized

  4. Complex Flows: Withdraw and immediately use in other protocols


getAllocateCollateralTx

Build an allocate-collateral transaction to move collateral from general account balance into a specific market.

What This Does:

Allocates (locks) collateral to a specific market/clearing house, making it available for trading in that market. This is typically done automatically during order placement, but can be done manually for advanced use cases.

Important:

  • Works for both direct accounts and vault accounts

  • Allocated collateral is locked to that market

  • Can improve margin calculations for existing positions

Parameters:

  • marketId: PerpetualsMarketId

    • Market to allocate collateral to

    • Must be a valid market ID

  • allocateAmount: Balance (bigint)

    • Amount of collateral to allocate

    • Must not exceed available collateral

  • tx (optional): Transaction

    • Existing transaction to extend

Returns:

Object containing:

  • tx: Transaction - Transaction ready to sign and execute

Example:

Use Cases:

  1. Position Preparation: Allocate before placing large orders

  2. Margin Management: Manually control market-specific collateral

  3. Multi-Market Strategy: Pre-allocate to multiple markets

  4. Risk Isolation: Separate collateral across markets


getDeallocateCollateralTx

Build a deallocate-collateral transaction to move collateral from a specific market back to general account balance.

What This Does:

Deallocates (unlocks) collateral from a specific market, returning it to the account's available balance. This is the opposite of getAllocateCollateralTx.

Important:

  • Works for both direct accounts and vault accounts

  • Can only deallocate free collateral not backing positions/orders

  • May affect margin ratios for positions in that market

Parameters:

  • marketId: PerpetualsMarketId

    • Market to deallocate collateral from

  • deallocateAmount: Balance (bigint)

    • Amount of collateral to deallocate

    • Must not exceed free collateral in that market

  • tx (optional): Transaction

    • Existing transaction to extend

Returns:

Object containing:

  • tx: Transaction - Transaction ready to sign and execute

Example:

Use Cases:

  1. Collateral Consolidation: Move free collateral to main balance

  2. Leverage Reduction: Free up collateral by reducing leverage

  3. Market Exit: Deallocate after closing positions

  4. Portfolio Rebalancing: Reallocate collateral across markets


getTransferCollateralTx

Build a transfer-collateral transaction to move collateral between two Perpetuals accounts.

What This Does:

Transfers collateral from this account to another Perpetuals account. Both accounts must use the same collateral type.

Important:

  • Only supported for direct accounts, NOT vault accounts

  • Both accounts must use the same collateral coin type

  • Throws error if called on a vault account

  • Requires sufficient available collateral

Parameters:

  • transferAmount: Balance (bigint)

    • Amount of collateral to transfer

    • Must not exceed available collateral

  • toAccountId: PerpetualsAccountId (bigint)

    • Destination account ID

    • Must be a valid Perpetuals account with matching collateral type

  • tx (optional): Transaction

    • Existing transaction to extend

Returns:

Object containing:

  • tx: Transaction - Transaction ready to sign and execute

Example:

Use Cases:

  1. Account Consolidation: Move funds between user accounts

  2. Sub-Account Management: Fund trading sub-accounts

  3. Account Migration: Move to new account

  4. Emergency Transfers: Quickly move funds for risk management


Order Transaction Methods

getPlaceMarketOrderTx

Build a place-market-order transaction for opening or closing positions.

circle-info

Works for both direct accounts and vault accounts.

circle-info

Can attach SL/TP stop orders via slTp parameter.

What This Does:

Places a market order that executes immediately at the best available price. This is the primary method for:

  • Opening new positions

  • Adding to existing positions

  • Closing positions (with reduceOnly: true)

Parameters (via SdkPerpetualsPlaceMarketOrderInputs):

  • marketId: PerpetualsMarketId

    • Market to trade in

  • side: PerpetualsOrderSide

    • PerpetualsOrderSide.Bid = Buy/Long

    • PerpetualsOrderSide.Ask = Sell/Short

  • size: bigint

    • Order size in base asset units (scaled by Casting.Fixed.fixedOneN9)

    • Must be multiple of lot size

  • collateralChange: number

    • Collateral to add (positive) or remove (negative)

    • Used for position margin adjustment

  • reduceOnly: boolean

    • true: Can only reduce position size

    • false: Can open or increase position

  • leverage (optional): number

    • Target leverage for position

    • If omitted, uses existing position leverage

  • slTp (optional): Stop-loss/take-profit parameters

    • Attaches SL/TP orders to the trade

  • tx (optional): Transaction

    • Existing transaction to extend

circle-info

Automatically derives hasPosition from account state.

Returns:

Object containing:

  • tx: Transaction - Transaction ready to sign and execute

Example:


getPlaceLimitOrderTx

Build a place-limit-order transaction for limit orders.

Example:


getPlaceScaleOrderTx

Build a place-scale-order transaction that distributes a total size across multiple limit orders evenly spaced between a start and end price.

Parameters:

  • marketId: PerpetualsMarketId

    • Target market

  • side: PerpetualsOrderSide

    • Order side (Bid = long, Ask = short)

  • 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)

  • collateralChange: number

    • Collateral change associated with the order

  • hasPosition: boolean

    • Whether the account already has a position in this market

  • reduceOnly: boolean

    • If true, orders can only reduce an existing position

  • cancelSlTp: boolean

    • True if position is closed

  • 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

    • Leverage override

  • expiryTimestamp (optional): bigint

    • Expiration timestamp in milliseconds since epoch

  • tx (optional): Transaction

    • Existing transaction to extend

Example:


getCancelAndPlaceOrdersTx

Build a cancel-and-place-orders transaction that atomically cancels existing orders and places new ones in a single transaction. Useful for rebalancing order grids or replacing stale orders without intermediate exposure.

Parameters:

  • marketId: PerpetualsMarketId

    • Target market

  • orderIdsToCancle: PerpetualsOrderId[]

    • Order IDs to cancel

  • ordersToPlace: ApiPerpetualsOrderToPlace[]

    • New orders to place after cancellation. Each order has:

      • side: PerpetualsOrderSide — order side

      • price: bigint — limit price (scaled by 1e9)

      • size: bigint — order size (scaled by 1e9)

  • orderType: PerpetualsOrderType

    • Order type for the new orders

  • reduceOnly: boolean

    • If true, placed orders can only reduce an existing position

  • hasPosition: boolean

    • Whether the account already has a position in this market

  • leverage (optional): number

    • Leverage override

  • expiryTimestamp (optional): bigint

    • Expiration timestamp in milliseconds since epoch

  • tx (optional): Transaction

    • Existing transaction to extend

Example:


getCancelOrdersTx

Build a cancel-orders transaction to cancel pending orders.

Example:


getCancelStopOrdersTx

Cancel stop-order tickets by their object IDs.

Example:


getPlaceStopOrdersTx

Place one or more stop orders in a single transaction.

Example:


getPlaceSlTpOrdersTx

Place SL/TP orders for an existing position.

circle-info

Requires an existing position in the market.

Example:


getEditStopOrdersTx

Edit existing stop orders.


getSetLeverageTx

Update leverage for a position in a market.

Example:


Stop Order Methods

getStopOrdersMessageToSign

Build a deterministic message for signing when querying stop orders.

What This Does:

Creates an off-chain authentication message that must be signed to prove account ownership when fetching stop order data.

Workflow:

  1. Call this method to get message

  2. Sign message with wallet

  3. Pass signed message to getStopOrderDatas()

Example:


nonSlTpStopOrderDatas

Filter stop orders to only include non-SL/TP orders.

What This Does:

Filters out all SL/TP stop orders from a list, returning only regular stop orders. A stop order is considered SL/TP if it appears in the combined set of SL/TP orders across all markets.

Parameters:

  • stopOrderDatas: PerpetualsStopOrderData[]

    • Full array of stop order tickets to filter

Returns:

  • PerpetualsStopOrderData[] | undefined

    • Array of non-SL/TP stop orders

    • undefined if no non-SL/TP orders exist

Example:

Use Cases:

  1. Order Management: Separate regular stop orders from SL/TP for different handling

  2. UI Display: Show different UI sections for different order types

  3. Batch Operations: Cancel or edit specific order types

  4. Analytics: Analyze regular stop order patterns


SL/TP Methods

slTpStopOrderDatas

Extract all SL/TP-style stop orders across all markets for this account.

What This Does:

Identifies and returns all stop orders that function as stop-loss or take-profit orders. These are stop orders that:

  • Have an slTp payload

  • Target the opposite side of the current position

  • Have either stopLossIndexPrice or takeProfitIndexPrice set

SL/TP Types:

  • Full SL/TP: Size >= Casting.i64MaxBigInt (close entire position)

  • Partial SL/TP: Size < Casting.i64MaxBigInt (close partial position)

Parameters:

  • stopOrderDatas: PerpetualsStopOrderData[]

    • Full list of stop order tickets

Returns:

  • PerpetualsStopOrderData[] | undefined

    • Array of all SL/TP stop orders across all markets

    • undefined if no SL/TP orders exist

Example:

Use Cases:

  1. Risk Management: Monitor and manage all SL/TP orders

  2. Position Protection: Ensure all positions have SL/TP coverage

  3. Batch Updates: Update SL/TP prices across all positions

  4. Analytics: Analyze SL/TP order distribution


nonSlTpStopOrderDatasForPosition

Filter stop orders for a single market to only include non-SL/TP orders.

What This Does:

Returns regular (non-SL/TP) stop orders for a specific market. Uses slTpStopOrderDatasForPosition internally to identify SL/TP orders, then filters them out.

Parameters:

  • marketId: PerpetualsMarketId

    • Market ID to filter for

  • stopOrderDatas: PerpetualsStopOrderData[]

    • Full list of stop orders

Returns:

  • PerpetualsStopOrderData[] | undefined

    • Non-SL/TP stop orders for the market

    • undefined if no position exists or no regular orders found

Example:

Use Cases:

  1. Market-Specific Management: Handle regular stop orders for one market

  2. UI Filtering: Display regular vs SL/TP orders separately

  3. Order Cleanup: Cancel specific types of orders per market


slTpStopOrderDatasForLimitOrder

Categorize SL/TP stop orders attached to a specific limit order.

What This Does:

Finds SL/TP stop orders that are attached to a specific limit order, separating them into full and partial orders.

Parameters:

  • stopOrderDatas: PerpetualsStopOrderData[]

    • Full list of stop orders

  • limitOrderId: PerpetualsOrderId

    • Limit order ID to find attached SL/TP for

Returns:

Object containing:

  • fullSlTpOrder: PerpetualsStopOrderData | undefined

    • Full position SL/TP order (size >= Casting.i64MaxBigInt)

  • partialSlTpOrders: PerpetualsStopOrderData[] | undefined

    • Partial position SL/TP orders (size < Casting.i64MaxBigInt)

Example:

Use Cases:

  1. Limit Order Management: Track SL/TP attached to limit orders

  2. Order Updates: Update SL/TP when limit order fills

  3. Risk Tracking: Monitor protection on pending orders


Preview Methods

getPlaceMarketOrderPreview

Preview market order effects without building a transaction.

Returns: Either { error: string } or preview object with:

  • updatedPosition: Simulated position after order

  • slippage: Expected slippage

  • executionPrice: Average execution price

  • filledSize, postedSize: Order fill amounts

  • collateralChange: Actual collateral change

Example:


getPlaceLimitOrderPreview

Preview limit order effects.

Example:


getPlaceScaleOrderPreview

Preview the effects of placing a scale order without building a transaction.

Parameters:

  • marketId: PerpetualsMarketId

    • Target market

  • side: PerpetualsOrderSide

    • Order side (Bid = long, Ask = short)

  • 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)

  • reduceOnly: boolean

    • If true, orders can only reduce an existing position

  • sizeSkew (optional): number

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

  • leverage (optional): number

    • Leverage override

  • expiryTimestamp (optional): bigint

    • Expiration timestamp in milliseconds since epoch

  • abortSignal (optional): AbortSignal

    • Signal to cancel the request

Returns:

ApiPerpetualsPreviewPlaceOrderResponse — same shape as market/limit order previews (execution price, filled/posted size, slippage, updated position, etc.), or { error: string } on failure.

Example:


getCancelOrdersPreview

Preview effects of canceling orders.

Example:


getSetLeveragePreview

Preview leverage change effects.

Example:


getEditCollateralPreview

Preview allocate/deallocate collateral effects.

Example:


Data Query Methods

getOrderDatas

Fetch latest metadata for pending orders.

What This Returns:

Current order data for all pending orders in the account, useful for refreshing order state.

Example:


getStopOrderDatas

Fetch stop order ticket data using signed authentication.

Example:


getCollateralHistory

Fetch paginated collateral change history.

Example:


getOrderHistory

Fetch paginated order history.

Example:


getMarginHistory

Fetch historical margin snapshots for charting.

Example:


Helper Methods

positionForMarketId

Find position for a specific market.

Example:


slTpStopOrderDatasForPosition

Extract SL/TP orders for a position.

Example:


collateral

Get available collateral.

Example:


isVault

Check if account is vault-backed.

Example:


ownerAddress

Get owner wallet address.


accountObjectId

Get account object ID.


accountId

Get numeric account ID.


accountCapId

Get account cap object ID (direct accounts only).


Complete Usage Examples

Example 1: Complete Trading Flow

Example 2: Position Management

Example 3: Risk Management

Last updated