Skip to content

A simple example demonstrating how to use the Kanalabs Perps SDK for interacting with perpetual trading features.

Notifications You must be signed in to change notification settings

kanalabs/perps-sdk-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 

Repository files navigation

πŸŒ€ Perpetual Public SDK

A developer-friendly SDK to interact with the Perpetual Trading Platform. Built with TypeScript, this SDK allows easy integration with core functionalities like placing orders, fetching market data, viewing positions, and more.

πŸ“¦ Installation

Install the Perpetual SDK and required dependencies:

npm install @kanalabs/perpetual-sdk
npm install dotenv
npm install @aptos-labs/ts-sdk

Testnet Supported Markets

Asset Market ID Description
APT/USDC 1338 Aptos-based trading market
BTC/USDC 1339 Bitcoin-based trading market
ETH/USDC 1340 Ethereum-based trading market
SOL/USDC 2387 Solana-based trading market

Mainnet Supported Markets

Asset Market ID Description
APT/USDC 14 Aptos-based trading market
BTC/USDC 15 Bitcoin-based trading market
ETH/USDC 16 Ethereum-based trading market
SOL/USDC 31 Solana-based trading market

βš™οΈ Supported Functionalities

Function Name Description
usdtTestnetFaucet Request test USDT from the faucet on testnet.
getMarketView Fetch detailed market view information.
deposit Deposit USDT into a specific perpetual market.
withdrawSpecificMarket Withdraw USDT from a specific market.
withdrawMultipleMarkets Withdraw USDT from multiple markets in a single call.
placeLimitOrder Place a limit order on the perpetual trading platform.
placeMarketOrder Execute a market order instantly at the current market price.
getProfileBalanceSnpashot Retrieve a snapshot of the user’s balance and profile information.
cancelMultipleOrders Cancel multiple open orders using order IDs.
placeMultipleOrders Place multiple orders in one transaction.
cancelAndPlaceMultipleOrders Cancel existing orders and place new ones in a single transaction.
getOpenOrders Fetch all active open orders for the user.
getPositions View current open positions in the perpetual markets.
updateTakeProfit Update the take profit value for an open position.
updateStopLoss Update the stop loss value for an open position.
getTradeHistory Retrieve order history for the user.
getOrderHistory Retrieve trade history for the user.
getDepositAndWithdrawHistory Retrieve deposit and withdraw history for the user.
addMargin Add margin (collateral) to an open position in a specific market.
collapsePosition Collapse (close and withdraw) an open position in a specific market.

πŸ”§ SDK Initialization

  1. Import and Initialize
import { PerpsMarkets } from '@kanalabs/perpetual-sdk';

const marketIds = [1338, 1339, 1340, 2387];  // You can give all the market IDs you need to initialize
const perpsMarketsInstance = new PerpsMarkets({
  network: process.env.PERPS_APTOS_NETWORK!,
  nodeurl: process.env.PERPS_APTOS_INDEXER_NODE_URL!,
  apikey: process.env.PERPS_APTOS_INDEXER_API_KEY!
});
await perpsMarketsInstance.init(marketIds);
  1. Aptos client setup
const clientConfig: ClientConfig = {
  API_KEY: process.env.PERPS_APTOS_INDEXER_API_KEY as string,
};
const config = new AptosConfig({
  fullnode: process.env.PERPS_APTOS_INDEXER_NODE_URL,
  network: process.env.PERPS_APTOS_NETWORK as Network,
  clientConfig
});
const aptos = new Aptos(config);
  1. .env File Configuration
PERPS_APTOS_NETWORK = your_networ_here  // testnet or mainnet
PERPS_APTOS_INDEXER_NODE_URL = https://your-aptos-indexer-node-url
PERPS_APTOS_INDEXER_API_KEY = https://your-aptos-indexer-api-key
APTOS_PRIVATEKEY = your_private_key
  1. Wallet setup
const formattedPrivateKey = PrivateKey.formatPrivateKey(
  process.env.APTOS_PRIVATEKEY || '',
  "ed25519" as PrivateKeyVariants
);
const account = Account.fromPrivateKey({
  privateKey: new Ed25519PrivateKey(formattedPrivateKey),
});

🧠 Function Types

This SDK provides two types of functions:

πŸ” Entry Functions – These return a transaction payload that must be signed and submitted to the Aptos blockchain.

πŸ‘οΈ View Functions – These internally call aptos.view(...) and return the actual on-chain data as a response.

