1. Get Market Info
Query Parameters :
marketId
(Required) - The ID of the market you want information about.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getMarketInfo?marketId=66
Example Response:
Copy {
"success" : true ,
"message" : "Fetched market info successfully" ,
"data" : [
{
"base_decimals" : 8 ,
"base_name" : "APT/USDC" ,
"counter" : "0" ,
"creator_address" : "0xb61d7b57333abf8ac036e752f19d0ba0c4baa5404db1cbf868c57dac3628f2bf" ,
"lot_size" : "150000000" ,
"maintenance_margin" : "250" ,
"market_address" : "0x2b1c1f9288506541f5a9ad37b5071e100bf289a74d27801cb6d3dc92a2c5fcca" ,
"market_id" : "301" ,
"max_leverage" : "20" ,
"max_lots" : "1500000" ,
"min_lots" : "500" ,
"quote_decimals" : 6 ,
"quote_precision" : 3 ,
"tick_size" : "1"
}
]
}
Example Code to Fetch Market Information:
The following TypeScript/Node.js script demonstrates how to call the Get Market Info API using the axios
library.
Copy import requests
import os
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/getMarketInfo'
params = {
'marketId' : 'your_market_id'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_market_info = response . json ()
print ( "getMarketInfo: " , get_market_info)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
2. Get Wallet Account Balance
Query Parameters :
marketId
(Required) - The ID of the market you want information about.
address (Required) - The wallet address for which the account balance is being fetched.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getWalletAccountBalance?marketId=66&address=0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770
Example Response:
Copy {
"success" : true ,
"message" : "Fetched wallet account balance successfully" ,
"data" : 611899
}
Example Code to Fetch Wallet Account Balance Information:
The following TypeScript/Node.js script demonstrates how to call the Get Wallet Account Balance API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/getWalletAccountBalance'
params = {
'marketId' : 'your_market_id' ,
'address' : 'your_wallet_address'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_wallet_account_balance = response . json ()
print ( "getWalletAccountBalance: " , get_wallet_account_balance)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
3. Get Trading Account Balance
Query Parameters :
marketId
(Required) - The ID of the market you want information about.
address (Required) - The wallet address for which the account balance is being fetched.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getTradingAccountBalance?marketId=66&address=0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770
Example Response:
Copy {
"success" : true ,
"message" : "Fetched trading account balance successfully" ,
"data" : 1027469914
}
Example Code to Fetch Trading Account Balance Information:
The following TypeScript/Node.js script demonstrates how to call the Get Trading Account Balance API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/getTradingAccountBalance'
params = {
'marketId' : 'your_market_id' ,
'address' : 'your_wallet_address'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_trading_account_balance = response . json ()
print ( "getTradingAccountBalance: " , get_trading_account_balance)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
4. Deposit
Query Parameters :
amount
(Required) - The amount of the quote coin to deposit.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/deposit?amount=50000000
Example Response:
Copy {
"success" : true ,
"message" : "Deposit payload built successfully" ,
"data" : {
"function" : "0xa1dc5fe31b275707ead4602c7aaf46e193c4c684b7420c389885702e86d80007::perpetual_core::deposit_asset" ,
"functionArguments" : [
50000000
] ,
"typeArguments" : [
]
}
}
Example Code to Depsoit a quote coin:
The following TypeScript/Node.js script demonstrates how to call the Get Deposit API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url , params , headers ):
try :
response = requests . get (api_url, params = params, headers = headers)
response . raise_for_status ()
return response . json (). get ( "data" )
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return None
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/deposit"
PARAMS = {
"amount" : "your_amount"
}
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, PARAMS, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "argumentTypes" ] = [Serializer . u64]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())
5. Withdraw
Query Parameters :
marketId
(Required) - The ID of the market you want to withdraw.
amount
(Required) - The amount of the quote coin to withdraw.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/withdraw?marketId=66&amount=50000000
Example Response:
Copy {
"success" : true ,
"message" : "Withdraw payload built successfully" ,
"data" : {
"function" : "0x1ce63c441256263ea2f45dd2d3a1e68e5843107c65c10b79c7a2d5aa2b7a4e3e::perp_market::withdraw" ,
"functionArguments" : [
50000000
] ,
"typeArguments" : [
]
}
}
Example Code to Withdraw a quote coin:
The following TypeScript/Node.js script demonstrates how to call the Get Withdraw API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url , params , headers ):
try :
response = requests . get (api_url, params = params, headers = headers)
response . raise_for_status ()
return response . json (). get ( "data" )
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return None
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/withdraw"
PARAMS = {
"marketId" : "your_market_id" ,
"amount" : "your_amount"
}
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, PARAMS, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "argumentTypes" ] = [Serializer . u64 , Serializer . u64]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())
6. Place Limit Order
Query Parameters :
marketId (Required) - The ID of the market where the limit order will be placed.
tradeSide (Required) - Indicates the trade side:
false
for the short side.
direction (Required) - Indicates the direction of the trade:
false
to open a position.
true
to close a position.
size (Required) - The size of the order.
price (Required) - The price at which the order is to be placed.
leverage (Required) - The leverage to be used for the order.
restriction - Specifies the type of order restriction. It is an optional parameter with a default value of 0
.
Possible values are:
0
- NO_RESTRICTION
: Optionally fill as a taker, then post to the book as a maker.
1
- FILL_OR_ABORT
: Abort if any size posts as a maker (only fill).
3
- POST_OR_ABORT
: Abort if any size fills as a taker (only post).
If restriction
is not provided, it defaults to 0
. It can either be a number or left undefined.
takeProfit - The take profit value is optional. If not provided, it defaults to 0
. It can either be a number or left undefined.
stopLoss - The stop loss value is also optional. If not provided, it defaults to 0
. It can either be a number or left undefined.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/limitOrder/?marketId=66&tradeSide=true&direction=false&size=10000&price=3000&leverage=3
Example Response:
Copy {
"success" : true ,
"message" : "Limit Order payload has been built successfully" ,
"data" : {
"function" : "0xa1dc5fe31b275707ead4602c7aaf46e193c4c684b7420c389885702e86d80007::perpetual_scripts::place_limit_order_external" ,
"functionArguments" : [
301 ,
true ,
false ,
10000 ,
3000 ,
3 ,
0 ,
10 ,
1
] ,
"typeArguments" : []
}
}
Example Code to Place a limit order:
The following TypeScript/Node.js script demonstrates how to call the Get Place Limit Order API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url , params , headers ):
try :
response = requests . get (api_url, params = params, headers = headers)
response . raise_for_status ()
return response . json (). get ( "data" )
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return None
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/limitOrder"
PARAMS = {
"marketId" : 'your_market_id' ,
"tradeSide" : 'your_trade_side' ,
"direction" : 'your_direction' ,
"price" : "your_price" ,
"size" : 'your_size' ,
"leverage" : 'your_leverage'
}
# restriction, take profit, and stop loss are optional (by default, they are set to 0).
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, PARAMS, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "argumentTypes" ] = [Serializer . u64 , Serializer . bool , Serializer . bool , Serializer . u64 , Serializer . u64 , Serializer . u8 , Serializer . u8 , Serializer . u64 , Serializer . u64]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())
7. Place Market Order
Query Parameters :
marketId (Required) - The ID of the market where the limit order will be placed.
tradeSide (Required) - Indicates the trade side:
false
for the short side.
direction (Required) - Indicates the direction of the trade:
false
to open a position.
true
to close a position.
size (Required) - The size of the order.
leverage (Required) - The leverage to be used for the order.
takeProfit - The take profit value is optional. If not provided, it defaults to 0
. It can either be a number or left undefined.
stopLoss - The stop loss value is also optional. If not provided, it defaults to 0
. It can either be a number or left undefined.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/marketOrder?marketId=66&tradeSide=false&direction=true&size=1000&leverage=20
Example Response:
Copy {
"success" : true ,
"message" : "Market Order payload has been built successfully" ,
"data" : {
"function" : "0xa1dc5fe31b275707ead4602c7aaf46e193c4c684b7420c389885702e86d80007::perpetual_scripts::place_market_order_external" ,
"functionArguments" : [
301 ,
false ,
true ,
1000 ,
20 ,
0 ,
0
] ,
"typeArguments" : []
}
}
Example Code to Place a market order:
The following TypeScript/Node.js script demonstrates how to call the Get Place Market Order API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url , params , headers ):
try :
response = requests . get (api_url, params = params, headers = headers)
response . raise_for_status ()
return response . json (). get ( "data" )
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return None
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/marketOrder"
PARAMS = {
"marketId" : 'your_market_id' ,
"tradeSide" : 'your_trade_side' ,
"direction" : 'your_direction' ,
"size" : 'your_size' ,
"leverage" : 'your_leverage'
}
# take profit, and stop loss are optional (by default, they are set to 0).
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, PARAMS, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "argumentTypes" ] = [Serializer . u64 , Serializer . bool , Serializer . bool , Serializer . u64 , Serializer . u8 , Serializer . u64 , Serializer . u64]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())
8. Cancel Multiple Orders
Request Body :
marketId : The ID of the market for which the orders will be canceled.
orderIds : A list of order IDs to cancel.
cancelTradeSides: The sides of the orders to cancel (true for long, false for short).
Example Request:
Copy {
"marketId" : 66 ,
"orderIds" : [ "1077898597726583798162207" , "1077880153515406921884445" ] ,
"cancelTradeSides" : [ true , false ]
}
Example Response:
Copy {
"success" : true ,
"message" : "Cancel Multiple Orders payload has been built successfully" ,
"data" : {
"function" : "0xa1dc5fe31b275707ead4602c7aaf46e193c4c684b7420c389885702e86d80007::perpetual_scripts::cancel_multiple_orders_external" ,
"functionArguments" : [
17 ,
[
"37114852031954082077144" ,
"37133298353772376889716"
] ,
[
true ,
false
]
] ,
"typeArguments" : []
}
}
Example Code to Cancel multiple orders:
The following TypeScript/Node.js script demonstrates how to call the Post Cancel Multiple Orders API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url , json_data , headers ):
try :
response = requests . post (api_url, json = json_data, headers = headers)
response . raise_for_status ()
return response . json (). get ( "data" )
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return None
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
try :
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
except Exception as e :
print ( f "Error creating transaction arguments: { e } " )
raise
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/cancelMultipleOrders"
BODY = {
"marketId" : "your_market_id" , # Please provide marketId as an integer
"orderIds" : [ "your_order_ids" ] ,
"cancelTradeSides" : [ "your_cancel_trade_sides" ]
}
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, BODY, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "functionArguments" ] = [
BODY [ "marketId" ],
BODY [ "orderIds" ],
BODY [ "cancelTradeSides" ]
]
payload_data [ "argumentTypes" ] = [
Serializer . u64 ,
Serializer . sequence_serializer (Serializer.u128),
Serializer . sequence_serializer (Serializer.bool)
]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())
8. Place Multiple Orders
Request Body :
marketId (Required) - The ID of the market where the orders will be placed.
orderTypes (Required) - An array of order types for each order:
tradeSides (Required) - An array indicating the trade sides for each order:
false for short positions.
directions (Required) - An array indicating the direction of each trade:
false to open a position.
true to close a position.
sizes (Required) - An array of sizes for each order.
leverages (Required) - An array of leverages for each order.
prices (Required) - An array of prices at which each order is to be placed.
restriction - Specifies the type of order restriction. It is an optional parameter with a default value of 0
.
Possible values are:
0
- NO_RESTRICTION
: Optionally fill as a taker, then post to the book as a maker.
1
- FILL_OR_ABORT
: Abort if any size posts as a maker (only fill).
3
- POST_OR_ABORT
: Abort if any size fills as a taker (only post).
If restriction
is not provided, it defaults to 0
. It can either be a number or left undefined.
takeProfits - The take profit value is optional. If not provided, it defaults to 0
. It can either be a number or left undefined.
stopLosses - The stop loss value is also optional. If not provided, it defaults to 0
. It can either be a number or left undefined.
Example Request:
Copy {
"marketId" : 66 ,
"orderTypes" : [ true , true ] ,
"tradeSides" : [ true , true ] ,
"directions" : [ true , true ] ,
"sizes" : [ 1000 , 1000 ] ,
"prices" : [ 1000 , 1000 ] ,
"leverages" : [ 2 , 2 ]
}
Example Response:
Copy {
"success" : true ,
"message" : "Place multiple orders payload built successfully" ,
"data" : {
"function" : "0xa1dc5fe31b275707ead4602c7aaf46e193c4c684b7420c389885702e86d80007::perpetual_scripts::place_multiple_orders_external" ,
"functionArguments" : [
47 ,
[ true , true ] ,
[ true , false ] ,
[ true , false ] ,
[ 1000 , 2000 ] ,
[ 4000 , 6000 ] ,
[ 2 , 3 ] ,
[ 0 , 0 ] ,
[ 11000 , 13000 ] ,
[ 15000 , 16000 ]
] ,
"typeArguments" : []
}
}
Example Code to Place a multiple orders:
The following TypeScript/Node.js script demonstrates how to call the Get Place Multiple Orders API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url : str , json_data : dict , headers : dict ) -> dict :
try :
response = requests . post (api_url, json = json_data, headers = headers)
response . raise_for_status ()
payload_data = response . json (). get ( "data" )
if payload_data is None :
print ( "No data returned from API." )
return {}
# Dynamically ensure the length matches the sizes provided
payload_data [ "takeProfits" ] = payload_data . get ( "takeProfits" , [ 0 ] * len (json_data[ "sizes" ]))
payload_data [ "stopLosses" ] = payload_data . get ( "stopLosses" , [ 0 ] * len (json_data[ "sizes" ]))
payload_data [ "restrictions" ] = payload_data . get ( "restrictions" , [ 0 ] * len (json_data[ "sizes" ]))
return payload_data
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return {}
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
try :
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
except Exception as e :
print ( f "Error creating transaction arguments: { e } " )
raise
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/placeMultipleOrders"
BODY = {
"marketId" : "your_market_id" , # Please provide marketId as an integer
"orderTypes" : [ "your_order_types" ] ,
"tradeSides" : [ "your_trade_sides" ] ,
"directions" : [ "your_directions" ] ,
"sizes" : [ "your_sizes" ] ,
"prices" : [ "your_prices" ] ,
"leverages" : [ "your_leverages" ]
}
# restrictions, take profits, and stop losses are optional (by default, they are set to 0)
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, BODY, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "functionArguments" ] = [
BODY [ "marketId" ],
BODY [ "orderTypes" ],
BODY [ "tradeSides" ],
BODY [ "directions" ],
BODY [ "sizes" ],
BODY [ "prices" ],
BODY [ "leverages" ],
payload_data [ "restrictions" ],
payload_data [ "takeProfits" ],
payload_data [ "stopLosses" ]
]
payload_data [ "argumentTypes" ] = [
Serializer . u64 ,
Serializer . sequence_serializer (Serializer.bool),
Serializer . sequence_serializer (Serializer.bool),
Serializer . sequence_serializer (Serializer.bool),
Serializer . sequence_serializer (Serializer.u64),
Serializer . sequence_serializer (Serializer.u64),
Serializer . sequence_serializer (Serializer.u8),
Serializer . sequence_serializer (Serializer.u8),
Serializer . sequence_serializer (Serializer.u64),
Serializer . sequence_serializer (Serializer.u64)
]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())
9. Cancel and Place Multiple Orders
Request Body :
marketId (Required) - The ID of the market where the orders will be placed.
orderIds (Required) - An array of strings representing the IDs of the orders to be canceled.
cancelTradeSides (Required) - An array indicating the sides of the orders being canceled:
orderTypes (Required) - An array of order types for each order:
orderTradeSides (Required) - An array indicating the trade sides for each order:
false for short positions.
directions (Required) - An array indicating the direction of each trade:
false to open a position.
true to close a position.
sizes (Required) - An array of sizes for each order.
leverages (Required) - An array of leverages for each order.
prices (Required) - An array of prices at which each order is to be placed.
restriction - Specifies the type of order restriction. It is an optional parameter with a default value of 0
.
Possible values are:
0
- NO_RESTRICTION
: Optionally fill as a taker, then post to the book as a maker.
1
- FILL_OR_ABORT
: Abort if any size posts as a maker (only fill).
3
- POST_OR_ABORT
: Abort if any size fills as a taker (only post).
If restriction
is not provided, it defaults to 0
. It can either be a number or left undefined
takeProfits - The take profit value is optional. If not provided, it defaults to 0
. It can either be a number or left undefined.
stopLosses - The stop loss value is also optional. If not provided, it defaults to 0
. It can either be a number or left undefined.
Example Request:
Copy {
"marketId" : 66 ,
"orderIds" : [ "23434565434567" , "454345665456" ] ,
"cancelTradeSides" : [ true , true ] ,
"orderTypes" : [ true , true ] ,
"orderTradeSides" : [ true , false ] ,
"directions" : [ true , true ] ,
"sizes" : [ 1000 , 2000 ] ,
"prices" : [ 5000 , 6000 ] ,
"leverages" : [ 2 , 2 ]
}
Example Response:
Copy {
"success" : true ,
"message" : "Cancel and place multiple Orders payload has been built successfully" ,
"data" : {
"function" : "0xa1dc5fe31b275707ead4602c7aaf46e193c4c684b7420c389885702e86d80007::perpetual_scripts::cancel_and_place_multiple_orders_external" ,
"functionArguments" : [
47 ,
"0xc0de11113b427d35ece1d8991865a941c0578b0f349acabbe9753863c24109ff" ,
[
"37114852031954082077144" ,
"37133298353772376889716"
] ,
[ true , false ] ,
[ true , false ] ,
[ true , false ] ,
[ 1000 , 2000 ] ,
[ 4000 , 6000 ] ,
[ 2 , 3 ] ,
[ 0 , 0 ] ,
[ 11000 , 13000 ] ,
[ 15000 , 16000 ]
] ,
"typeArguments" : []
}
}
Example Code to cancel and Place a multiple orders:
The following TypeScript/Node.js script demonstrates how to call the Get Cancel And Place Multiple Orders API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url : str , json_data : dict , headers : dict ) -> dict :
try :
response = requests . post (api_url, json = json_data, headers = headers)
response . raise_for_status ()
payload_data = response . json (). get ( "data" )
if payload_data is None :
print ( "No data returned from API." )
return {}
# Dynamically ensure the length matches the sizes provided
payload_data [ "takeProfits" ] = payload_data . get ( "takeProfits" , [ 0 ] * len (json_data[ "sizes" ]))
payload_data [ "stopLosses" ] = payload_data . get ( "stopLosses" , [ 0 ] * len (json_data[ "sizes" ]))
payload_data [ "restrictions" ] = payload_data . get ( "restrictions" , [ 0 ] * len (json_data[ "sizes" ]))
return payload_data
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return {}
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
try :
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
except Exception as e :
print ( f "Error creating transaction arguments: { e } " )
raise
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/cancelAndPlaceMultipleOrders"
BODY = {
"marketId" : "your_market_id" , # Please provide marketId as an integer
"orderIds" : [ "your_order_ids" ] ,
"cancelTradeSides" : [ "your_cancel_trade_sides" ] ,
"orderTypes" : [ "your_order_types" ] ,
"orderTradeSides" : [ "your_order_trade_sides" ] ,
"directions" : [ "your_directions" ] ,
"sizes" : [ "your_sizes" ] ,
"prices" : [ "your_prices" ] ,
"leverages" : [ "your_leverages" ]
}
# restrictions, take profits, and stop losses are optional (by default, they are set to 0)
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, BODY, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "functionArguments" ] = [
BODY [ "marketId" ],
BODY [ "orderIds" ],
BODY [ "cancelTradeSides" ],
BODY [ "orderTypes" ],
BODY [ "orderTradeSides" ],
BODY [ "directions" ],
BODY [ "sizes" ],
BODY [ "prices" ],
BODY [ "leverages" ],
payload_data [ "restrictions" ],
payload_data [ "takeProfits" ],
payload_data [ "stopLosses" ]
]
payload_data [ "argumentTypes" ] = [
Serializer . u64 ,
Serializer . sequence_serializer (Serializer.u128),
Serializer . sequence_serializer (Serializer.bool),
Serializer . sequence_serializer (Serializer.bool),
Serializer . sequence_serializer (Serializer.bool),
Serializer . sequence_serializer (Serializer.bool),
Serializer . sequence_serializer (Serializer.u64),
Serializer . sequence_serializer (Serializer.u64),
Serializer . sequence_serializer (Serializer.u8),
Serializer . sequence_serializer (Serializer.u8),
Serializer . sequence_serializer (Serializer.u64),
Serializer . sequence_serializer (Serializer.u64)
]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())
10. Get Open Orders
Query Parameters :
address (Required) - The wallet address to retrieve open orders for.
marketId (Required) - The ID of the market to filter open orders.
Copy Note : Trade Types Explanation:
OPEN_LONG (1): Opens a new long position.
OPEN_SHORT (2): Opens a new short position.
INCREASE_LONG (3): Increases the size of an existing long position.
INCREASE_SHORT (4): Increases the size of an existing short position.
DECREASE_LONG (5): Reduces the size of an existing long position.
DECREASE_SHORT (6): Reduces the size of an existing short position.
CLOSE_LONG (7): Closes an existing long position.
CLOSE_SHORT (8): Closes an existing short position.
Note: Order Side Explanation:
orderSide: false --> Bids (buy)
orderSide: true --> Asks (sell)
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/openOrders?address=0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770&marketId=66
Example Response:
Copy {
"success" : true ,
"message" : "Current open orders data fetched successfully" ,
"data" : [
{
"marketOrderId" : "92233861123215989592" ,
"orderSide" : false ,
"marketPrice" : "7000" ,
"marketSize" : "100000000" ,
"leverage" : 2 ,
"tradeType" : 1 ,
"timestamp" : "2024-12-31T04:21:27.892309+00:00"
} ,
{
"marketOrderId" : "110680745925823961945" ,
"orderSide" : false ,
"marketPrice" : "7001" ,
"marketSize" : "200000000" ,
"leverage" : 2 ,
"tradeType" : 3 ,
"timestamp" : "2024-12-31T04:21:27.892309+00:00"
} ,
{
"marketOrderId" : "147574374827911291688" ,
"orderSide" : false ,
"marketPrice" : "9000" ,
"marketSize" : "100000000" ,
"leverage" : 2 ,
"tradeType" : 3 ,
"timestamp" : "2024-12-31T12:25:19.368272+00:00"
}
]
}
Example Code to Fetch Open Orders:
The following TypeScript/Node.js script demonstrates how to call the Get Open Orders API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/openOrders'
params = {
'marketId' : 'your_market_id' ,
'address' : 'your_wallet_address'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_open_orders = response . json ()
print ( "getOpenOrders: " , get_open_orders)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
11. Get Order History
Query Parameters :
address (Required) - The wallet address to retrieve the order history for.
marketId (Required) - The ID of the market to filter the order history.
offset (Optional) - The number of records to skip for pagination (default is 0
if not provided).
limit (Optional) - The maximum number of records to retrieve (default is 10
if not provided).
order (Optional) - The sorting order for the results. Options:
'asc'
for ascending order.
'desc'
for descending order.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/orderHistory?address=0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770&marketId=66
Example Response:
Copy {
"status" : true ,
"message" : "Fetched order history successfully" ,
"data" : [
{
"market_id" : 66 ,
"order_id" : "15308344164217124470915072" ,
"created_at" : "2024-11-20T11:54:54.672164+00:00" ,
"last_updated_at" : "2024-11-20T11:54:54.672164+00:00" ,
"integrator" : "0xfb7e14963ceda75902f2767e38f95305646de7849b96c433b8a8ec31b008aaa1" ,
"total_filled" : 1000 ,
"remaining_size" : 0 ,
"order_status" : "closed" ,
"order_type" : "market" ,
"user" : "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770" ,
"direction" : "sell" ,
"price" : 0 ,
"average_execution_price" : 12792 ,
"custodian_id" : 28 ,
"self_match_behavior" : 0 ,
"restriction" : 0 ,
"last_increase_stamp" : null ,
"min_base" : null ,
"max_base" : null ,
"min_quote" : null ,
"max_quote" : null ,
"total_fees_paid_in_quote_subunits" : 6396 ,
"leverage" : 20 ,
"trade_type" : 11 ,
"timestamp" : "1732103694"
} ,
{
"market_id" : 66 ,
"order_id" : "15308325717473050761363456" ,
"created_at" : "2024-11-20T11:54:45.957059+00:00" ,
"last_updated_at" : "2024-11-20T11:54:45.957059+00:00" ,
"integrator" : "0xee820ab02631dd1a195d3c53fa64f0a8f455dbb9261388e141c3bd3bd3c08363" ,
"total_filled" : 1000 ,
"remaining_size" : 0 ,
"order_status" : "closed" ,
"order_type" : "market" ,
"user" : "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770" ,
"direction" : "buy" ,
"price" : 0 ,
"average_execution_price" : 12813 ,
"custodian_id" : 28 ,
"self_match_behavior" : 0 ,
"restriction" : 0 ,
"last_increase_stamp" : null ,
"min_base" : null ,
"max_base" : null ,
"min_quote" : null ,
"max_quote" : null ,
"total_fees_paid_in_quote_subunits" : 6406 ,
"leverage" : 20 ,
"trade_type" : 3 ,
"timestamp" : "1732103685"
}
]
}
Example Code to Fetch Order History:
The following TypeScript/Node.js script demonstrates how to call the Get Order History API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/orderHistory'
params = {
'marketId' : 'your_market_id' ,
'address' : 'your_wallet_address'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_order_history = response . json ()
print ( "getOrderHistory: " , get_order_history)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
12. Get Open Position
Query Parameters :
address (Required) - The wallet address of the user to view positions for.
marketId (Required) - The ID of the market to filter the positions.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/viewPositions?marketId=66&address=0x2eda5777ed2bf68cbcc67359dd00ae5fa73b1d5fa160b7c3aeb42d748d485387
Example Response:
Copy {
"success" : true ,
"message" : "Fetched view position successfully" ,
"data" : {
"longViewData" : {
"close_size" : "0" ,
"close_taker_fee" : "0" ,
"collateral" : "15001000" ,
"entry_price" : "700100000000" ,
"exit_price" : "0" ,
"filled_close_size" : "0" ,
"filled_open_size" : "100000000" ,
"leverage" : 2 ,
"liquidation_price" : "3590" ,
"open_size" : "400000000" ,
"open_taker_fee" : "0" ,
"position_value" : "30002000" ,
"quote_contribution" : "15001000" ,
"stop_loss" : "0" ,
"take_profit" : "0" ,
"trade_id" : "55340232221128655149"
} ,
"shortViewData" : {
"base_contribution" : "0" ,
"close_size" : "0" ,
"close_taker_fee" : "0" ,
"collateral" : "0" ,
"entry_price" : "0" ,
"exit_price" : "0" ,
"filled_close_size" : "0" ,
"filled_open_size" : "0" ,
"leverage" : 0 ,
"liquidation_price" : "0" ,
"open_size" : "0" ,
"open_taker_fee" : "0" ,
"position_value" : "0" ,
"stop_loss" : "0" ,
"take_profit" : "0" ,
"trade_id" : "0"
} ,
"tradingBalance" : "286394611"
}
}
Example Code to Fetch Open Position:
The following TypeScript/Node.js script demonstrates how to call the Get Open Position API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/viewPositions'
params = {
'marketId' : 'your_market_id' ,
'address' : 'your_wallet_address'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_open_position = response . json ()
print ( "getOpenPosition: " , get_open_position)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
12. Get All Trades
Query Parameters :
marketId (Required) - The ID of the market to retrieve all trades information.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getAllTrades?marketId=66
Example Response:
Copy {
"success" : true ,
"message" : "Recent trades fetched successfully" ,
"data" : [
{
"txn_version" : 6297687196 ,
"event_idx" : 5 ,
"emit_address" : "0x2eda5777ed2bf68cbcc67359dd00ae5fa73b1d5fa160b7c3aeb42d748d485387" ,
"time" : "2024-11-20T20:33:38.600241+00:00" ,
"maker_address" : "0x2eda5777ed2bf68cbcc67359dd00ae5fa73b1d5fa160b7c3aeb42d748d485387" ,
"maker_custodian_id" : 28 ,
"maker_order_id" : "15951655917465922493754983" ,
"maker_side" : true ,
"market_id" : 66 ,
"price" : 11879 ,
"sequence_number_for_trade" : 0 ,
"size" : 10000 ,
"taker_address" : "0x13eb7ea6b62c6cd791b5c4e0e2ef1dfbe59d1cf4823929343a273274c288bc8a" ,
"taker_custodian_id" : 28 ,
"taker_order_id" : "15951748150764039921729536" ,
"taker_quote_fees_paid" : 59395
} ,
{
"txn_version" : 6297687196 ,
"event_idx" : 4 ,
"emit_address" : "0x13eb7ea6b62c6cd791b5c4e0e2ef1dfbe59d1cf4823929343a273274c288bc8a" ,
"time" : "2024-11-20T20:33:38.600241+00:00" ,
"maker_address" : "0x2eda5777ed2bf68cbcc67359dd00ae5fa73b1d5fa160b7c3aeb42d748d485387" ,
"maker_custodian_id" : 28 ,
"maker_order_id" : "15951655917465922493754983" ,
"maker_side" : true ,
"market_id" : 66 ,
"price" : 11879 ,
"sequence_number_for_trade" : 0 ,
"size" : 10000 ,
"taker_address" : "0x13eb7ea6b62c6cd791b5c4e0e2ef1dfbe59d1cf4823929343a273274c288bc8a" ,
"taker_custodian_id" : 28 ,
"taker_order_id" : "15951748150764039921729536" ,
"taker_quote_fees_paid" : 59395
}
]
}
Example Code to Fetch Open Position:
The following TypeScript/Node.js script demonstrates how to call the Get Open Position API using the axios
library.
Copy import axios from "axios" ;
async function main () : Promise < void > {
const baseURL = 'https://perps-tradeapi.kanalabs.io/getAllTrades' ;
const params = {
marketId : 'your_market_id'
};
const res = await axios .get (baseURL , {
params ,
headers : {
'x-api-key' : process . env . API_KEY ,
} ,
});
const getAllTrades = res .data;
console .log ( "getAllTrades : " , getAllTrades);
}
main () .catch (error => {
console .error ( 'An error occurred:' , error);
});
13. Get Order Status By Order Id
Query Parameters :
marketId (Required) - The ID of the market associated with the order.
orderId (Required) - The unique identifier of the order to retrieve its status.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getOrderStatusByOrderId?marketId=66&orderId=15308325717473050761363456
Example Response:
Copy {
"status" : true ,
"message" : "Fetched order status for a given order Id successfully" ,
"data" : {
"market_id" : 66 ,
"order_id" : "15308325717473050761363456" ,
"created_at" : "2024-11-20T11:54:45.957059+00:00" ,
"last_updated_at" : "2024-11-20T11:54:45.957059+00:00" ,
"integrator" : "0xee820ab02631dd1a195d3c53fa64f0a8f455dbb9261388e141c3bd3bd3c08363" ,
"total_filled" : 1000 ,
"remaining_size" : 0 ,
"order_status" : "closed" ,
"order_type" : "market" ,
"user" : "0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770" ,
"direction" : "buy" ,
"price" : 0 ,
"average_execution_price" : 12813 ,
"custodian_id" : 28 ,
"self_match_behavior" : 0 ,
"restriction" : 0 ,
"last_increase_stamp" : null ,
"min_base" : null ,
"max_base" : null ,
"min_quote" : null ,
"max_quote" : null ,
"total_fees_paid_in_quote_subunits" : 6406
}
}
Example Code to Fetch Order Status B Order Id:
The following TypeScript/Node.js script demonstrates how to call the Get Order Status By Order Id API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/getOrderStatusByOrderId'
params = {
'marketId' : 'your_market_id' ,
'orderId' : 'your_order_id'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_order_status_by_order_id = response . json ()
print ( "getOrderStatusByOrderId: " , get_order_status_by_order_id)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
14. Get Fills
Query Parameters :
marketId (Required) - The ID of the market for which fills are retrieved.
address (Optional) - The address of the user to filter fills (if applicable).
from (Required) - The start time of the range in ISO 8601 format (e.g., 2024-11-21T00:00:00Z
).
to (Required) - The end time of the range in ISO 8601 format (e.g., 2024-11-21T23:59:59Z
).
orderId (Required) - The unique identifier of the order to retrieve its status.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getFills?marketId=66&address=0x3a6b332c7889784fe57ea61f507b5056e386db8f56c6323b4d898485f468f0c2&from=2024-11-20T00:00:00Z&to=2024-11-21T23:59:59Z
Example Response:
Copy {
"success" : true ,
"message" : "Fetched fill trades for a given time range Successfully" ,
"data" : [
{
"txn_version" : 6296434935 ,
"event_idx" : 1 ,
"emit_address" : "0x3a6b332c7889784fe57ea61f507b5056e386db8f56c6323b4d898485f468f0c2" ,
"time" : "2024-11-20T19:23:14.67535+00:00" ,
"maker_address" : "0x2eda5777ed2bf68cbcc67359dd00ae5fa73b1d5fa160b7c3aeb42d748d485387" ,
"maker_custodian_id" : 28 ,
"maker_order_id" : "15891335065048614061485282" ,
"maker_side" : true ,
"market_id" : 66 ,
"price" : 11490 ,
"sequence_number_for_trade" : 0 ,
"size" : 1000 ,
"taker_address" : "0x3a6b332c7889784fe57ea61f507b5056e386db8f56c6323b4d898485f468f0c2" ,
"taker_custodian_id" : 28 ,
"taker_order_id" : "15891427297643009687945216" ,
"taker_quote_fees_paid" : 5745
} ,
{
"txn_version" : 6295302625 ,
"event_idx" : 4 ,
"emit_address" : "0x3a6b332c7889784fe57ea61f507b5056e386db8f56c6323b4d898485f468f0c2" ,
"time" : "2024-11-20T18:19:35.70863+00:00" ,
"maker_address" : "0x2eda5777ed2bf68cbcc67359dd00ae5fa73b1d5fa160b7c3aeb42d748d485387" ,
"maker_custodian_id" : 28 ,
"maker_order_id" : "15812401447297883953966476" ,
"maker_side" : false ,
"market_id" : 66 ,
"price" : 11660 ,
"sequence_number_for_trade" : 0 ,
"size" : 1000 ,
"taker_address" : "0x3a6b332c7889784fe57ea61f507b5056e386db8f56c6323b4d898485f468f0c2" ,
"taker_custodian_id" : 28 ,
"taker_order_id" : "15812549019983827645235200" ,
"taker_quote_fees_paid" : 5830
}
]
}
Example Code to Fetch Order Status B Order IdFills Data:
The following TypeScript/Node.js script demonstrates how to call the Get Fills Data API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/getFills'
params = {
'marketId' : 'your_market_id' ,
'address' : 'your_address' ,
'from' : 'your_from_time' ,
'to' : 'your_to_time'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_fills_data = response . json ()
print ( "getFillsData: " , get_fills_data)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
14. Get Market Price
Query Parameters :
marketId (Required) - The ID of the market for which the price information is being retrieved.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getMarketPrice?marketId=66
Example Response:
Copy {
"success" : true ,
"message" : "Fetched Market Price Successfully" ,
"data" : {
"bestAskPrice" : 6000 ,
"bestBidPrice" : 9000
}
}
Example Code to Fetch Market Price:
The following TypeScript/Node.js script demonstrates how to call the Get Market Price API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/getMarketPrice'
params = {
'marketId' : 'your_market_id'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_market_price = response . json ()
print ( "getMarketPrice: " , get_market_price)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
15. Get Last Execution Price
Query Parameters :
marketId (Required) - The ID of the market for which the last execution price information is being retrieved.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getLastPlacedPrice?marketId=66
Example Response:
Copy {
"success" : true ,
"message" : "Fetched last execution price Successfully" ,
"data" : {
"tickPrice" : 7074 ,
"usdcPrice" : 7.074
}
}
Example Code to Fetch Last Execution Price:
The following TypeScript/Node.js script demonstrates how to call the Get Last Execution Price API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/getLastPlacedPrice'
params = {
'marketId' : 'your_market_id'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_last_execution_price = response . json ()
print ( "getLastExecutionPrice: " , get_last_execution_price)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
16. Get Open Order Ids
Query Parameters :
address (Required) - The address associated with the orders.
marketId (Required) - The ID of the market for which open order IDs are being retrieved.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/openOrderIds?marketId=66&address=0x3a6b332c7889784fe57ea61f507b5056e386db8f56c6323b4d898485f468f0c2
Example Response:
Copy {
"success" : true ,
"message" : "Open order IDs fetched successfully" ,
"data" : [
"92233861123215989592" ,
"110680745925823961945" ,
"147574374827911291688"
]
}
Example Code to Fetch Open Order Ids:
The following TypeScript/Node.js script demonstrates how to call the Get Open Order Ids API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/openOrderIds'
params = {
'address' : 'your_wallet_address' ,
'marketId' : 'your_market_id'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_open_order_ids = response . json ()
print ( "getOpenOrderIds: " , get_open_order_ids)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
17. Update Take Profit
Query Parameters :
marketId (Required) - The ID of the market for which the take profit values will be updated.
tradeSide (Required) - The trade side:
false
for the short side.
newTakeProfitPrice (Required) - The new take profit price to be set for the trade.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/updateTp?marketId=66&tradeSide=true&newTakeProfitPrice=6000
Example Response:
Copy {
"success" : true ,
"message" : "Update take profit payload built successfully" ,
"data" : {
"function" : "0xa1dc5fe31b275707ead4602c7aaf46e193c4c684b7420c389885702e86d80007::perpetual_core::UpdateTakeProfitEvent" ,
"functionArguments" : [
17 ,
true ,
5000
] ,
"typeArguments" : [ "" ]
}
}
Example Code to Update take profit price:
The following TypeScript/Node.js script demonstrates how to call the Get Update Take Profit Price API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url , params , headers ):
try :
response = requests . get (api_url, params = params, headers = headers)
response . raise_for_status ()
return response . json (). get ( "data" )
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return None
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/updateTp"
PARAMS = {
"marketId" : 'your_market_id' ,
"tradeSide" : 'your_trade_side' ,
"newTakeProfitPrice" : 'your_tp_price'
}
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, PARAMS, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "argumentTypes" ] = [Serializer . u64 , Serializer . bool , Serializer . u64]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())
18. Get Account Aptos Balance
marketId (Required) - The ID of the market for which the account's balance is being retrieved.
address (Required) - The address of the account whose balance will be
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/getAccountAptBalance?marketId=66&address=0x4d6dc68e391e86991e58ab4d548b7e92872430d1f51bc666fe0c206bad7ff770
Example Response:
Copy {
"success" : true ,
"message" : "Fetched Account Apt Balance Successfully" ,
"data" : 82344617
}
Example Code to Fetch Wallet Account Aptos Balance Information:
The following TypeScript/Node.js script demonstrates how to call the Get Wallet Account Aptos Balance API using the axios
library.
Copy import os
import requests
from dotenv import load_dotenv
load_dotenv ()
def main ():
try :
base_url = 'https://perps-tradeapi.kanalabs.io/getAccountAptBalance'
params = {
'marketId' : 'your_market_id' ,
'address' : 'your_wallet_address'
}
api_key = os . getenv ( 'API_KEY' )
headers = {
'x-api-key' : api_key
}
response = requests . get (base_url, params = params, headers = headers)
response . raise_for_status ()
get_wallet_account_aptos_balance = response . json ()
print ( "getWalletAccountAptosBalance: " , get_wallet_account_aptos_balance)
except requests . exceptions . RequestException as error :
print ( 'An error occurred:' , error)
if __name__ == "__main__" :
main ()
19. Update Stop Loss
Query Parameters :
marketId (Required) - The ID of the market for which the take profit values will be updated.
tradeSide (Required) - The trade side:
false
for the short side.
newStopLossPrice (Required) - The new stop loss price to be set for the trade.
Example Request:
Copy GET https://perps-tradeapi.kanalabs.io/updateSl?marketId=66&tradeSide=true&newStopLossPrice=6000
Example Response:
Copy {
"success" : true ,
"message" : "Update stop loss payload built successfully" ,
"data" : {
"function" : "0xa1dc5fe31b275707ead4602c7aaf46e193c4c684b7420c389885702e86d80007::perpetual_core::UpdateStopLossEvent" ,
"functionArguments" : [
17 ,
true ,
3000
] ,
"typeArguments" : [ "" ]
}
}
Example Code to Update stop loss price:
The following TypeScript/Node.js script demonstrates how to call the Get Update Stop Loss Price API using the axios
library.
Copy import asyncio
import os
from aptos_sdk . account import Account
from aptos_sdk . async_client import RestClient
from aptos_sdk . transactions import EntryFunction , TransactionArgument , TransactionPayload
from aptos_sdk . bcs import Serializer
from aptos_sdk . type_tag import TypeTag , StructTag
import requests
from dotenv import load_dotenv
from typing import Any , List
load_dotenv ()
class AptosTransactionHandler :
def __init__ ( self , rest_client : RestClient , account : Account):
self . rest_client = rest_client
self . account = account
def fetch_payload ( self , api_url , params , headers ):
try :
response = requests . get (api_url, params = params, headers = headers)
response . raise_for_status ()
return response . json (). get ( "data" )
except requests . exceptions . RequestException as e :
print ( f "Error fetching payload: { e } " )
return None
def create_transaction_function_arguments ( self , arguments : List [ Any ], types : List [ Serializer ] ) -> List [ TransactionArgument ] :
if len (arguments) != len (types):
raise ValueError ( "Arguments and types length mismatch." )
return [ TransactionArgument (arg, serializer) for arg , serializer in zip (arguments, types) ]
def create_transaction_payload ( self , payload : dict ) -> TransactionPayload:
try :
function_information = payload [ "function" ]. split ( "::" )
module = "::" . join (function_information[: - 1 ])
function_id = function_information [ - 1 ]
function_arguments = self . create_transaction_function_arguments (
payload[ "functionArguments" ],
payload[ "argumentTypes" ]
)
type_arguments = [ TypeTag (StructTag. from_str (argument)) for argument in payload [ "typeArguments" ] ]
entry_function = EntryFunction . natural (
module = module,
function = function_id,
ty_args = type_arguments,
args = function_arguments,
)
return TransactionPayload (payload = entry_function)
except Exception as e :
print ( f "Error creating transaction payload: { e } " )
raise
async def submit_transaction ( self , transaction_payload : TransactionPayload) -> str :
try :
signed_transaction_request = await self . rest_client . create_bcs_signed_transaction (
sender = self.account, payload = transaction_payload
)
txn_hash = await self . rest_client . submit_bcs_transaction (
signed_transaction = signed_transaction_request
)
await self . rest_client . wait_for_transaction (txn_hash = txn_hash)
return txn_hash
except Exception as e :
print ( f "Error during transaction submission: { e } " )
raise
async def main ():
NODE_URL = "https://api.testnet.aptoslabs.com/v1"
rest_client = RestClient (NODE_URL)
private_key_hex = os . getenv ( 'APTOS_PRIVATEKEY' )
if private_key_hex . startswith ( "0x" ):
private_key_hex = private_key_hex [ 2 :]
private_key_bytes = bytes . fromhex (private_key_hex)
account = Account . load_key (private_key_bytes)
API_URL = "https://perps-tradeapi.kanalabs.io/updateSl"
PARAMS = {
"marketId" : 'your_market_id' ,
"tradeSide" : 'your_trade_side' ,
"newStopLossPrice" : 'your_sl_price'
}
HEADERS = { "x-api-key" : os . getenv ( 'API_KEY' )}
handler = AptosTransactionHandler (rest_client, account)
payload_data = handler . fetch_payload (API_URL, PARAMS, HEADERS)
if not payload_data :
print ( "Failed to fetch payload data." )
return
try :
payload_data [ "argumentTypes" ] = [Serializer . u64 , Serializer . bool , Serializer . u64]
transaction_payload = handler . create_transaction_payload (payload_data)
print ( "Transaction payload created successfully." )
txn_hash = await handler . submit_transaction (transaction_payload)
print ( f "Transaction submitted successfully. Transaction hash: { txn_hash } " )
except Exception as e :
print ( f "Error during transaction process: { e } " )
if __name__ == "__main__" :
asyncio . run ( main ())