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
This class wraps a snapshot of account state fetched via Perpetuals.getAccount(). For long-lived applications, refresh the account periodically to avoid stale state, especially:
After placing/canceling orders
After fills, liquidations, or funding settlements
After switching markets or wallets
Typical Usage:
Constructor
constructor
constructorCreates a new PerpetualsAccount wrapper instance.
You typically don't construct this directly. Instead, use Perpetuals.getAccount() or Perpetuals.getAccounts().
Parameters:
account:PerpetualsAccountObjectRaw account object containing:
positions: Array of open positionsavailableCollateral: Free collateraltotalEquity: Total account equityOther account state fields
accountCap:PerpetualsAccountCap | PerpetualsPartialVaultCapAccount cap or partial vault cap object containing:
accountId: Numeric account IDaccountObjectId: On-chain account object IDcollateralCoinType: Collateral typewalletAddress(for direct accounts) orownerAddress(for vaults)vaultId(only for vault accounts)
config(optional):CallerConfigConfiguration object containing network settings
Provider(optional):AftermathApiShared provider instance for transaction building
Remarks:
This class extends
Callerwith the"perpetuals"route prefixAutomatically detects whether the account is vault-backed by checking for
vaultIdin the capRoutes API calls to
/perpetuals/account/...or/perpetuals/vault/...accordingly
Example:
Use Cases:
Account Wrapping: Wrap raw account data with convenient methods
Testing: Create account instances with mock data
Custom Initialization: Initialize with specific configs
Public Properties
account
accountRaw account object containing the current snapshot of account state.
Available Fields:
positions: Array ofPerpetualsPositionobjects for each marketavailableCollateral: Free collateral not allocated to marketstotalEquity: Total account equity (collateral + unrealized PnL)Other account state fields
Example:
accountCap
accountCapAccount cap or vault cap containing ownership and identification metadata.
For Direct Accounts (PerpetualsAccountCap):
objectId: Cap object IDaccountId: Numeric account IDaccountObjectId: Account object IDcollateralCoinType: Collateral typewalletAddress: Owner address
For Vault Accounts (PerpetualsPartialVaultCap):
vaultId: Vault object IDaccountId: Vault's trading account IDaccountObjectId: Account object IDcollateralCoinType: Collateral typeownerAddress: Vault owner address
Example:
Agent Wallet Methods
Want to find out more about Agent Wallets? Read more.
getGrantAgentWalletTx
getGrantAgentWalletTxBuild 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:SuiAddressWallet address to receive agent permissions
This wallet will be able to trade on behalf of the account
tx(optional):TransactionExisting transaction to extend
Returns:
Object containing:
tx:Transaction- Transaction ready to sign and execute
Example:
Use Cases:
Trading Bots: Grant permissions to automated trading systems
Portfolio Management: Allow managers to trade on behalf of users
Trading Services: Integrate with third-party trading platforms
Team Trading: Enable team members to execute trades
Testing: Create test agents for strategy development
getRevokeAgentWalletTx
getRevokeAgentWalletTxBuild 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:ObjectIdObject ID of the assistant capability to revoke
This is the capability object that was created when granting agent permissions
tx(optional):TransactionExisting transaction to extend
Returns:
Object containing:
tx:Transaction- Transaction ready to sign and execute
Example:
Use Cases:
Security: Revoke compromised or suspicious agent wallets
Lifecycle Management: Remove inactive or retired trading bots
Access Control: Update permissions when roles change
Emergency Response: Quickly disable all agents in case of issues
Rotation: Regularly rotate agent credentials for security
Collateral Transaction Methods
getDepositCollateralTx
getDepositCollateralTxBuild 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()insteadThrows error if called on a vault account
Parameters:
tx(optional):TransactionExisting transaction to extend
If omitted, creates new transaction
isSponsoredTx(optional):booleanWhether 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:TransactionObjectArgumentTransaction coin argument from previous commands
Use when building complex transactions
Returns:
Object containing:
tx:Transaction- Transaction ready to sign and execute
Example:
Use Cases:
Initial Funding: Fund new account for trading
Margin Top-Up: Add collateral to avoid liquidation
Position Scaling: Increase collateral before opening larger positions
Batch Funding: Deposit multiple times in single transaction
getWithdrawCollateralTx
getWithdrawCollateralTxBuild 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()insteadCan 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):SuiAddressAddress to receive withdrawn coins
If provided: coins automatically transferred
If omitted: coins exposed as
coinOutArgfor further use
tx(optional):TransactionExisting transaction to extend
Returns:
Object containing:
tx:Transaction- Transaction to sign and executecoinOutArg(optional):TransactionObjectArgumentTransaction argument for withdrawn coins
Only present if
recipientAddressnot providedCan be used in subsequent transaction commands
Example:
Use Cases:
Profit Taking: Withdraw profits after successful trades
Portfolio Rebalancing: Move funds between accounts
Margin Reduction: Reduce collateral when over-capitalized
Complex Flows: Withdraw and immediately use in other protocols
getAllocateCollateralTx
getAllocateCollateralTxBuild 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:PerpetualsMarketIdMarket 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):TransactionExisting transaction to extend
Returns:
Object containing:
tx:Transaction- Transaction ready to sign and execute
Example:
Use Cases:
Position Preparation: Allocate before placing large orders
Margin Management: Manually control market-specific collateral
Multi-Market Strategy: Pre-allocate to multiple markets
Risk Isolation: Separate collateral across markets
getDeallocateCollateralTx
getDeallocateCollateralTxBuild 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:PerpetualsMarketIdMarket to deallocate collateral from
deallocateAmount:Balance(bigint)Amount of collateral to deallocate
Must not exceed free collateral in that market
tx(optional):TransactionExisting transaction to extend
Returns:
Object containing:
tx:Transaction- Transaction ready to sign and execute
Example:
Use Cases:
Collateral Consolidation: Move free collateral to main balance
Leverage Reduction: Free up collateral by reducing leverage
Market Exit: Deallocate after closing positions
Portfolio Rebalancing: Reallocate collateral across markets
getTransferCollateralTx
getTransferCollateralTxBuild 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):TransactionExisting transaction to extend
Returns:
Object containing:
tx:Transaction- Transaction ready to sign and execute
Example:
Use Cases:
Account Consolidation: Move funds between user accounts
Sub-Account Management: Fund trading sub-accounts
Account Migration: Move to new account
Emergency Transfers: Quickly move funds for risk management
Order Transaction Methods
getPlaceMarketOrderTx
getPlaceMarketOrderTxBuild a place-market-order transaction for opening or closing positions.
Works for both direct accounts and vault accounts.
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:PerpetualsMarketIdMarket to trade in
side:PerpetualsOrderSidePerpetualsOrderSide.Bid= Buy/LongPerpetualsOrderSide.Ask= Sell/Short
size:bigintOrder size in base asset units (scaled by
Casting.Fixed.fixedOneN9)Must be multiple of lot size
collateralChange:numberCollateral to add (positive) or remove (negative)
Used for position margin adjustment
reduceOnly:booleantrue: Can only reduce position sizefalse: Can open or increase position
leverage(optional):numberTarget leverage for position
If omitted, uses existing position leverage
slTp(optional): Stop-loss/take-profit parametersAttaches SL/TP orders to the trade
tx(optional):TransactionExisting transaction to extend
Automatically derives hasPosition from account state.
Returns:
Object containing:
tx:Transaction- Transaction ready to sign and execute
Example:
getPlaceLimitOrderTx
getPlaceLimitOrderTxBuild a place-limit-order transaction for limit orders.
Example:
getPlaceScaleOrderTx
getPlaceScaleOrderTxBuild a place-scale-order transaction that distributes a total size across multiple limit orders evenly spaced between a start and end price.
Parameters:
marketId:PerpetualsMarketIdTarget market
side:PerpetualsOrderSideOrder side (
Bid= long,Ask= short)
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)
collateralChange:numberCollateral change associated with the order
hasPosition:booleanWhether the account already has a position in this market
reduceOnly:booleanIf true, orders can only reduce an existing position
cancelSlTp:booleanTrue if position is closed
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):numberLeverage override
expiryTimestamp(optional):bigintExpiration timestamp in milliseconds since epoch
tx(optional):TransactionExisting transaction to extend
Example:
getCancelAndPlaceOrdersTx
getCancelAndPlaceOrdersTxBuild 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:PerpetualsMarketIdTarget market
orderIdsToCancle:PerpetualsOrderId[]Order IDs to cancel
ordersToPlace:ApiPerpetualsOrderToPlace[]New orders to place after cancellation. Each order has:
side:PerpetualsOrderSide— order sideprice:bigint— limit price (scaled by 1e9)size:bigint— order size (scaled by 1e9)
orderType:PerpetualsOrderTypeOrder type for the new orders
reduceOnly:booleanIf true, placed orders can only reduce an existing position
hasPosition:booleanWhether the account already has a position in this market
leverage(optional):numberLeverage override
expiryTimestamp(optional):bigintExpiration timestamp in milliseconds since epoch
tx(optional):TransactionExisting transaction to extend
Example:
getCancelOrdersTx
getCancelOrdersTxBuild a cancel-orders transaction to cancel pending orders.
Example:
getCancelStopOrdersTx
getCancelStopOrdersTxCancel stop-order tickets by their object IDs.
Example:
getPlaceStopOrdersTx
getPlaceStopOrdersTxPlace one or more stop orders in a single transaction.
Example:
getPlaceSlTpOrdersTx
getPlaceSlTpOrdersTxPlace SL/TP orders for an existing position.
Requires an existing position in the market.
Example:
getEditStopOrdersTx
getEditStopOrdersTxEdit existing stop orders.
getSetLeverageTx
getSetLeverageTxUpdate leverage for a position in a market.
Example:
Stop Order Methods
getStopOrdersMessageToSign
getStopOrdersMessageToSignBuild 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:
Call this method to get message
Sign message with wallet
Pass signed message to
getStopOrderDatas()
Example:
nonSlTpStopOrderDatas
nonSlTpStopOrderDatasFilter 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[] | undefinedArray of non-SL/TP stop orders
undefinedif no non-SL/TP orders exist
Example:
Use Cases:
Order Management: Separate regular stop orders from SL/TP for different handling
UI Display: Show different UI sections for different order types
Batch Operations: Cancel or edit specific order types
Analytics: Analyze regular stop order patterns
SL/TP Methods
slTpStopOrderDatas
slTpStopOrderDatasExtract 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
slTppayloadTarget the opposite side of the current position
Have either
stopLossIndexPriceortakeProfitIndexPriceset
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[] | undefinedArray of all SL/TP stop orders across all markets
undefinedif no SL/TP orders exist
Example:
Use Cases:
Risk Management: Monitor and manage all SL/TP orders
Position Protection: Ensure all positions have SL/TP coverage
Batch Updates: Update SL/TP prices across all positions
Analytics: Analyze SL/TP order distribution
nonSlTpStopOrderDatasForPosition
nonSlTpStopOrderDatasForPositionFilter 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:PerpetualsMarketIdMarket ID to filter for
stopOrderDatas:PerpetualsStopOrderData[]Full list of stop orders
Returns:
PerpetualsStopOrderData[] | undefinedNon-SL/TP stop orders for the market
undefinedif no position exists or no regular orders found
Example:
Use Cases:
Market-Specific Management: Handle regular stop orders for one market
UI Filtering: Display regular vs SL/TP orders separately
Order Cleanup: Cancel specific types of orders per market
slTpStopOrderDatasForLimitOrder
slTpStopOrderDatasForLimitOrderCategorize 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:PerpetualsOrderIdLimit order ID to find attached SL/TP for
Returns:
Object containing:
fullSlTpOrder:PerpetualsStopOrderData | undefinedFull position SL/TP order (size >=
Casting.i64MaxBigInt)
partialSlTpOrders:PerpetualsStopOrderData[] | undefinedPartial position SL/TP orders (size <
Casting.i64MaxBigInt)
Example:
Use Cases:
Limit Order Management: Track SL/TP attached to limit orders
Order Updates: Update SL/TP when limit order fills
Risk Tracking: Monitor protection on pending orders
Preview Methods
getPlaceMarketOrderPreview
getPlaceMarketOrderPreviewPreview market order effects without building a transaction.
Returns: Either { error: string } or preview object with:
updatedPosition: Simulated position after orderslippage: Expected slippageexecutionPrice: Average execution pricefilledSize,postedSize: Order fill amountscollateralChange: Actual collateral change
Example:
getPlaceLimitOrderPreview
getPlaceLimitOrderPreviewPreview limit order effects.
Example:
getPlaceScaleOrderPreview
getPlaceScaleOrderPreviewPreview the effects of placing a scale order without building a transaction.
Parameters:
marketId:PerpetualsMarketIdTarget market
side:PerpetualsOrderSideOrder side (
Bid= long,Ask= short)
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)
reduceOnly:booleanIf true, orders can only reduce an existing position
sizeSkew(optional):numberSize ratio between last and first order.
1.0= uniform,2.0= last is 2x first
leverage(optional):numberLeverage override
expiryTimestamp(optional):bigintExpiration timestamp in milliseconds since epoch
abortSignal(optional):AbortSignalSignal 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
getCancelOrdersPreviewPreview effects of canceling orders.
Example:
getSetLeveragePreview
getSetLeveragePreviewPreview leverage change effects.
Example:
getEditCollateralPreview
getEditCollateralPreviewPreview allocate/deallocate collateral effects.
Example:
Data Query Methods
getOrderDatas
getOrderDatasFetch 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
getStopOrderDatasFetch stop order ticket data using signed authentication.
Example:
getCollateralHistory
getCollateralHistoryFetch paginated collateral change history.
Example:
getOrderHistory
getOrderHistoryFetch paginated order history.
Example:
getMarginHistory
getMarginHistoryFetch historical margin snapshots for charting.
Example:
Helper Methods
positionForMarketId
positionForMarketIdFind position for a specific market.
Example:
slTpStopOrderDatasForPosition
slTpStopOrderDatasForPositionExtract SL/TP orders for a position.
Example:
collateral
collateralGet available collateral.
Example:
isVault
isVaultCheck if account is vault-backed.
Example:
ownerAddress
ownerAddressGet owner wallet address.
accountObjectId
accountObjectIdGet account object ID.
accountId
accountIdGet numeric account ID.
accountCapId
accountCapIdGet 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