πŸ“Œ How to Use Entry & View Function Payloads Before diving into each function’s parameters and responses, it's important to understand how to use the payloads returned by both entry and view functions.

πŸ” For Entry Functions

All entry functions return a transaction payload. You must use this payload to build, sign, and submit a transaction to the Aptos blockchain.

Here’s the general flow:

const payload = await perpsMarketsInstance.functionName(...args); // returns { data: TransactionPayload }

const transactionPayload = await aptos.transaction.build.simple({
  sender: account.accountAddress,
  data: payload.data
});

const committedTxn = await aptos.transaction.signAndSubmitTransaction({
  transaction: transactionPayload,
  signer: account,
});

const response = await aptos.waitForTransaction({
  transactionHash: committedTxn.hash,
});
console.log("response", response.success);

πŸ‘οΈ For View Functions

All view functions in the SDK automatically handle the call to aptos.view(...) internally. That means you do not need to call aptos.view() yourself β€” simply call the function and get the result directly.

Example:

const response = await perpsMarketsInstance.functionName(...args); // returns { function: ..., type_arguments: ..., arguments: [...] }

πŸ” Let’s Explore with Full Code Examples Before we dive into the full list of supported functions, arguments, and response structures, let’s walk through:

--> πŸ” One Entry Function Example

--> πŸ‘οΈ One View Function Example

βœ… Full Example: Entry Function – Request USDT Faucet

import dotenv from "dotenv";
import { PerpsMarkets } from "@kanalabs/perpetual-sdk";
import { Network } from "@aptos-labs/ts-sdk";
dotenv.config();

async function main(): Promise<void> {
    const amount = 100;
    const marketIds = [1338, 1339];  // You can give all the market IDs you need to initialize
    const perpsMarketsInstance = new PerpsMarkets({
      network: process.env.PERPS_APTOS_NETWORK!,
      nodeurl: process.env.PERPS_APTOS_INDEXER_NODE_URL!,
      apikey: process.env.PERPS_APTOS_INDEXER_API_KEY!
    });
    await perpsMarketsInstance.init(marketIds);
    const payload = await perpsMarketsInstance.usdtTestnetFaucet(amount);
    const transactionPayload = await aptos.transaction.build.simple({
        sender: account.accountAddress,
        data: payload.data
    });
    const committedTxn = await aptos.transaction.signAndSubmitTransaction({
        transaction: transactionPayload,
        signer: account,
    });
    console.log(`Submitted transaction: ${committedTxn.hash}`);
    const response = await aptos.waitForTransaction({
        transactionHash: committedTxn.hash,
    });
    console.log("response", response.success);
}


main().catch(error => {
    console.error('An error occurred:', error);
});

πŸ‘οΈ Full Example: View Function – Fetch Market Info

import dotenv from "dotenv";
import { PerpsMarkets } from "@kanalabs/perpetual-sdk";
import { Network } from "@aptos-labs/ts-sdk";
dotenv.config();

async function main(): Promise<void> {
    const marketId = 1338;
    const perpsMarketsInstance = new PerpsMarkets({
      network: process.env.PERPS_APTOS_NETWORK!,
      nodeurl: process.env.PERPS_APTOS_INDEXER_NODE_URL!,
      apikey: process.env.PERPS_APTOS_INDEXER_API_KEY!
     });
    await perpsMarketsInstance.init(marketIds);
    const getMarketInfo = await perpsMarketsInstance.getMarketView(marketId);
    console.log("getMarketInfo: ", getMarketInfo);
}

main().catch(error => {
    console.error('An error occurred:', error);
});

πŸ“š What’s Next? Up next, explore:

✨ Function Parameters – A breakdown of arguments for each function

πŸ“€ Response Format – Sample outputs and fields explained

πŸ’‘ Usage Tips – Best practices and common use cases

πŸ’‘ Important Note:

Please ensure that the parameters for amount, size, and price are provided in human-readable formats (e.g., as simple numbers with decimals where applicable). These values will be automatically converted internally to the required format.

--> Amount: If you provide 100, it will be internally converted to 100000000 (multiplied by 10^6).

--> Size: If you provide 7 for size, it will be internally converted to 7000.

--> Price: If you provide 5.678 for price, it will be internally converted to 5678.

This ensures that users can input values in a more understandable format, and the system will handle the necessary conversions automatically.

πŸš€ Let’s See One by One: Entry & View Functions

