Zeta SDK CrossClient Full Documentation
Initialization and Setup
Load and Initialize CrossClient
CrossClient.load( connection: Connection, wallet: Wallet, opts?: ConfirmOptions, callback?: Function, throttle?: boolean, delegator?: PublicKey, useVersionedTxs?: boolean, txRetryAmount?: number, subaccountIndex?: number):Promise<CrossClient>
Creates and initializes a new instance of the CrossClient.
Description
The CrossClient.load()
method initializes a new CrossClient instance, which provides functionality for managing cross-margin accounts, placing and canceling orders, handling deposits and withdrawals, and more in the Zeta Markets protocol.
Parameters
-
connection
- (Connection) Required.
- Solana connection object.
-
wallet
- (Wallet) Required.
- Wallet interface for signing transactions.
-
opts
- (ConfirmOptions) Optional.
- Confirmation options for transactions.
- Default:
undefined
-
callback
- (Function) Optional.
- Function to handle events.
- Default:
undefined
-
throttle
- (boolean) Optional.
- Whether to throttle updates.
- Default:
false
-
delegator
- (PublicKey) Optional.
- Public key of the delegator.
- Default:
undefined
-
useVersionedTxs
- (boolean) Optional.
- Whether to use versioned transactions.
- Default:
false
-
txRetryAmount
- (number) Optional.
- Number of times to retry a failed transaction.
- Default:
undefined
-
subaccountIndex
- (number) Optional.
- Index of the subaccount.
- Default:
0
Return
- (Promise
) A promise that resolves to a new CrossClient instance.
Example
import { Connection } from '@solana/web3.js';import { CrossClient, Wallet } from '@zetamarkets/sdk';
const connection = new Connection('https://api.mainnet-beta.solana.com');const wallet = new Wallet(/* ... */);
const crossClient = await CrossClient.load(connection, wallet);
Account Management
Initialize Accounts
initializeAccounts(referrerId?: string): Promise<TransactionSignature>
Initializes the CrossMarginAccount and CrossMarginAccountManager.
Description
The initializeAccounts()
method creates the necessary accounts for trading on the Zeta Markets protocol. It initializes both the CrossMarginAccount and CrossMarginAccountManager if they don’t already exist.
Parameters
referrerId
- (string) Optional.
- Referrer ID for account initialization.
- Default:
undefined
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const txSignature = await crossClient.initializeAccounts("REFERRER_ID");console.log("Accounts initialized. Transaction signature:", txSignature);
Deposit Funds
deposit(amount: number, referrerId?: string): Promise<TransactionSignature>
Deposits funds into the cross-margin account.
Description
The deposit()
method allows you to add funds to your cross-margin account. If the account doesn’t exist, it will be created automatically.
Parameters
-
amount
- (number) Required.
- Amount to deposit (in native units, 6 decimal places).
-
referrerId
- (string) Optional.
- Referrer ID for new accounts.
- Default:
undefined
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const amountToDeposit = 1000000; // 1 USDCconst txSignature = await crossClient.deposit(amountToDeposit);console.log("Deposit successful. Transaction signature:", txSignature);
Withdraw Funds
withdraw(amount: number): Promise<TransactionSignature>
Withdraws funds from the cross-margin account.
Description
The withdraw()
method allows you to remove funds from your cross-margin account.
Parameters
amount
- (number) Required.
- Amount to withdraw (in native units, 6 decimal places).
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const amountToWithdraw = 500000; // 0.5 USDCconst txSignature = await crossClient.withdraw(amountToWithdraw);console.log("Withdrawal successful. Transaction signature:", txSignature);
Close Account
closeAccount(): Promise<TransactionSignature>
Closes the CrossClient’s account.
Description
The closeAccount()
method closes the CrossMarginAccount associated with the CrossClient instance.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const txSignature = await crossClient.closeAccount();console.log("Account closed. Transaction signature:", txSignature);
Close Account Manager
closeAccountManager(): Promise<TransactionSignature>
Closes the CrossClient’s account manager.
Description
The closeAccountManager()
method closes the CrossMarginAccountManager associated with the CrossClient instance.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const txSignature = await crossClient.closeAccountManager();console.log("Account manager closed. Transaction signature:", txSignature);
Close Account and Manager
closeAccountAndManager(): Promise<TransactionSignature>
Closes both the CrossMarginAccount and CrossMarginAccountManager in one transaction.
Description
The closeAccountAndManager()
method closes both the CrossMarginAccount and CrossMarginAccountManager associated with the CrossClient instance in a single transaction.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const txSignature = await crossClient.closeAccountAndManager();console.log("Account and manager closed. Transaction signature:", txSignature);
Withdraw and Close Account
withdrawAndCloseAccount(): Promise<TransactionSignature>
Withdraws the entirety of the CrossClient’s margin account and then closes it.
Description
The withdrawAndCloseAccount()
method withdraws all funds from the CrossMarginAccount and then closes it. This is useful for closing a single subaccount.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const txSignature = await crossClient.withdrawAndCloseAccount();console.log("Funds withdrawn and account closed. Transaction signature:", txSignature);
Withdraw, Close Account, and Close Manager
withdrawAndCloseAccountAndCloseManager(): Promise<TransactionSignature>
Withdraws all funds, closes the margin account, and closes the account manager.
Description
The withdrawAndCloseAccountAndCloseManager()
method withdraws all funds from the CrossMarginAccount, closes it, and then closes the CrossMarginAccountManager. This is useful for completely closing out all accounts associated with the CrossClient.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const txSignature = await crossClient.withdrawAndCloseAccountAndCloseManager();console.log("Funds withdrawn, account and manager closed. Transaction signature:", txSignature);
Order Placement and Management
Place Order
placeOrder(asset: Asset, price: number, size: number, side: types.Side, options?: types.OrderOptions, preIxs?: TransactionInstruction[]): Promise<TransactionSignature>
Places an order on a Zeta perp market.
Description
The placeOrder()
method allows you to place an order on a specific asset’s perpetual market.
Parameters
-
asset
- (Asset) Required.
- Asset to trade.
-
price
- (number) Required.
- Order price (in native units, 6 decimal places).
-
size
- (number) Required.
- Order size (in native units, 3 decimal places).
-
side
- (types.Side) Required.
- Order side (BID or ASK).
-
options
- (types.OrderOptions) Optional.
- Order options.
- Default:
types.defaultOrderOptions()
-
preIxs
- (TransactionInstruction[]) Optional.
- Additional instructions to include before the order placement.
- Default:
[]
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset, types } from '@zetamarkets/sdk';
const txSignature = await crossClient.placeOrder( Asset.SOL, 20000000, // $20 price 1000, // 1 SOL size types.Side.BID);console.log("Order placed. Transaction signature:", txSignature);
Place Timestamp Trigger Order
placeTimestampTriggerOrder(asset: Asset, orderPrice: number, triggerTime: anchor.BN, size: number, side: types.Side, orderType: types.OrderType, options?: types.TriggerOrderOptions): Promise<TransactionSignature>
Places a trigger order that will execute at a specific timestamp.
Description
The placeTimestampTriggerOrder()
method allows you to place a trigger order that will be executed when a specific timestamp is reached.
Parameters
-
asset
- (Asset) Required.
- Asset to trade.
-
orderPrice
- (number) Required.
- Order price (in native units, 6 decimal places).
-
triggerTime
- (anchor.BN) Required.
- Unix timestamp for order execution.
-
size
- (number) Required.
- Order size (in native units, 3 decimal places).
-
side
- (types.Side) Required.
- Order side (BID or ASK).
-
orderType
- (types.OrderType) Required.
- Type of order to place.
-
options
- (types.TriggerOrderOptions) Optional.
- Trigger order options.
- Default:
types.defaultTriggerOrderOptions()
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset, types } from '@zetamarkets/sdk';import { BN } from '@zetamarkets/anchor';
const triggerTime = new BN(Math.floor(Date.now() / 1000) + 3600); // 1 hour from now
const txSignature = await crossClient.placeTimestampTriggerOrder( Asset.SOL, 20000000, // $20 price triggerTime, 1000, // 1 SOL size types.Side.BID, types.OrderType.LIMIT);console.log("Timestamp trigger order placed. Transaction signature:", txSignature);
Place Price Trigger Order
placePriceTriggerOrder(asset: Asset, orderPrice: number, triggerPrice: number, size: number, side: types.Side, orderType: types.OrderType, options?: types.TriggerOrderOptions, triggerDirection?: types.TriggerDirection): Promise<TransactionSignature>
Places a trigger order that will execute when the mark price reaches a specific level.
Description
The placePriceTriggerOrder()
method allows you to place a trigger order that will be executed when the mark price of the asset reaches a specified trigger price.
Parameters
-
asset
- (Asset) Required.
- Asset to trade.
-
orderPrice
- (number) Required.
- Order price (in native units, 6 decimal places).
-
triggerPrice
- (number) Required.
- Price at which to trigger the order (in native units, 6 decimal places).
-
size
- (number) Required.
- Order size (in native units, 3 decimal places).
-
side
- (types.Side) Required.
- Order side (BID or ASK).
-
orderType
- (types.OrderType) Required.
- Type of order to place.
-
options
- (types.TriggerOrderOptions) Optional.
- Trigger order options.
- Default:
types.defaultTriggerOrderOptions()
-
triggerDirection
- (types.TriggerDirection) Optional.
- Direction for price trigger.
- Default:
types.getDefaultTriggerDirection(side)
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset, types } from '@zetamarkets/sdk';
const txSignature = await crossClient.placePriceTriggerOrder( Asset.SOL, 20000000, // $20 order price 19000000, // $19 trigger price 1000, // 1 SOL size types.Side.BID, types.OrderType.LIMIT);console.log("Price trigger order placed. Transaction signature:", txSignature);
Cancel Order
cancelOrder(asset: Asset, orderId: BN, side: types.Side): Promise<TransactionSignature>
Cancels a specific order by order ID.
Description
The cancelOrder()
method allows you to cancel an existing order on a specific asset’s market.
Parameters
-
asset
- (Asset) Required.
- Asset of the order to cancel.
-
orderId
- (BN) Required.
- Order ID to cancel.
-
side
- (types.Side) Required.
- Side of the order (BID or ASK).
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset, types } from '@zetamarkets/sdk';import { BN } from '@zetamarkets/anchor';
const txSignature = await crossClient.cancelOrder( Asset.SOL, new BN("123456"), // Order ID types.Side.BID);console.log("Order cancelled. Transaction signature:", txSignature);
Cancel Order by Client Order ID
cancelOrderByClientOrderId(asset: Asset, clientOrderId: number): Promise<TransactionSignature>
Cancels an order by client order ID.
Description
The cancelOrderByClientOrderId()
method allows you to cancel an existing order using the client-specified order ID.
Parameters
-
asset
- (Asset) Required.
- Asset of the order to cancel.
-
clientOrderId
- (number) Required.
- Client order ID to cancel.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset } from '@zetamarkets/sdk';
const txSignature = await crossClient.cancelOrderByClientOrderId( Asset.SOL, 12345 // Client Order ID);console.log("Order cancelled by client order ID. Transaction signature:", txSignature);
Cancel and Place Order
cancelAndPlaceOrder(asset: Asset, orderId: BN, cancelSide: types.Side, newOrderPrice: number, newOrderSize: number, newOrderSide: types.Side, options?: types.OrderOptions): Promise<TransactionSignature>
Cancels an existing order and places a new order atomically.
Description
The cancelAndPlaceOrder()
method allows you to cancel an existing order and place a new order in a single atomic transaction. This is useful for quickly adjusting your position in the market.
Parameters
-
asset
- (Asset) Required.
- Asset to trade.
-
orderId
- (BN) Required.
- Order ID of the order to cancel.
-
cancelSide
- (types.Side) Required.
- Side of the order to cancel (BID or ASK).
-
newOrderPrice
- (number) Required.
- Price of the new order (in native units, 6 decimal places).
-
newOrderSize
- (number) Required.
- Size of the new order (in native units, 3 decimal places).
-
newOrderSide
- (types.Side) Required.
- Side of the new order (BID or ASK).
-
options
- (types.OrderOptions) Optional.
- Options for the new order.
- Default:
types.defaultOrderOptions()
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset, types } from '@zetamarkets/sdk';import { BN } from '@zetamarkets/anchor';
const txSignature = await crossClient.cancelAndPlaceOrder( Asset.SOL, new BN("123456"), // Order ID to cancel types.Side.BID, // Side of the order to cancel 21000000, // New order price ($21) 1000, // New order size (1 SOL) types.Side.BID // New order side);console.log("Order cancelled and new order placed. Transaction signature:", txSignature);
Cancel All Orders
cancelAllOrders(asset?: Asset): Promise<TransactionSignature[]>
Cancels all active orders for a specific asset or all assets.
Description
The cancelAllOrders()
method allows you to cancel all active orders for a specific asset. If no asset is specified, it cancels orders for all assets.
Parameters
asset
- (Asset) Optional.
- Asset to cancel orders for. If undefined, cancels for all assets.
- Default:
undefined
Return
- (Promise<TransactionSignature[]>) A promise that resolves to an array of transaction signatures.
Example
import { Asset } from '@zetamarkets/sdk';
// Cancel all SOL ordersconst txSignatures = await crossClient.cancelAllOrders(Asset.SOL);console.log("All SOL orders cancelled. Transaction signatures:", txSignatures);
// Cancel all orders for all assets// const txSignatures = await crossClient.cancelAllOrders();
Cancel All Orders No Error
cancelAllOrdersNoError(asset?: Asset): Promise<TransactionSignature[]>
Cancels all active orders for a specific asset or all assets, ignoring errors.
Description
The cancelAllOrdersNoError()
method is similar to cancelAllOrders()
, but it continues to process cancellations even if some orders fail to cancel. This can be useful in situations where you want to ensure as many orders as possible are cancelled, even if some cancellations fail.
Parameters
asset
- (Asset) Optional.
- Asset to cancel orders for. If undefined, cancels for all assets.
- Default:
undefined
Return
- (Promise<TransactionSignature[]>) A promise that resolves to an array of transaction signatures.
Example
const txSignatures = await crossClient.cancelAllOrdersNoError();console.log("All orders cancelled (ignoring errors). Transaction signatures:", txSignatures);
Cancel Trigger Order
cancelTriggerOrder(orderIndex: number): Promise<TransactionSignature>
Cancels a specific trigger order.
Description
The cancelTriggerOrder()
method allows you to cancel a specific trigger order by its index.
Parameters
orderIndex
- (number) Required.
- Index of the trigger order to cancel.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const txSignature = await crossClient.cancelTriggerOrder(0);console.log("Trigger order cancelled. Transaction signature:", txSignature);
Cancel All Trigger Orders
cancelAllTriggerOrders(asset?: Asset): Promise<string[]>
Cancels all trigger orders for a specific asset or all assets.
Description
The cancelAllTriggerOrders()
method allows you to cancel all trigger orders for a specific asset. If no asset is specified, it cancels trigger orders for all assets.
Parameters
asset
- (Asset) Optional.
- Asset to cancel trigger orders for. If undefined, cancels for all assets.
- Default:
undefined
Return
- (Promise<string[]>) A promise that resolves to an array of transaction signatures.
Example
import { Asset } from '@zetamarkets/sdk';
const txSignatures = await crossClient.cancelAllTriggerOrders(Asset.SOL);console.log("All SOL trigger orders cancelled. Transaction signatures:", txSignatures);
// To cancel all trigger orders for all assets:// const txSignatures = await crossClient.cancelAllTriggerOrders();
Cancel All Trigger Orders and Place Order
cancelAllTriggerOrdersAndPlaceOrder(asset: Asset, price: number, size: number, side: types.Side, options?: types.OrderOptions): Promise<string[]>
Cancels all trigger orders for a specific asset and places a new order.
Description
The cancelAllTriggerOrdersAndPlaceOrder()
method cancels all trigger orders for a specific asset and then places a new order. This is useful for quickly adjusting your strategy in changing market conditions.
Parameters
-
asset
- (Asset) Required.
- Asset to trade and cancel trigger orders for.
-
price
- (number) Required.
- Price of the new order (in native units, 6 decimal places).
-
size
- (number) Required.
- Size of the new order (in native units, 3 decimal places).
-
side
- (types.Side) Required.
- Side of the new order (BID or ASK).
-
options
- (types.OrderOptions) Optional.
- Options for the new order.
- Default:
types.defaultOrderOptions()
Return
- (Promise<string[]>) A promise that resolves to an array of transaction signatures.
Example
import { Asset, types } from '@zetamarkets/sdk';
const txSignatures = await crossClient.cancelAllTriggerOrdersAndPlaceOrder( Asset.SOL, 20000000, // $20 price 1000, // 1 SOL size types.Side.BID);console.log("All trigger orders cancelled and new order placed. Transaction signatures:", txSignatures);
Position Management
Liquidate
liquidate(asset: Asset, liquidatedMarginAccount: PublicKey, size: number): Promise<TransactionSignature>
Liquidates a position in another user’s account.
Description
The liquidate()
method allows you to liquidate a position in another user’s account. This function is typically used by liquidators to manage risk in the system.
Parameters
-
asset
- (Asset) Required.
- Asset to liquidate.
-
liquidatedMarginAccount
- (PublicKey) Required.
- Public key of the account to liquidate.
-
size
- (number) Required.
- Size of the position to liquidate (in native units, 3 decimal places).
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset } from '@zetamarkets/sdk';import { PublicKey } from '@solana/web3.js';
const liquidatedAccountPubkey = new PublicKey("..."); // Public key of the account to liquidateconst txSignature = await crossClient.liquidate(Asset.SOL, liquidatedAccountPubkey, 1000); // Liquidate 1 SOLconsole.log("Position liquidated. Transaction signature:", txSignature);
Close All Positions
closeAllPositions(orderPrices: Map<Asset, number>): Promise<string[]>
Closes all open positions using market orders.
Description
The closeAllPositions()
method allows you to close all open positions for all assets using market orders. You need to provide the current market prices for each asset.
Parameters
orderPrices
- (Map<Asset, number>) Required.
- Map of assets to their respective market prices for closing.
Return
- (Promise<string[]>) A promise that resolves to an array of transaction signatures.
Example
import { Asset } from '@zetamarkets/sdk';
const orderPrices = new Map<Asset, number>([ [Asset.SOL, 20000000], // $20 for SOL [Asset.BTC, 30000000000] // $30,000 for BTC]);
const txSignatures = await crossClient.closeAllPositions(orderPrices);console.log("All positions closed. Transaction signatures:", txSignatures);
Account Information and State
Get Account State
getAccountState(): types.CrossMarginAccountState
Retrieves the current state of the cross-margin account.
Description
The getAccountState()
method returns the current state of the cross-margin account, including balance, equity, available balance, and risk metrics.
Return
- (types.CrossMarginAccountState) The current state of the cross-margin account.
Example
const accountState = crossClient.getAccountState();console.log("Account State:", accountState);
Update State
updateState(fetch?: boolean, force?: boolean): Promise<number>
Updates the client’s state with the latest information from the blockchain.
Description
The updateState()
method updates the client’s local state with the latest information from the blockchain. This includes account balances, positions, orders, and other relevant data.
Parameters
-
fetch
- (boolean) Optional.
- Whether to fetch new data from the blockchain.
- Default:
true
-
force
- (boolean) Optional.
- Whether to force an update even if one is in progress.
- Default:
false
Return
- (Promise
) A promise that resolves to the fetch slot number.
Example
const fetchSlot = await crossClient.updateState();console.log("State updated. Fetch slot:", fetchSlot);
Get Trigger Order
getTriggerOrder(triggerOrderBit: number): types.TriggerOrder
Retrieves a specific trigger order by its bit.
Description
The getTriggerOrder()
method returns the details of a specific trigger order identified by its trigger order bit.
Parameters
triggerOrderBit
- (number) Required.
- The bit identifying the trigger order.
Return
- (types.TriggerOrder) The trigger order details.
Example
const triggerOrder = crossClient.getTriggerOrder(0);console.log("Trigger Order:", triggerOrder);
Get Trigger Orders
getTriggerOrders(asset: Asset): types.TriggerOrder[]
Retrieves all trigger orders for a specific asset.
Description
The getTriggerOrders()
method returns an array of all trigger orders for the specified asset.
Parameters
asset
- (Asset) Required.
- The asset to get trigger orders for.
Return
- (types.TriggerOrder[]) An array of trigger orders for the specified asset.
Example
import { Asset } from '@zetamarkets/sdk';
const triggerOrders = crossClient.getTriggerOrders(Asset.SOL);console.log("SOL Trigger Orders:", triggerOrders);
Get Orders
getOrders(asset: Asset): types.Order[]
Retrieves all active orders for a specific asset.
Description
The getOrders()
method returns an array of all active orders for the specified asset.
Parameters
asset
- (Asset) Required.
- The asset to get orders for.
Return
- (types.Order[]) An array of active orders for the specified asset.
Example
import { Asset } from '@zetamarkets/sdk';
const orders = crossClient.getOrders(Asset.SOL);console.log("SOL Orders:", orders);
Get Positions
getPositions(asset: Asset): types.Position[]
Retrieves all positions for a specific asset.
Description
The getPositions()
method returns an array of all positions for the specified asset.
Parameters
asset
- (Asset) Required.
- The asset to get positions for.
Return
- (types.Position[]) An array of positions for the specified asset.
Example
import { Asset } from '@zetamarkets/sdk';
const positions = crossClient.getPositions(Asset.SOL);console.log("SOL Positions:", positions);
Open Orders Management
Initialize Open Orders Account
initializeOpenOrdersAccount(asset: Asset): Promise<TransactionSignature>
Initializes a user open orders account for a given market.
Description
The initializeOpenOrdersAccount()
method creates an open orders account for the specified asset. This is typically handled automatically when placing an order, but can be used to initialize the account independently.
Parameters
asset
- (Asset) Required.
- The asset for which to initialize the open orders account.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset } from '@zetamarkets/sdk';
const txSignature = await crossClient.initializeOpenOrdersAccount(Asset.SOL);console.log("Open orders account initialized. Transaction signature:", txSignature);
Close Open Orders Account
closeOpenOrdersAccount(asset: Asset): Promise<TransactionSignature>
Closes a user open orders account for a given market.
Description
The closeOpenOrdersAccount()
method closes the open orders account for the specified asset. This can only be done if there are no active orders for the asset.
Parameters
asset
- (Asset) Required.
- The asset for which to close the open orders account.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset } from '@zetamarkets/sdk';
const txSignature = await crossClient.closeOpenOrdersAccount(Asset.SOL);console.log("Open orders account closed. Transaction signature:", txSignature);
Close Multiple Open Orders Accounts
closeMultipleOpenOrdersAccount(assets: Asset[]): Promise<TransactionSignature[]>
Closes multiple user open orders accounts for a given set of markets.
Description
The closeMultipleOpenOrdersAccount()
method closes the open orders accounts for multiple specified assets in a single transaction. This can only be done if there are no active orders for any of the assets.
Parameters
assets
- (Asset[]) Required.
- An array of assets for which to close the open orders accounts.
Return
- (Promise<TransactionSignature[]>) A promise that resolves to an array of transaction signatures.
Example
import { Asset } from '@zetamarkets/sdk';
const txSignatures = await crossClient.closeMultipleOpenOrdersAccount([Asset.SOL, Asset.BTC]);console.log("Multiple open orders accounts closed. Transaction signatures:", txSignatures);
Force Operations (Admin/Liquidator Functions)
Force Cancel Order by Order ID
forceCancelOrderByOrderId(asset: Asset, marginAccountToCancel: PublicKey, orderId: BN, side: types.Side): Promise<TransactionSignature>
Forcefully cancels an order on another user’s account by order ID.
Description
The forceCancelOrderByOrderId()
method allows authorized users (such as liquidators or admins) to cancel a specific order on another user’s account. This function is typically used in risk management scenarios.
Parameters
-
asset
- (Asset) Required.
- The asset of the order to cancel.
-
marginAccountToCancel
- (PublicKey) Required.
- The public key of the margin account containing the order to cancel.
-
orderId
- (BN) Required.
- The ID of the order to cancel.
-
side
- (types.Side) Required.
- The side of the order (BID or ASK).
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset, types } from '@zetamarkets/sdk';import { PublicKey } from '@solana/web3.js';import { BN } from '@zetamarkets/anchor';
const marginAccountToCancel = new PublicKey("...");const orderId = new BN("123456");
const txSignature = await crossClient.forceCancelOrderByOrderId( Asset.SOL, marginAccountToCancel, orderId, types.Side.BID);console.log("Order forcefully cancelled. Transaction signature:", txSignature);
Force Cancel Orders
forceCancelOrders(asset: Asset, marginAccountToCancel: PublicKey): Promise<TransactionSignature>
Forcefully cancels all orders on another user’s account for a specific asset.
Description
The forceCancelOrders()
method allows authorized users (such as liquidators or admins) to cancel all orders for a specific asset on another user’s account. This function is typically used in risk management scenarios.
Parameters
-
asset
- (Asset) Required.
- The asset for which to cancel all orders.
-
marginAccountToCancel
- (PublicKey) Required.
- The public key of the margin account containing the orders to cancel.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset } from '@zetamarkets/sdk';import { PublicKey } from '@solana/web3.js';
const marginAccountToCancel = new PublicKey("...");
const txSignature = await crossClient.forceCancelOrders(Asset.SOL, marginAccountToCancel);console.log("All orders forcefully cancelled. Transaction signature:", txSignature);
Utility Functions
Find Available Trigger Order Bit
findAvailableTriggerOrderBit(startIndex?: number): number
Finds the next available bit to store a trigger order.
Description
The findAvailableTriggerOrderBit()
method searches for the next available bit that can be used to store a trigger order. It starts searching from the provided start index or from 0 if no start index is provided.
Parameters
startIndex
- (number) Optional.
- The index from which to start searching (0 to 127).
- Default:
0
Return
- (number) The first available bit (0 to 127).
Example
const availableBit = crossClient.findAvailableTriggerOrderBit();console.log("Available trigger order bit:", availableBit);
Close (Cleanup)
close(): Promise<void>
Closes all WebSocket subscriptions and intervals.
Description
The close()
method should be called when you’re done using the CrossClient instance. It cleans up resources by closing WebSocket subscriptions and clearing any intervals.
Return
- (Promise
) A promise that resolves when the cleanup is complete.
Example
await crossClient.close();console.log("CrossClient closed and cleaned up.");
Referral and Community Functions
Initialize Referrer Account
initializeReferrerAccount(id: string): Promise<TransactionSignature>
Initializes a referrer account for the user.
Description
The initializeReferrerAccount()
method creates a referrer account for the user, allowing them to participate in referral programs.
Parameters
id
- (string) Required.
- The referrer ID to use.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const referrerId = "MYREFID123";const txSignature = await crossClient.initializeReferrerAccount(referrerId);console.log("Referrer account initialized. Transaction signature:", txSignature);
Remake Referrer Accounts
remakeReferrerAccounts(id: string): Promise<TransactionSignature>
Remakes the referrer accounts for the user with a new ID.
Description
The remakeReferrerAccounts()
method closes existing referrer accounts (if any) and creates new ones with the provided ID.
Parameters
id
- (string) Required.
- The new referrer ID to use.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const newReferrerId = "NEWREFID456";const txSignature = await crossClient.remakeReferrerAccounts(newReferrerId);console.log("Referrer accounts remade. Transaction signature:", txSignature);
Close Referrer Accounts
closeReferrerAccounts(): Promise<TransactionSignature>
Closes the user’s referrer accounts.
Description
The closeReferrerAccounts()
method closes all referrer accounts associated with the user.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
const txSignature = await crossClient.closeReferrerAccounts();console.log("Referrer accounts closed. Transaction signature:", txSignature);
Choose Airdrop Community
chooseAirdropCommunity(community: types.AirdropCommunity): Promise<TransactionSignature>
Selects an airdrop community for the user.
Description
The chooseAirdropCommunity()
method allows the user to select an airdrop community, which may affect their eligibility for certain airdrops or rewards.
Parameters
community
- (types.AirdropCommunity) Required.
- The airdrop community to select.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { types } from '@zetamarkets/sdk';
const txSignature = await crossClient.chooseAirdropCommunity(types.AirdropCommunity.JUP);console.log("Airdrop community selected. Transaction signature:", txSignature);
Advanced Operations
Edit Delegated Pubkey
editDelegatedPubkey(delegatedPubkey: PublicKey): Promise<TransactionSignature>
Edits the delegated public key for the cross-margin account.
Description
The editDelegatedPubkey()
method allows the user to change the delegated public key associated with their cross-margin account. This can be used to grant or revoke trading permissions to another public key.
Parameters
delegatedPubkey
- (PublicKey) Required.
- The new delegated public key.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { PublicKey } from '@solana/web3.js';
const newDelegatedPubkey = new PublicKey("...");const txSignature = await crossClient.editDelegatedPubkey(newDelegatedPubkey);console.log("Delegated pubkey updated. Transaction signature:", txSignature);
Migrate to Cross Margin Account
migrateToCrossMarginAccount(referrer?: PublicKey): Promise<TransactionSignature[]>
Migrates the user’s existing margin accounts to a cross-margin account.
Description
The migrateToCrossMarginAccount()
method migrates the user’s existing individual margin accounts to a unified cross-margin account. This can potentially provide better capital efficiency.
Parameters
referrer
- (PublicKey) Optional.
- The public key of the referrer for the new cross-margin account.
- Default:
undefined
Return
- (Promise<TransactionSignature[]>) A promise that resolves to an array of transaction signatures.
Example
import { PublicKey } from '@solana/web3.js';
const referrerPubkey = new PublicKey("...");const txSignatures = await crossClient.migrateToCrossMarginAccount(referrerPubkey);console.log("Migration to cross-margin account complete. Transaction signatures:", txSignatures);
Multi-Order Operations
Cancel Multiple Orders
cancelMultipleOrders(cancelArguments: types.CancelArgs[]): Promise<TransactionSignature[]>
Cancels multiple orders in a single transaction.
Description
The cancelMultipleOrders()
method allows you to cancel multiple orders across different assets in a single transaction.
Parameters
cancelArguments
- (types.CancelArgs[]) Required.
- An array of cancel arguments, each specifying an order to cancel.
Return
- (Promise<TransactionSignature[]>) A promise that resolves to an array of transaction signatures.
Example
import { Asset, types } from '@zetamarkets/sdk';import { PublicKey } from '@solana/web3.js';import { BN } from '@zetamarkets/anchor';
const cancelArgs: types.CancelArgs[] = [ { asset: Asset.SOL, market: new PublicKey("..."), orderId: new BN("123456"), cancelSide: types.Side.BID }, { asset: Asset.BTC, market: new PublicKey("..."), orderId: new BN("789012"), cancelSide: types.Side.ASK }];
const txSignatures = await crossClient.cancelMultipleOrders(cancelArgs);console.log("Multiple orders cancelled. Transaction signatures:", txSignatures);
Cancel Multiple Orders No Error
cancelMultipleOrdersNoError(cancelArguments: types.CancelArgs[]): Promise<TransactionSignature[]>
Cancels multiple orders in a single transaction, ignoring errors.
Description
The cancelMultipleOrdersNoError()
method is similar to cancelMultipleOrders()
, but it continues to process cancellations even if some orders fail to cancel. This can be useful in situations where you want to ensure as many orders as possible are cancelled, even if some cancellations fail.
Parameters
cancelArguments
- (types.CancelArgs[]) Required.
- An array of cancel arguments, each specifying an order to cancel.
Return
- (Promise<TransactionSignature[]>) A promise that resolves to an array of transaction signatures.
Example
import { Asset, types } from '@zetamarkets/sdk';import { PublicKey } from '@solana/web3.js';import { BN } from '@zetamarkets/anchor';
const cancelArgs: types.CancelArgs[] = [ { asset: Asset.SOL, market: new PublicKey("..."), orderId: new BN("123456"), cancelSide: types.Side.BID }, { asset: Asset.BTC, market: new PublicKey("..."), orderId: new BN("789012"), cancelSide: types.Side.ASK }];
const txSignatures = await crossClient.cancelMultipleOrdersNoError(cancelArgs);console.log("Multiple orders cancelled (ignoring errors). Transaction signatures:", txSignatures);
Market Operations
Cancel Market Orders
cancelMarketOrders(asset: Asset): Promise<TransactionSignature>
Cancels all market orders for a specific asset.
Description
The cancelMarketOrders()
method cancels all market orders for the specified asset.
Parameters
asset
- (Asset) Required.
- The asset for which to cancel market orders.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset } from '@zetamarkets/sdk';
const txSignature = await crossClient.cancelMarketOrders(Asset.SOL);console.log("All market orders for SOL cancelled. Transaction signature:", txSignature);
Cancel All Market Orders
cancelAllMarketOrders(): Promise<TransactionSignature[]>
Cancels all market orders for all assets.
Description
The cancelAllMarketOrders()
method cancels all market orders across all assets.
Return
- (Promise<TransactionSignature[]>) A promise that resolves to an array of transaction signatures.
Example
const txSignatures = await crossClient.cancelAllMarketOrders();console.log("All market orders cancelled. Transaction signatures:", txSignatures);
Trigger Order Management
Edit Timestamp Trigger Order
editTimestampTriggerOrder( orderIndex: number, newOrderPrice: number, newTriggerTime: anchor.BN, newSize: number, newSide: types.Side, newOrderType: types.OrderType, newOptions?: types.TriggerOrderOptions): Promise<TransactionSignature>
Edits an existing timestamp trigger order.
Description
The editTimestampTriggerOrder()
method allows you to modify the parameters of an existing timestamp trigger order.
Parameters
-
orderIndex
- (number) Required.
- The index of the trigger order to edit.
-
newOrderPrice
- (number) Required.
- The new order price (in native units, 6 decimal places).
-
newTriggerTime
- (anchor.BN) Required.
- The new trigger timestamp.
-
newSize
- (number) Required.
- The new order size (in native units, 3 decimal places).
-
newSide
- (types.Side) Required.
- The new order side (BID or ASK).
-
newOrderType
- (types.OrderType) Required.
- The new order type.
-
newOptions
- (types.TriggerOrderOptions) Optional.
- New trigger order options.
- Default:
types.defaultTriggerOrderOptions()
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { types } from '@zetamarkets/sdk';import { BN } from '@zetamarkets/anchor';
const txSignature = await crossClient.editTimestampTriggerOrder( 0, // orderIndex 21000000, // newOrderPrice ($21) new BN(Math.floor(Date.now() / 1000) + 3600), // newTriggerTime (1 hour from now) 1000, // newSize (1 SOL) types.Side.BID, types.OrderType.LIMIT);console.log("Timestamp trigger order edited. Transaction signature:", txSignature);
Edit Price Trigger Order
editPriceTriggerOrder( orderIndex: number, newOrderPrice: number, newTriggerPrice: number, newSize: number, newSide: types.Side, newDirection: types.TriggerDirection, newOrderType: types.OrderType, newOptions?: types.TriggerOrderOptions): Promise<TransactionSignature>
Edits an existing price trigger order.
Description
The editPriceTriggerOrder()
method allows you to modify the parameters of an existing price trigger order.
Parameters
-
orderIndex
- (number) Required.
- The index of the trigger order to edit.
-
newOrderPrice
- (number) Required.
- The new order price (in native units, 6 decimal places).
-
newTriggerPrice
- (number) Required.
- The new trigger price (in native units, 6 decimal places).
-
newSize
- (number) Required.
- The new order size (in native units, 3 decimal places).
-
newSide
- (types.Side) Required.
- The new order side (BID or ASK).
-
newDirection
- (types.TriggerDirection) Required.
- The new trigger direction.
-
newOrderType
- (types.OrderType) Required.
- The new order type.
-
newOptions
- (types.TriggerOrderOptions) Optional.
- New trigger order options.
- Default:
types.defaultTriggerOrderOptions()
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { types } from '@zetamarkets/sdk';
const txSignature = await crossClient.editPriceTriggerOrder( 0, // orderIndex 21000000, // newOrderPrice ($21) 20000000, // newTriggerPrice ($20) 1000, // newSize (1 SOL) types.Side.BID, types.TriggerDirection.GREATERTHANOREQUAL, types.OrderType.LIMIT);console.log("Price trigger order edited. Transaction signature:", txSignature);
Take Trigger Order
takeTriggerOrder( orderIndex: number, asset: Asset, orderMarginAccount: PublicKey): Promise<TransactionSignature>
Executes a trigger order.
Description
The takeTriggerOrder()
method allows you to manually execute a trigger order. This is typically used by keepers or in testing scenarios.
Parameters
-
orderIndex
- (number) Required.
- The index of the trigger order to take.
-
asset
- (Asset) Required.
- The asset of the trigger order.
-
orderMarginAccount
- (PublicKey) Required.
- The public key of the margin account that owns the trigger order.
Return
- (Promise
) A promise that resolves to the transaction signature.
Example
import { Asset } from '@zetamarkets/sdk';import { PublicKey } from '@solana/web3.js';
const orderMarginAccount = new PublicKey("...");const txSignature = await crossClient.takeTriggerOrder(0, Asset.SOL, orderMarginAccount);console.log("Trigger order taken. Transaction signature:", txSignature);
Instruction Creation (for Advanced Usage)
Create Cancel Order No Error Instruction
createCancelOrderNoErrorInstruction( asset: Asset, orderId: BN, side: types.Side): TransactionInstruction
Creates a cancel order instruction that doesn’t throw an error if the order doesn’t exist.
Description
The createCancelOrderNoErrorInstruction()
method creates a Solana transaction instruction to cancel an order without throwing an error if the order doesn’t exist. This is useful for creating more complex transactions.
Parameters
-
asset
- (Asset) Required.
- The asset of the order to cancel.
-
orderId
- (BN) Required.
- The ID of the order to cancel.
-
side
- (types.Side) Required.
- The side of the order (BID or ASK).
Return
- (TransactionInstruction) A Solana transaction instruction.
Example
import { Asset, types } from '@zetamarkets/sdk';import { BN } from '@zetamarkets/anchor';
const cancelInstruction = crossClient.createCancelOrderNoErrorInstruction( Asset.SOL, new BN("123456"), types.Side.BID);// You can now add this instruction to a transaction
Create Cancel All Market Orders Instruction
createCancelAllMarketOrdersInstruction(asset: Asset): TransactionInstruction
Creates an instruction to cancel all market orders for a specific asset.
Description
The createCancelAllMarketOrdersInstruction()
method creates a Solana transaction instruction to cancel all market orders for a specific asset. This is useful for creating more complex transactions.
Parameters
asset
- (Asset) Required.
- The asset for which to cancel all market orders.
Return
- (TransactionInstruction) A Solana transaction instruction.
Example
import { Asset } from '@zetamarkets/sdk';
const cancelAllInstruction = crossClient.createCancelAllMarketOrdersInstruction(Asset.SOL);// You can now add this instruction to a transaction
Create Place Perp Order Instruction
createPlacePerpOrderInstruction( asset: Asset, price: number, size: number, side: types.Side, options?: types.OrderOptions): TransactionInstruction
Creates an instruction to place a perpetual order.
Description
The createPlacePerpOrderInstruction()
method creates a Solana transaction instruction to place a perpetual order. This is useful for creating more complex transactions.
Parameters
-
asset
- (Asset) Required.
- The asset to trade.
-
price
- (number) Required.
- The order price (in native units, 6 decimal places).
-
size
- (number) Required.
- The order size (in native units, 3 decimal places).
-
side
- (types.Side) Required.
- The order side (BID or ASK).
-
options
- (types.OrderOptions) Optional.
- Order options.
- Default:
types.defaultOrderOptions()
Return
- (TransactionInstruction) A Solana transaction instruction.
Example
import { Asset, types } from '@zetamarkets/sdk';
const placeOrderInstruction = crossClient.createPlacePerpOrderInstruction( Asset.SOL, 20000000, // $20 price 1000, // 1 SOL size types.Side.BID);// You can now add this instruction to a transaction
Create Place Multi Order Instruction
createPlaceMultiOrderInstruction( asset: Asset, bids: types.PlaceMultiOrderArg[], asks: types.PlaceMultiOrderArg[], orderType: types.OrderType): TransactionInstruction
Creates an instruction to place multiple orders for a specific asset.
Description
The createPlaceMultiOrderInstruction()
method creates a Solana transaction instruction to place multiple orders for a specific asset in a single instruction. This is useful for creating more complex transactions and for placing multiple orders efficiently.
Parameters
-
asset
- (Asset) Required.
- The asset to trade.
-
bids
- (types.PlaceMultiOrderArg[]) Required.
- An array of bid order arguments.
-
asks
- (types.PlaceMultiOrderArg[]) Required.
- An array of ask order arguments.
-
orderType
- (types.OrderType) Required.
- The type of orders to place (must be POSTONLY, POSTONLYSLIDE, or POSTONLYFRONT).
Return
- (TransactionInstruction) A Solana transaction instruction.
Example
import { Asset, types } from '@zetamarkets/sdk';
const bids: types.PlaceMultiOrderArg[] = [ { price: 19000000, size: 1000, tifOptions: {} }, { price: 18000000, size: 2000, tifOptions: {} }];const asks: types.PlaceMultiOrderArg[] = [ { price: 21000000, size: 1000, tifOptions: {} }, { price: 22000000, size: 2000, tifOptions: {} }];
const placeMultiOrderInstruction = crossClient.createPlaceMultiOrderInstruction( Asset.SOL, bids, asks, types.OrderType.POSTONLY);// You can now add this instruction to a transaction
Conclusion
This documentation covers the main functionalities of the CrossClient class in the Zeta Markets SDK. It provides detailed information on how to initialize the client, manage accounts, place and cancel orders, handle positions, and perform various other operations related to trading on the Zeta Markets protocol.
Remember to always check the latest version of the SDK for any updates or changes to the API. For more advanced usage and detailed information about the Zeta Markets protocol, please refer to the official Zeta Markets documentation and developer resources.