1. Entry Function – usdtTestnetFaucet:

Param Type Required Description
amount number βœ… Amount of USDT to request
const amount = 100;

const payload = await perpsMarketsInstance.usdtTestnetFaucet(amount);

2. Entry Function – deposit:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Address of the user
amount number βœ… Amount of USDT to deposit (in USDT)

πŸ“€ Example Usage

const userAddress = "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770";
const amount = 10;

const payload = await perpsMarketsInstance.deposit(userAddress, amount);

3. Entry Function – withdrawSpecificMarket:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Address of the user
marketId number βœ… Market ID from which to withdraw
amount number βœ… Amount of USDT to withdraw (in USDT)

πŸ“€ Example Usage

const marketId = 624;
const userAddress = "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770";
const amount = 10;

const payload = await perpsMarketsInstance.withdrawSpecificMarket(userAddress, marketId, amount);

4. Entry Function – withdrawMultipleMarkets:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Address of the user
marketIds number[] βœ… List of Market IDs from which to withdraw
amount number βœ… Amount of USDT to withdraw from each (in USDT)

πŸ“€ Example Usage

const amount = 10;
const marketIds = [624, 639, 640];
const userAddress = "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770";

const payload = await perpsMarketsInstance.withdrawMultipleMarkets(userAddress, marketIds, amount);

5. Entry Function – placeLimitOrder:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market to place the order in
tradeSide boolean βœ… true = Long, false = Short
direction boolean βœ… false = Buy, true = Sell
size number βœ… Size of the order in base asset (e.g., APT)
price number βœ… Limit price of the order (e.g., in USDC)
leverage number βœ… Leverage for the order (min: 1, max: 20)
takeProfit number ❌ (Optional) Price at which to take profit
stopLoss number ❌ (Optional) Price at which to stop loss
restriction number ❌ (Optional) Type of order restriction:
0 – NO*RESTRICTION *(default)_: Taker then maker
1 – FILL_OR_ABORT: Only fill, abort if posts as maker
3 – POST_OR_ABORT: Only post, abort if fills as taker

πŸ“€ Example Usage

const marketId = 624;
const tradeSide = true; // Long
const direction = false; // Buy
const size = 1; // 1 APT
const price = 5.678; // 5.678 USDC
const leverage = 2;

const payload = await perpsMarketsInstance.placeLimitOrder({
        marketId, tradeSide, direction, size, price, leverage, takeProfit
});

6. Entry Function – placeMarketOrder:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market to place the order in
tradeSide boolean βœ… true = Long, false = Short
direction boolean βœ… false = Buy, true = Sell
size number βœ… Size of the order in base asset (e.g., APT)
leverage number βœ… Leverage for the order (min: 1, max: 20)
takeProfit number ❌ (Optional) Price at which to take profit
stopLoss number ❌ (Optional) Price at which to stop loss

πŸ“€ Example Usage

const marketId = 501;
const tradeSide = false; // Short
const direction = false; // Sell
const size = 1; // 2 APT
const leverage = 2;
const takeProfit = 6.0; // Optional: Take profit price
const stopLoss = 4.0; // Optional: Stop loss price

const payload = await perpsMarketsInstance.placeMarketOrder({
        marketId, tradeSide, direction, size, leverage
});

7. Entry Function – cancelMultipleOrders:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market to cancel orders from
cancelOrderIds string[] βœ… List of Order IDs to cancel
orderSides boolean[] βœ… List of order sides: true for Long, false for Short

πŸ“€ Example Usage

const marketId = 624;
const cancelOrderIds = ['516508974814240709142']; // Order IDs to cancel
const orderSides = [true]; // `true` = Long, `false` = Short

const payload = await perpsMarketsInstance.cancelMultipleOrders({
        marketId, cancelOrderIds, orderSides
});

8. Entry Function – placeMultipleOrders:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market to place the orders in
orderTypes boolean[] βœ… List of order types (true for limit, false for market)
tradeSides boolean[] βœ… List of trade sides: true for Long, false for Short
directions boolean[] βœ… List of directions: false for open, true for close
sizes number[] βœ… List of sizes for the orders (in base asset, e.g., APT)
prices number[] βœ… List of prices for the limit orders (in USDC or other base currency)
leverages number[] βœ… List of leverages for each order (min: 1, max: 20)
restrictions number[] ❌ (Optional) List of restrictions for each order:
0 for NO_RESTRICTION, 1 for FILL_OR_ABORT, 3 for POST_OR_ABORT
takeProfits number[] ❌ (Optional) List of take profit prices for each order
stopLosses number[] ❌ (Optional) List of stop loss prices for each order

πŸ“€ Example Usage

const marketId = 624;
const orderTypes = [true, true]; // Limit orders
const tradeSides = [true, true]; // Long positions
const directions = [false, false]; // Open positions
const sizes = [1.5, 2.7]; // Size of orders in APT
const prices = [4.5, 4.326]; // Prices in USDC
const leverages = [2, 2]; // Leverage for each order
const restrictions = [0, 1]; // Optional: Restrictions for each order (e.g., NO_RESTRICTION or FILL_OR_ABORT)
const takeProfits = [6.0, 5.5]; // Optional: Take profit prices for each order
const stopLosses = [3.5, 4.0]; // Optional: Stop loss prices for each order

const payload = await perpsMarketsInstance.placeMultipleOrders({
        marketId, orderTypes, tradeSides, directions, sizes, prices, leverages
});

9. Entry Function – cancelAndPlaceMultipleOrders:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market to place the orders in
cancelOrderIds string[] βœ… List of order IDs to cancel
orderSides boolean[] βœ… List of order sides: true for Long, false for Short
orderTypes boolean[] βœ… List of order types: true for limit, false for market
tradeSides boolean[] βœ… List of trade sides: true for Long, false for Short
directions boolean[] βœ… List of directions: false for open, true for close
sizes number[] βœ… List of sizes for the orders (e.g., APT)
prices number[] βœ… List of prices for the limit orders (e.g., in USDC or other base currency)
leverages number[] βœ… List of leverages for each order (min: 1, max: 20)
restrictions number[] ❌ (Optional) List of restrictions for each order:
0 for NO_RESTRICTION, 1 for FILL_OR_ABORT, 3 for POST_OR_ABORT
takeProfits number[] ❌ (Optional) List of take profit prices for each order
stopLosses number[] ❌ (Optional) List of stop loss prices for each order

πŸ“€ Example Usage

const marketId = 624;
const cancelOrderIds = ['387381766311158747540', '405828651113766719718'];
const orderSides = [true, true]; // Long positions
const orderTypes = [true, true]; // Limit orders
const tradeSides = [true, true]; // Long trades
const directions = [false, false]; // Open positions
const sizes = [1.5, 2.7]; // Size of orders in APT
const prices = [4.5, 4.326]; // Prices in USDC
const leverages = [2, 2]; // Leverage for each order
const restrictions = [0, 1]; // Optional: Restrictions for each order (e.g., NO_RESTRICTION or FILL_OR_ABORT)
const takeProfits = [6.0, 5.5]; // Optional: Take profit prices for each order
const stopLosses = [3.5, 4.0]; // Optional: Stop loss prices for each order

const payload = await perpsMarketsInstance.cancelAndPlaceMultipleOrders({
        marketId, cancelOrderIds, orderSides, orderTypes, tradeSides, directions, sizes, prices, leverages
});

10. Entry Function – updateTakeProfit:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market to update the take profit for
tradeSide boolean βœ… true = Long, false = Short
newTakeProfitPrice number βœ… New price at which to set the take profit

πŸ“€ Example Usage

const marketId = 624;
const tradeSide = true; // Long position
const newTakeProfitPrice = 6.012; // New take profit price in USDC

const payload = await perpsMarketsInstance.updateTakeProfit(marketId, tradeSide, newTakeProfitPrice);

11. Entry Function – updateStopLoss:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market to update the take profit for
tradeSide boolean βœ… true = Long, false = Short
newTakeProfitPrice number βœ… New price at which to set the take profit

πŸ“€ Example Usage

const marketId = 624;
const tradeSide = true; // Long position
const newStopLossPrice = 5.012; // New take profit price in USDC

const payload = await perpsMarketsInstance.updateTakeProfit(marketId, tradeSide, newStopLossPrice);

12. Entry Function – addMargin:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market where margin is being added
tradeSide boolean βœ… true = Long, false = Short
amount number βœ… Amount of USDT to add as margin (in USDT)

πŸ“€ Example Usage

const marketId = 624;
const tradeSide = true; // Long
const amount = 100; // Add 100 USDT margin

const payload = await perpsMarketsInstance.addMargin(marketId, tradeSide, amount);

13. Entry Function – collapsePosition:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the market to collapse

πŸ“€ Example Usage

const marketId = 624;

const payload = await perpsMarketsInstance.collapsePosition(marketId);

14. View Function – getMarketView:

πŸ” Parameters

Param Type Required Description
marketId number βœ… ID of the perpetual market to view

πŸ“€ Example Usage

const marketId = 624;

const response = await perpsMarketsInstance.getMarketView(marketId);

πŸ“˜ Response Description

Field Type Description
__variant__ string Variant version of the market view object (e.g., "V1")
base_decimals number Decimal precision of the base asset
base_name string Name of the trading pair (e.g., "APT-USD")
counter string Internal reference ID (can be used for mapping or internal tracking)
creator string Address of the user or contract that created the market
lot_size string Minimum tradeable unit size for the market
maintenance_margin string Minimum required margin to maintain a position (in basis points, e.g., 250 = 2.5%)
market_address string On-chain address of the market
market_id string Unique ID of the perpetual market
max_leverage string Maximum allowed leverage for trading in this market
max_lots string Maximum lot size allowed for a trade
min_lots string Minimum lot size required to place an order
quote_decimals number Decimal precision of the quote asset
quote_precision number Display precision for quote prices (number of decimal places shown)
tick_size string Minimum price increment allowed for order placement

**πŸ“‘ Example Response **

{
  "success": true,
  "message": "Market information fetched successfully",
  "data": [
    {
      "__variant__": "V1",
      "base_decimals": 8,
      "base_name": "APT-USD",
      "counter": "17",
      "creator": "0xb61d7b57333abf8ac036e752f19d0ba0c4baa5404db1cbf868c57dac3628f2bf",
      "lot_size": "100000",
      "maintenance_margin": "250",
      "market_address": "0xfd8d58fdd05dd9d0442a9d555a4f8ed310112eb7d1c297307038a650136e207b",
      "market_id": "501",
      "max_leverage": "20",
      "max_lots": "150000000",
      "min_lots": "500",
      "quote_decimals": 6,
      "quote_precision": 3,
      "tick_size": "1"
    }
  ]
}

15. View Function – getOpenOrders:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Address of the user
marketId number βœ… ID of the perpetual market to query

πŸ“€ Example Usage

const userAddress = '0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770';
const marketId = 501;

const response = await perpsMarketsInstance.getOpenOrders(userAddress, marketId);

πŸ“˜ Response Description

Field Type Description
address string Address of the user who placed the order
market_id string ID of the market where the order was placed
leverage number Leverage used for the order (e.g., 2x, 5x)
order_type number Type of the order (refer to order type table below)
timestamp string Unix timestamp of when the order was created
price string Price at which the order is placed
total_size string Total size/quantity of the order
remaining_size string Remaining size/quantity yet to be filled
order_value string Total value of the order (price * size)
order_id string Unique identifier for the order
trade_id string Trade group ID the order is part of
last_updated string Unix timestamp of the last update to the order

**πŸ“‘ Example Response **

{
  "success": true,
  "message": "Fetched open orders successfully",
  "data": [
    {
      "address": "0x3c78886aa67752706b3502b12959edf92e68d85ae64b24226783d26ce6efc1e",
      "market_id": "501",
      "leverage": 2,
      "order_type": 3,
      "timestamp": "1741444213",
      "price": "7",
      "total_size": "2",
      "remaining_size": "2",
      "order_value": "14",
      "order_id": "645636324063400958808",
      "trade_id": "295147905179352826357",
      "last_updated": "1741444214"
    }
  ]
}

**πŸ“Œ Order Type Reference **

Code Label Description
1 OPEN_LONG Opens a new long position (buy expecting price to go up)
2 OPEN_SHORT Opens a new short position (sell expecting price to go down)
3 INCREASE_LONG Increases the size of an existing long position
4 INCREASE_SHORT Increases the size of an existing short position
5 DECREASE_LONG Reduces the size of an existing long position
6 DECREASE_SHORT Reduces the size of an existing short position
7 CLOSE_LONG Closes an existing long position
8 CLOSE_SHORT Closes an existing short position
9 LONG_LIQUIDATION Auto-closes long position due to insufficient margin
10 SHORT_LIQUIDATION Auto-closes short position due to insufficient margin
11 LONG_TAKE_PROFIT Automatically closes long position when take-profit target is reached
12 SHORT_TAKE_PROFIT Automatically closes short position when take-profit target is reached
13 LONG_STOP_LOSS Automatically closes long position when stop-loss is triggered
14 SHORT_STOP_LOSS Automatically closes short position when stop-loss is triggered

16. View Function – getPositions:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Address of the user
marketId number βœ… ID of the perpetual market to query

**πŸ“€ Example Usage **

const userAddress = '0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770';
const marketId = 501;

const response = await perpsMarketsInstance.getPositions(userAddress, marketId);

πŸ“˜ Response Description

Field Type Description
address string Address of the user holding the position
market_id string ID of the market for this position
leverage number Leverage used for the position (e.g., 2x, 5x)
trade_side boolean Indicates if the position is a long (true) or short (false)
size string Total size/quantity of the position
available_order_size string Size available for placing reduce/close orders
value string Total value of the position (size * entry_price)
entry_price string Price at which the position was opened
liq_price string Liquidation price for the position
margin string Margin allocated to maintain this position
tp string Take-profit target price (if set)
sl string Stop-loss target price (if set)
trade_id string Trade group ID associated with this position
last_updated string Unix timestamp when the position was last updated

**πŸ“‘ Example Response **

{
  "success": true,
  "message": "Fetched positions successfully",
  "data": [
    {
      "address": "0x3c78886aa67752706b3502b12959edf92e68d85ae64b24226783d26ce6efc1e",
      "market_id": "501",
      "leverage": 2,
      "trade_side": true,
      "size": "1",
      "available_order_size": "1",
      "value": "5.678",
      "entry_price": "5.678",
      "liq_price": "2.9117948717948717990163355253",
      "margin": "2.839",
      "tp": "6.012",
      "sl": null,
      "trade_id": "295147905179352826357",
      "last_updated": "1741262185"
    }
  ]
}

Delegated Functions:

17. Entry Function – placeDelegatedLimitOrder:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Profile address of the user
marketId number βœ… ID of the market to place the order in
tradeSide boolean βœ… true = Long, false = Short
direction boolean βœ… false = Buy, true = Sell
size number βœ… Size of the order in base asset (e.g., APT)
price number βœ… Limit price of the order (e.g., in USDC)
leverage number βœ… Leverage for the order (min: 1, max: 20)
takeProfit number ❌ (Optional) Price at which to take profit
stopLoss number ❌ (Optional) Price at which to stop loss
restriction number ❌ (Optional) Type of order restriction:
0 – NO*RESTRICTION *(default)_: Taker then maker
1 – FILL_OR_ABORT: Only fill, abort if posts as maker
3 – POST_OR_ABORT: Only post, abort if fills as taker

πŸ“€ Example Usage

const userAddress = "0x1.........." // profile address
const marketId = 624;
const tradeSide = true; // Long
const direction = false; // Buy
const size = 1; // 1 APT
const price = 5.678; // 5.678 USDC
const leverage = 2;

const payload = await perpsMarketsInstance.placeDelegatedLimitOrder({
        userAddress, marketId, tradeSide, direction, size, price, leverage, takeProfit
});

18. Entry Function – placeDelegatedMarketOrder:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Profile address of the user
marketId number βœ… ID of the market to place the order in
tradeSide boolean βœ… true = Long, false = Short
direction boolean βœ… false = Buy, true = Sell
size number βœ… Size of the order in base asset (e.g., APT)
leverage number βœ… Leverage for the order (min: 1, max: 20)
takeProfit number ❌ (Optional) Price at which to take profit
stopLoss number ❌ (Optional) Price at which to stop loss

πŸ“€ Example Usage

const userAddress = "0x1.........." // profile address
const marketId = 501;
const tradeSide = false; // Short
const direction = false; // Sell
const size = 1; // 2 APT
const leverage = 2;
const takeProfit = 6.0; // Optional: Take profit price
const stopLoss = 4.0; // Optional: Stop loss price

const payload = await perpsMarketsInstance.placeDelegatedMarketOrder({
        userAddress, marketId, tradeSide, direction, size, leverage
});

19. Entry Function – cancelDelegatedMultipleOrders:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Profile address of the user
marketId number βœ… ID of the market to cancel orders from
cancelOrderIds string[] βœ… List of Order IDs to cancel
orderSides boolean[] βœ… List of order sides: true for Long, false for Short

πŸ“€ Example Usage

const userAddress = "0x1.........." // profile address
const marketId = 624;
const cancelOrderIds = ['516508974814240709142']; // Order IDs to cancel
const orderSides = [true]; // `true` = Long, `false` = Short

const payload = await perpsMarketsInstance.cancelDelegatedMultipleOrders({
        userAddress, marketId, cancelOrderIds, orderSides
});

20. Entry Function – placeDelegatedMultipleOrders:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Profile address of the user
marketId number βœ… ID of the market to place the orders in
orderTypes boolean[] βœ… List of order types (true for limit, false for market)
tradeSides boolean[] βœ… List of trade sides: true for Long, false for Short
directions boolean[] βœ… List of directions: false for open, true for close
sizes number[] βœ… List of sizes for the orders (in base asset, e.g., APT)
prices number[] βœ… List of prices for the limit orders (in USDC or other base currency)
leverages number[] βœ… List of leverages for each order (min: 1, max: 20)
restrictions number[] ❌ (Optional) List of restrictions for each order:
0 for NO_RESTRICTION, 1 for FILL_OR_ABORT, 3 for POST_OR_ABORT
takeProfits number[] ❌ (Optional) List of take profit prices for each order
stopLosses number[] ❌ (Optional) List of stop loss prices for each order

πŸ“€ Example Usage

const userAddress = "0x1.........." // profile address
const marketId = 624;
const orderTypes = [true, true]; // Limit orders
const tradeSides = [true, true]; // Long positions
const directions = [false, false]; // Open positions
const sizes = [1.5, 2.7]; // Size of orders in APT
const prices = [4.5, 4.326]; // Prices in USDC
const leverages = [2, 2]; // Leverage for each order
const restrictions = [0, 1]; // Optional: Restrictions for each order (e.g., NO_RESTRICTION or FILL_OR_ABORT)
const takeProfits = [6.0, 5.5]; // Optional: Take profit prices for each order
const stopLosses = [3.5, 4.0]; // Optional: Stop loss prices for each order

const payload = await perpsMarketsInstance.placeDelegatedMultipleOrders({
        userAddress, marketId, orderTypes, tradeSides, directions, sizes, prices, leverages
});

21. Entry Function – cancelAndplaceDelegatedMultipleOrders:

πŸ” Parameters

Param Type Required Description
userAddress string βœ… Profile address of the user
marketId number βœ… ID of the market to place the orders in
cancelOrderIds string[] βœ… List of order IDs to cancel
orderSides boolean[] βœ… List of order sides: true for Long, false for Short
orderTypes boolean[] βœ… List of order types: true for limit, false for market
tradeSides boolean[] βœ… List of trade sides: true for Long, false for Short
directions boolean[] βœ… List of directions: false for open, true for close
sizes number[] βœ… List of sizes for the orders (e.g., APT)
prices number[] βœ… List of prices for the limit orders (e.g., in USDC or other base currency)
leverages number[] βœ… List of leverages for each order (min: 1, max: 20)
restrictions number[] ❌ (Optional) List of restrictions for each order:
0 for NO_RESTRICTION, 1 for FILL_OR_ABORT, 3 for POST_OR_ABORT
takeProfits number[] ❌ (Optional) List of take profit prices for each order
stopLosses number[] ❌ (Optional) List of stop loss prices for each order

πŸ“€ Example Usage

const userAddress = "0x1.........." // profile address
const marketId = 624;
const cancelOrderIds = ['387381766311158747540', '405828651113766719718'];
const orderSides = [true, true]; // Long positions
const orderTypes = [true, true]; // Limit orders
const tradeSides = [true, true]; // Long trades
const directions = [false, false]; // Open positions
const sizes = [1.5, 2.7]; // Size of orders in APT
const prices = [4.5, 4.326]; // Prices in USDC
const leverages = [2, 2]; // Leverage for each order
const restrictions = [0, 1]; // Optional: Restrictions for each order (e.g., NO_RESTRICTION or FILL_OR_ABORT)
const takeProfits = [6.0, 5.5]; // Optional: Take profit prices for each order
const stopLosses = [3.5, 4.0]; // Optional: Stop loss prices for each order

const payload = await perpsMarketsInstance.cancelAndplaceDelegatedMultipleOrders({
        userAddress, marketId, cancelOrderIds, orderSides, orderTypes, tradeSides, directions, sizes, prices, leverages
});

About

A simple example demonstrating how to use the Kanalabs Perps SDK for interacting with perpetual trading features.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors