NAV
shell python

Introduction

We have language bindings in Shell, Python! You can view code examples in the dark area to the right, and you can switch the programming language of the examples with the tabs in the top right.

General

v1.0.0

API Resources and Support Channels

Zero-Knowledge Rollups

On-chain data availability and integrity can be ensured with StarkWare’s STARK proofs, a form of zero-knowledge proof (ZK-proof) technology that will help safeguard a fully non-custodial protocol. Built on the Ethereum network, this Layer 2 architecture publishes ZK-proofs directly to Ethereum smart contracts for verification. Transactions are also uniquely packaged for publishing on-chain for traders concerned about data privacy as only balance charges will be made visible.

Cross-Chain Deposits and Withdrawals

Support for the deposits and withdrawals for EVM-compatible chains are available on ApeX Pro. Tokens will be converted to USDC via the 1inch API protocol swap.

Cross-Chain Deposits

ApeX Pro has built multiple asset pools on different chains. When users deposit assets from a non-Ethereum chain, ApeX Pro will transfer an equivalent amount of assets to the user's L2 account through its corresponding asset pool, built on the respective chain.
When a user deposit USDC from A chain, ApeX Pro could transfer the corresponding amount USDC to the user's account in L2 through its own asset pool.

Cross-Chain Withdrawal

You can withdraw assets directly to different chain on ApeX Pro. When a user withdraws their assets to an EVM-compatible chain, the asset will first be transferred to ApeX Pro's L2 asset pool. Thereafter, ApeX Pro will transfer the corresponding amount of assets to the user's address from its own asset pool on the corresponding withdrawal chain.
Please note that the maximum withdrawal amount is not only limited by the total assets available in a user’s account, but also needs to be less than the maximum available amount of the chain's asset pool.

Example:

Assume that there is 10,000 USDC available in Alice's account. Alice wants to withdraw 10,000 USDC via the Polygon chain, but only 8,000 USDC is available in Polygon's asset pool on ApeX Pro. The system will inform Alice that the current available assets in the Polygon chain are insufficient and prompt Alice to withdraw from another chain.
Alice has two choices. She either withdraws 8,000 USDC or less from the Polygon chain and withdraw the remainder of her balance via another chain or proceed to withdraw 10,000 USDC via another chain of which assets pools has sufficient funds to process the withdrawal request.
Traders can safely and easily proceed with deposit and withdrawal transactions via preferred chain on ApeX Pro.
ApeX Pro will also use a monitoring program to adjust the balance of funds across chains to ensure sufficient assets in varying asset pools at any one time.

REST Base Endpoint:

Testnet:

https://testnet.pro.apex.exchange/api/

Mainnet:

https://pro.apex.exchange/api/

Testnet

Query path and Parameters:

Http Get Request

Please add parameters to the query path.as
https://pro.apex.exchange/api/v1/transfers?limit=100&page=1&currencyId=USDC&chainIds=1

Http Post Request

Enter order data in body, in the content-type x-www-form-urlencoded. You do not need to encode your data. as starkKey=xxx&ethAddress=yyy&chainId=zzz

Public API Endpoints (Verification Required)

publicApi

Private API Endpoints (Authentication Required)

privateApi

All requests made to private endpoints must be authenticated. The following signatures must be used for authentication:

1. ApiKey Signature

Generate apiKey

import os
import sys
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key="0x*****")
configs = client.configs()

stark_key_pair_with_y_coordinate = client.derive_stark_key(client.default_address)
nonceRes = client.generate_nonce(starkKey=stark_key_pair_with_y_coordinate['public_key'],ethAddress=client.default_address,chainId="1")

regRes = client.register_user(nonce=nonceRes['data']['nonce'],starkKey=stark_key_pair_with_y_coordinate['public_key'],stark_public_key_y_coordinate=stark_key_pair_with_y_coordinate['public_key_y_coordinate'],ethereum_address=client.default_address)

key = regRes['data']['apiKey']['key']
secret = regRes['data']['apiKey']['secret']
passphrase = regRes['data']['apiKey']['passphrase']

#back stark_key_pair, apiKey,and accountId for private Api or create-oreder or withdraw
print(stark_key_pair_with_y_coordinate)
print(regRes['data']['account']['positionId'])
print(regRes['data']['apiKey'])
import os
import sys
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key="0x*****")
configs = client.configs()

stark_key_pair_with_y_coordinate = client.derive_stark_key(client.default_address)
nonceRes = client.generate_nonce(starkKey=stark_key_pair_with_y_coordinate['public_key'],ethAddress=client.default_address,chainId="1")

regRes = client.register_user(nonce=nonceRes['data']['nonce'],starkKey=stark_key_pair_with_y_coordinate['public_key'],stark_public_key_y_coordinate=stark_key_pair_with_y_coordinate['public_key_y_coordinate'],ethereum_address=client.default_address)

key = regRes['data']['apiKey']['key']
secret = regRes['data']['apiKey']['secret']
passphrase = regRes['data']['apiKey']['passphrase']

#back stark_key_pair, apiKey,and accountId for private Api or create-oreder or withdraw
print(stark_key_pair_with_y_coordinate)
print(regRes['data']['account']['positionId'])
print(regRes['data']['apiKey'])

Sign request message by apiSecret

def sign(
        self,
        request_path,
        method,
        iso_timestamp,
        data,
):
    sortedItems=sorted(data.items(),key=lambda x:x[0],reverse=False)
    dataString = '&'.join('{key}={value}'.format(
        key=x[0], value=x[1]) for x in sortedItems if x[1] is not None)

    message_string = (
            iso_timestamp +
            method +
            request_path +
            dataString
    )

    hashed = hmac.new(
        base64.standard_b64encode(
            (self.api_key_credentials['secret']).encode(encoding='utf-8'),
        ),
        msg=message_string.encode(encoding='utf-8'),
        digestmod=hashlib.sha256,
    )
    return base64.standard_b64encode(hashed.digest()).decode()
def sign(
        self,
        request_path,
        method,
        iso_timestamp,
        data,
):
    sortedItems=sorted(data.items(),key=lambda x:x[0],reverse=False)
    dataString = '&'.join('{key}={value}'.format(
        key=x[0], value=x[1]) for x in sortedItems if x[1] is not None)

    message_string = (
            iso_timestamp +
            method +
            request_path +
            dataString
    )

    hashed = hmac.new(
        base64.standard_b64encode(
            (self.api_key_credentials['secret']).encode(encoding='utf-8'),
        ),
        msg=message_string.encode(encoding='utf-8'),
        digestmod=hashlib.sha256,
    )
    return base64.standard_b64encode(hashed.digest()).decode()
Parameter Position Type Type Comment
APEX-SIGNATURE header string true signstr
APEX-TIMESTAMP header string true request timeStamp
APEX-API-KEY header string true key
APEX-PASSPHRASE header string true passphrase

2. StarkKey Signature

Response Parameters

{  
     "code": 10002,  
     "msg": "has been expired!",  
     "data": {
       "time": 1649409187477
     },
     "key": "ORDER_NOT_CANCEL_FILLED", 
     "detail":{  
        "orderId":"1234556"  
     }
}  

Client_id and Nonce Generation

When creating order and withdrawal requests, you will need to send a unique and randomly generated client_Id to server. You can refer to python codes:

def random_client_id():
   return str(int(float(str(random.random())[2:])))
def random_client_id():
   return str(int(float(str(random.random())[2:])))

When utilizing starkKey signatures in creating order and withdrawal requests, you will need to change client_Id to nonce in the server. Refer to python codes for the algorithm:

def nonce_from_client_id(client_id):
    message = hashlib.sha256()
    message.update(client_id.encode())  # Encode as UTF-8.
    return int(message.digest().hex()[0:8], 16)
def nonce_from_client_id(client_id):
    """Generate a nonce deterministically from an arbitrary string."""
    message = hashlib.sha256()
    message.update(client_id.encode())  # Encode as UTF-8.
    return int(message.digest().hex()[0:8], 16)

Rate Limits

IP Rate Limit

If you receive a HTTP 403 (Access Denied) response, your IP has been either temporarily or permanently banned. You should immediately review the below guidelines to ensure that your application does not continue to violate the limit.

Limit Comment
Limit 150,00 requests per 300 secs Per IP

API Rate Limit

Rate Limits for All Private Endpoints Per Account

Limit Comment
80 requests per 60 secs POST request
3,000 requests per 60 secs GET request

Orders Limit

Rate Limits for Creating Orders

Limit Comment
200 orders Per user

Margin

Margin required for each single position:

initialMargin = abs(Size * Oracle Price* initialMarginRate)
maintenanceMargin = abs(Size * Oracle Price* maintenanceMarginRate)

Margin required by all positions under all contract types under your account:

total initialMargin = Σ abs(Size * Oracle Price* initialMarginRate)
total maintenanceMargin = Σ abs(Size * Oracle Price* maintenanceMarginRate)

TotalAccountValue =Q+Σ abs(Size*Oracle Price)

where Q is the USDC balance in your account.

Liquidation

When the net equity of the account falls below the maintenance margin required, your position will be taken over by the liquidation engine and liquidated.

Deleverage

Funding Fee

Funding fees will be exchanged between long and short position holders every 1 hour.
Please note that the funding rate will fluctuate in real time every 1 hour. If the funding rate is positive upon settlement, long position holders will pay the funding fees to short position holders. Similarly, when the funding rate is negative, short positive holders will pay long position holders.

Funding Fees = Position Value * Index Price * Funding Rate

Oracle Price

ApeX Pro utilizes Oracle Price in the following case(s):

ApeX Pro pulls Oracle Price data from Stork, which is an oracle solution native to StarkNet and StarkEx. Stork will provide the price datapoint for ApeX Pro to determine the Liquidation Price.

Index Price

ApeX Pro utilizes Index Price in the following case(s): - Profits and Losses - Funding Fees

Index Price is the sum of prices pulled from multiple crypto spot exchanges, then calculated based on weighted average. It is also used to derive funding fees.
If the exchange's settlement token is not in USDC, e.g. In BTC-USDT, the exchange rate between USDC and USDT will be calculated as well.

exchange symbol weight
Binance BTC-USDT 1/6
CoinbasePro BTC-USD 1/6
FTX BTC-USD 1/6
OKEX BTC-USDT 1/6
Gemini BTC-USD 1/6
Kraken BTC-USD 1/6
exchange symbol weight
Binance ETH-USDT 1/6
CoinbasePro ETH-USD 1/6
FTX ETH-USD 1/6
OKEX ETH-USDT 1/6
Gemini ETH-USD 1/6
Kraken ETH-USD 1/6

Symbols Configs

name value
Min ticker price 0.5
Min step size 0.001
Min Order size 0.001
Max Order size 100
Max Position size 500
InitialMarginRate 0.05
MaintenanceMarginRate 0.03
Baseline position value 1000000
incrementalPositionValue 1000000
incrementalInitialMarginRate 0.0075
fundingInterestRate 0.0003
Max fundingInterestRate 0.00046875,-0.00046875
name value
Min ticker price 0.05
Min step size 0.01
Min Order size 0.01
Max Order size 1000
Max Position size 10000
InitialMarginRate 0.05
MaintenanceMarginRate 0.03
Baseline position value 1000000
incrementalPositionValue 1000000
incrementalInitialMarginRate 0.0075
fundingInterestRate 0.0003
Max fundingInterestRate 0.00046875,-0.00046875

V2 or V1

ApeX OpenAPI V2 now supports USDT currency pairs! Users can seamlessly manage USDT and USDC accounts, handle deposits and withdrawals, and meet all their currency pair trading needs through V2 APIs. Additionally, V2 adheres to the standards set by V1 for a consistent experience.

Current API Coverage

OpenAPI USDT Account USDC Account USDT Perp USDC Perp Quote USDT Deposit USDC Deposit
V1 NO YES NO YES YES NO YES
V2 YES YES YES YES YES YES NO

warning
Please note, the USDT account and USDC account are independent. Assets and positions are not shared, and deposits and withdrawals are processed separately.
To start trading USDT perpetual contract currency pairs, it is necessary to request V2 onboarding and register a USDT account.

sdk-v2

  1. The client initialization methods in v1 and v2 remain the same. For example:
client = HttpPrivate(APEX_HTTP_TEST, network_id=NETWORKID_TEST, eth_private_key=priKey)
client = HttpPublic(APEX_HTTP_MAIN)
  1. If the method names in v1 and v2 are identical, it indicates that the implementation logic in v1 and v2 has not changed, and the path supports HTTP requests for both v1 and v2. For example:
client = HttpPublic(APEX_HTTP_MAIN)   
print(client.klines(symbol="ETHUSDT",interval=5,start=1681463600, end=1681563600, limit=5))    
print(client.depth(symbol="BTC-USDC"))   
  1. If the method names in v1 and v2 differ, it signifies a change in the implementation logic between v1 and v2, and the request paths also differ. Request methods are distinguished by v2 and v1. For example:
client = HttpPrivate(APEX_HTTP_TEST, network_id=NETWORKID_TEST, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})    
configs = client.configs_v2()    
accountRes = client.get_account_v2()   
print(accountRes)   

PublicApi_V2

v2.0.0

GET System Time V2

GET /v2/time

from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.server_time()
curl "https://pro.apex.exchange/api/v2/time" 

Successful Response

{
  "data": {
    "time": 1648626529
  }
}

Response Status Code

Status Code Value Comment Data Model
200 OK Success Inline

Response Parameters

status code 200

Parameter Type Required Limit Comment
» time integer true none none

GET All Config Data V2

USDC and USDT config

GET /v2/symbols

from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.configs_v2()
curl "https://pro.apex.exchange/api/v2/symbols" 

Successful Response

{
  "data": {
    "usdcConfig": {
      "currency": [
        {
          "id": "USDC",
          "starkExAssetId": "0x02893294412a4c8f915f75892b395ebbf6859ec246ec365c3b1f56f47c3a0a5d",
          "starkExResolution": "1000000",
          "stepSize": "0.000001",
          "showStep": "0.0001",
          "iconUrl": "https://static-pro.apex.exchange/icon/USDC.svg"
        },
        {
          "id": "BTC",
          "starkExAssetId": "",
          "starkExResolution": "",
          "stepSize": "0.001",
          "showStep": "",
          "iconUrl": "https://static-pro.apex.exchange/icon/BTC.svg"
        },
        {
          "id": "ETH",
          "starkExAssetId": "",
          "starkExResolution": "",
          "stepSize": "0.01",
          "showStep": "",
          "iconUrl": "https://static-pro.apex.exchange/icon/ETH.svg"
        }
      ],
      "global": {
        "feeAccountId": "10240000",
        "feeAccountL2Key": "0x02382ceace17a59ec674b5ca7109eabc66e4107c7f473492cf192c60f4e17600",
        "starkExCollateralCurrencyId": "USDC",
        "starkExFundingValidityPeriod": 86400,
        "starkExMaxFundingRate": "2237",
        "starkExOrdersTreeHeight": 64,
        "starkExPositionsTreeHeight": 0,
        "starkExPriceValidityPeriod": 86400,
        "starkExContractAddress": "0xA1D5443F2FB80A5A55ac804C948B45ce4C52DCbb",
        "registerEnvId": 1,
        "crossChainAccountId": "351667704786059600",
        "crossChainL2Key": "0x0270884a62b952837f1ad48bf28559c86060990af3e63019da59dad9cdd76ed0",
        "fastWithdrawAccountId": "351667704786059600",
        "fastWithdrawFactRegisterAddress": "0xBE9a129909EbCb954bC065536D2bfAfBd170d27A",
        "fastWithdrawL2Key": "0x0270884a62b952837f1ad48bf28559c86060990af3e63019da59dad9cdd76ed0",
        "fastWithdrawMaxAmount": "100000",
        "bybitWithdrawAccountId": "386890783493456500",
        "bybitWithdrawL2Key": "0x03a30ed5c0184757effbbc1df3921da538e514e289f342751333340d90962cf4",
        "experienceMonenyAccountId": "431772213377499661",
        "experienceMonenyL2Key": "0x0577cf53e44275b3dfdfdfde1639752e35fff0cc6c2919b9389f087e87b16a8d",
        "experienceMoneyAccountId": "431772213377499661",
        "experienceMoneyL2Key": "0x0577cf53e44275b3dfdfdfde1639752e35fff0cc6c2919b9389f087e87b16a8d"
      },
      "perpetualContract": [
        {
          "baselinePositionValue": "50000.0000",
          "crossId": 30000,
          "crossSymbolId": 10,
          "crossSymbolName": "BTCUSDC",
          "digitMerge": "0.5,1,2,5,10",
          "displayMaxLeverage": "30",
          "displayMinLeverage": "1",
          "enableDisplay": true,
          "enableOpenPosition": true,
          "enableTrade": true,
          "fundingImpactMarginNotional": "10",
          "fundingInterestRate": "0.0003",
          "incrementalInitialMarginRate": "0.00250",
          "incrementalMaintenanceMarginRate": "0.00100",
          "incrementalPositionValue": "200000.0000",
          "initialMarginRate": "0.03333",
          "maintenanceMarginRate": "0.00700",
          "maxOrderSize": "100",
          "maxPositionSize": "130",
          "minOrderSize": "0.0010",
          "maxMarketPriceRange": "0.025",
          "settleCurrencyId": "USDC",
          "starkExOraclePriceQuorum": "1",
          "starkExResolution": "10000000000",
          "starkExRiskFactor": "128849019",
          "starkExSyntheticAssetId": "0x4254432d3130000000000000000000",
          "stepSize": "0.001",
          "symbol": "BTC-USDC",
          "symbolDisplayName": "BTCUSDC",
          "symbolDisplayName2": "BTCUSD",
          "tickSize": "0.5",
          "underlyingCurrencyId": "BTC",
          "maxMaintenanceMarginRate": "0.03000",
          "maxPositionValue": "10050000.0000",
          "tagIconUrl": "",
          "tag": "",
          "riskTip": false,
          "defaultLeverage": "",
          "klineStartTime": 0
        }
      ],
      "multiChain": {
        "chains": [
          {
            "chain": "Ethereum",
            "chainId": 1,
            "chainIconUrl": "https://static-pro.apex.exchange/chains/chain_logos/Ethereum.svg",
            "contractAddress": "0xe95b3Dc78c0881dEa17A69BaFC6cFeB8d891e9DE",
            "depositGasFeeLess": false,
            "stopDeposit": false,
            "feeLess": false,
            "feeRate": "0.0001",
            "gasLess": false,
            "gasToken": "ETH",
            "minFee": "1",
            "dynamicFee": true,
            "rpcUrl": "https://eth-mainnet.alchemyapi.io/v2/sNRPO_qXIfkVdfpcj33LId04rmHugka2",
            "webRpcUrl": "https://eth-mainnet.alchemyapi.io/v2/sNRPO_qXIfkVdfpcj33LId04rmHugka2",
            "webTxUrl": "https://etherscan.io/tx/",
            "blockTime": "15",
            "txConfirm": 15,
            "tokens": [
              {
                "decimals": 6,
                "iconUrl": "https://static-pro.apex.exchange/icon/USDC.svg",
                "token": "USDC",
                "tokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
                "pullOff": false,
                "withdrawEnable": true,
                "slippage": "",
                "isDefaultToken": true,
                "displayToken": "USDC"
              },
              {
                "decimals": 6,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Ethereum/Ethereum_USDT.svg",
                "token": "USDT",
                "tokenAddress": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "1",
                "isDefaultToken": false,
                "displayToken": "USDT"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Ethereum/Ethereum_ETH.svg",
                "token": "ETH",
                "tokenAddress": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "ETH"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Ethereum/Ethereum_DAI.svg",
                "token": "DAI",
                "tokenAddress": "0x6b175474e89094c44da98b954eedeac495271d0f",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "DAI"
              }
            ],
            "withdrawGasFeeLess": false,
            "isGray": false
          },
          {
            "chain": "BNB Chain(BSC)",
            "chainId": 56,
            "chainIconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_BNB.svg",
            "contractAddress": "0xe29304Af265641a49F55294F7E5BA5010ebA4497",
            "depositGasFeeLess": false,
            "stopDeposit": false,
            "feeLess": false,
            "feeRate": "0.0001",
            "gasLess": true,
            "gasToken": "BNB",
            "minFee": "1",
            "dynamicFee": false,
            "rpcUrl": "https://bsc-dataseed3.binance.org",
            "webRpcUrl": "https://bsc-dataseed3.binance.org",
            "webTxUrl": "https://bscscan.com/tx/",
            "blockTime": "3",
            "txConfirm": 15,
            "tokens": [
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_USDC.svg",
                "token": "USDC",
                "tokenAddress": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                "pullOff": false,
                "withdrawEnable": true,
                "slippage": "",
                "isDefaultToken": true,
                "displayToken": "USDC"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_USDT.svg",
                "token": "USDT",
                "tokenAddress": "0x55d398326f99059fF775485246999027B3197955",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "1",
                "isDefaultToken": false,
                "displayToken": "USDT"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_BNB.svg",
                "token": "BNB",
                "tokenAddress": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "BNB"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_BUSD.svg",
                "token": "BUSD",
                "tokenAddress": "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "BUSD"
              }
            ],
            "withdrawGasFeeLess": false,
            "isGray": false
          }
        ],
        "currency": "USDC",
        "maxWithdraw": "100000",
        "minDeposit": "10",
        "minWithdraw": "8"
      },
      "depositFromBybit": false
    },
    "usdtConfig": {
      "currency": [
        {
          "id": "USDT",
          "starkExAssetId": "0x02ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5",
          "starkExResolution": "1000000",
          "stepSize": "0.000001",
          "showStep": "0.0001",
          "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Ethereum/Ethereum_USDT.svg"
        },
        {
          "id": "BTC",
          "starkExAssetId": "",
          "starkExResolution": "",
          "stepSize": "0.001",
          "showStep": "",
          "iconUrl": "https://static-pro.apex.exchange/icon/BTC.svg"
        },
        {
          "id": "ETH",
          "starkExAssetId": "",
          "starkExResolution": "",
          "stepSize": "0.01",
          "showStep": "",
          "iconUrl": "https://static-pro.apex.exchange/icon/ETH.svg"
        }
      ],
      "global": {
        "feeAccountId": "10240000",
        "feeAccountL2Key": "0x02382ceace17a59ec674b5ca7109eabc66e4107c7f473492cf192c60f4e17600",
        "starkExCollateralCurrencyId": "USDT",
        "starkExFundingValidityPeriod": 86400,
        "starkExMaxFundingRate": "2237",
        "starkExOrdersTreeHeight": 64,
        "starkExPositionsTreeHeight": 0,
        "starkExPriceValidityPeriod": 86400,
        "starkExContractAddress": "0xe53A6eD882Eb3f90cCe0390DDB04c876C5482E6b",
        "registerEnvId": 1,
        "crossChainAccountId": "503102754309276028",
        "crossChainL2Key": "0x05dc82afffe0311f532b3ee86fbf5491fc4be1a3e7a204a37e69416999f00dfc",
        "fastWithdrawAccountId": "503102754309276028",
        "fastWithdrawFactRegisterAddress": "0xBE9a129909EbCb954bC065536D2bfAfBd170d27A",
        "fastWithdrawL2Key": "0x05dc82afffe0311f532b3ee86fbf5491fc4be1a3e7a204a37e69416999f00dfc",
        "fastWithdrawMaxAmount": "100000",
        "bybitWithdrawAccountId": "",
        "bybitWithdrawL2Key": "",
        "experienceMonenyAccountId": "503102758994313516",
        "experienceMonenyL2Key": "0x01402668ab56fef0c44ec9d0569f2706f08caa4bc29ee2eb2f9376d86bc5adac",
        "experienceMoneyAccountId": "503102758994313516",
        "experienceMoneyL2Key": "0x01402668ab56fef0c44ec9d0569f2706f08caa4bc29ee2eb2f9376d86bc5adac"
      },
      "perpetualContract": [
        {
          "baselinePositionValue": "50000.0000",
          "crossId": 30001,
          "crossSymbolId": 34,
          "crossSymbolName": "BTCUSDT",
          "digitMerge": "0.1,0.2,0.4,1,2",
          "displayMaxLeverage": "50",
          "displayMinLeverage": "1",
          "enableDisplay": false,
          "enableOpenPosition": true,
          "enableTrade": true,
          "fundingImpactMarginNotional": "10",
          "fundingInterestRate": "0.0003",
          "incrementalInitialMarginRate": "0.0075",
          "incrementalMaintenanceMarginRate": "0.005",
          "incrementalPositionValue": "150000.0000",
          "initialMarginRate": "0.02",
          "maintenanceMarginRate": "0.01",
          "maxOrderSize": "100",
          "maxPositionSize": "130",
          "minOrderSize": "0.0010",
          "maxMarketPriceRange": "0.025",
          "settleCurrencyId": "USDT",
          "starkExOraclePriceQuorum": "3",
          "starkExResolution": "10000000000",
          "starkExRiskFactor": "1417339208",
          "starkExSyntheticAssetId": "0x4254432d3130000000000000000000",
          "stepSize": "0.001",
          "symbol": "BTC-USDT",
          "symbolDisplayName": "BTCUSDT",
          "symbolDisplayName2": "BTCUSDT",
          "tickSize": "0.1",
          "underlyingCurrencyId": "BTC",
          "maxMaintenanceMarginRate": "0.3300",
          "maxPositionValue": "9650000",
          "tagIconUrl": "https://static-pro.apex.exchange/icon/LABLE_HOT.svg",
          "tag": "HOT",
          "riskTip": false,
          "defaultLeverage": "",
          "klineStartTime": 0
        },
        {
          "baselinePositionValue": "50000.0000",
          "crossId": 30001,
          "crossSymbolId": 35,
          "crossSymbolName": "ETHUSDT",
          "digitMerge": "0.01,0.02,0.04,0.1,0.2",
          "displayMaxLeverage": "50",
          "displayMinLeverage": "1",
          "enableDisplay": false,
          "enableOpenPosition": true,
          "enableTrade": true,
          "fundingImpactMarginNotional": "100",
          "fundingInterestRate": "0.0003",
          "incrementalInitialMarginRate": "0.0075",
          "incrementalMaintenanceMarginRate": "0.005",
          "incrementalPositionValue": "150000.0000",
          "initialMarginRate": "0.02",
          "maintenanceMarginRate": "0.01",
          "maxOrderSize": "800",
          "maxPositionSize": "1700",
          "minOrderSize": "0.010",
          "maxMarketPriceRange": "0.045",
          "settleCurrencyId": "USDT",
          "starkExOraclePriceQuorum": "3",
          "starkExResolution": "100000000",
          "starkExRiskFactor": "1417339208",
          "starkExSyntheticAssetId": "0x4554482d3800000000000000000000",
          "stepSize": "0.01",
          "symbol": "ETH-USDT",
          "symbolDisplayName": "ETHUSDT",
          "symbolDisplayName2": "ETHUSDT",
          "tickSize": "0.01",
          "underlyingCurrencyId": "ETH",
          "maxMaintenanceMarginRate": "0.3300",
          "maxPositionValue": "9650000",
          "tagIconUrl": "https://static-pro.apex.exchange/icon/LABLE_HOT.svg",
          "tag": "HOT",
          "riskTip": false,
          "defaultLeverage": "",
          "klineStartTime": 0
        }
      ],
      "multiChain": {
        "chains": [
          {
            "chain": "Ethereum",
            "chainId": 1,
            "chainIconUrl": "https://static-pro.apex.exchange/chains/chain_logos/Ethereum.svg",
            "contractAddress": "0x379c15156B527D6E693bED60d1FBb44CE46046b8",
            "depositGasFeeLess": false,
            "stopDeposit": false,
            "feeLess": false,
            "feeRate": "0.0001",
            "gasLess": false,
            "gasToken": "ETH",
            "minFee": "1",
            "dynamicFee": true,
            "rpcUrl": "https://eth-mainnet.alchemyapi.io/v2/sNRPO_qXIfkVdfpcj33LId04rmHugka2",
            "webRpcUrl": "https://eth-mainnet.alchemyapi.io/v2/sNRPO_qXIfkVdfpcj33LId04rmHugka2",
            "webTxUrl": "https://etherscan.io/tx/",
            "blockTime": "15",
            "txConfirm": 15,
            "tokens": [
              {
                "decimals": 6,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Ethereum/Ethereum_USDT.svg",
                "token": "USDT",
                "tokenAddress": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
                "pullOff": false,
                "withdrawEnable": true,
                "slippage": "",
                "isDefaultToken": true,
                "displayToken": "USDT"
              },
              {
                "decimals": 6,
                "iconUrl": "https://static-pro.apex.exchange/icon/USDC.svg",
                "token": "USDC",
                "tokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "USDC"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Ethereum/Ethereum_ETH.svg",
                "token": "ETH",
                "tokenAddress": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "ETH"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Ethereum/Ethereum_DAI.svg",
                "token": "DAI",
                "tokenAddress": "0x6b175474e89094c44da98b954eedeac495271d0f",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "DAI"
              }
            ],
            "withdrawGasFeeLess": false,
            "isGray": false
          },
          {
            "chain": "BNB Chain(BSC)",
            "chainId": 56,
            "chainIconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_BNB.svg",
            "contractAddress": "0x7B71Ff8451706B9e863879a84bf967Ff4Dc7A9bF",
            "depositGasFeeLess": false,
            "stopDeposit": false,
            "feeLess": false,
            "feeRate": "0.0001",
            "gasLess": true,
            "gasToken": "BNB",
            "minFee": "1",
            "dynamicFee": false,
            "rpcUrl": "https://bsc-dataseed3.binance.org",
            "webRpcUrl": "https://bsc-dataseed3.binance.org",
            "webTxUrl": "https://bscscan.com/tx/",
            "blockTime": "3",
            "txConfirm": 15,
            "tokens": [
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_USDT.svg",
                "token": "USDT",
                "tokenAddress": "0x55d398326f99059fF775485246999027B3197955",
                "pullOff": false,
                "withdrawEnable": true,
                "slippage": "",
                "isDefaultToken": true,
                "displayToken": "USDT"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_USDC.svg",
                "token": "USDC",
                "tokenAddress": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "USDC"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_BNB.svg",
                "token": "BNB",
                "tokenAddress": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "BNB"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/BSC/BNB_BUSD.svg",
                "token": "BUSD",
                "tokenAddress": "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "BUSD"
              }
            ],
            "withdrawGasFeeLess": false,
            "isGray": false
          },
          {
            "chain": "Arbitrum One",
            "chainId": 42161,
            "chainIconUrl": "https://static-pro.apex.exchange/chains/chain_logos/Arbitrum.svg",
            "contractAddress": "0x192DB9Fe1C0b9D7c6B4045e4F029b21792c68165",
            "depositGasFeeLess": false,
            "stopDeposit": false,
            "feeLess": true,
            "feeRate": "0.0001",
            "gasLess": true,
            "gasToken": "ETH",
            "minFee": "2",
            "dynamicFee": false,
            "rpcUrl": "https://arb1.arbitrum.io/rpc",
            "webRpcUrl": "https://arb1.arbitrum.io/rpc",
            "webTxUrl": "https://arbiscan.io/tx/",
            "blockTime": "1",
            "txConfirm": 12,
            "tokens": [
              {
                "decimals": 6,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Arbitrum/Arbitrum_USDT.svg",
                "token": "USDT",
                "tokenAddress": "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
                "pullOff": false,
                "withdrawEnable": true,
                "slippage": "",
                "isDefaultToken": true,
                "displayToken": "USDT"
              },
              {
                "decimals": 6,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Arbitrum/Arbitrum_USDC.svg",
                "token": "USDC",
                "tokenAddress": "0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "USDC.e"
              },
              {
                "decimals": 6,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Arbitrum/Arbitrum_USDC.svg",
                "token": "USDC.o",
                "tokenAddress": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "USDC"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Arbitrum/Arbitrum_ETH.svg",
                "token": "ETH",
                "tokenAddress": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "ETH"
              },
              {
                "decimals": 18,
                "iconUrl": "https://static-pro.apex.exchange/chains/chain_tokens/Arbitrum/Arbitrum_WETH.svg",
                "token": "WETH",
                "tokenAddress": "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
                "pullOff": false,
                "withdrawEnable": false,
                "slippage": "",
                "isDefaultToken": false,
                "displayToken": "WETH"
              }
            ],
            "withdrawGasFeeLess": false,
            "isGray": false
          }
        ],
        "currency": "USDT",
        "maxWithdraw": "10000",
        "minDeposit": "10",
        "minWithdraw": "8"
      },
    }
  },
  "timeCost": 1416146
}

Response Status Code

Status Code Value Comment Data Model
200 OK success Inline

Response Parameters

status code 200

Parameter type required limit comment
» global object true none none
»» feeAccountId string true none Trading fee system account id
»» feeAccountL2Key string true none Trading fee system l2Key
»» starkExCollateralCurrencyId string true none Starkex supported collateral asset id
»» starkExMaxFundingRate string true none Maximum funding rate
»» starkExOrdersTreeHeight integer true none Order merkle tree height
»» starkExPositionsTreeHeight integer true none Account merkle tree height
»» starkExFundingValidityPeriod integer true none L2 funding validity period
»» starkExPriceValidityPeriod integer true none L2 price validity period
»» fastWithdrawAccountId string true none Fast withdraw system account id
»» fastWithdrawL2Key string true none Fast withdraw system l2Key
»» fastWithdrawMaxAmount string true none Maximum Fast withdraw amount
»» fastWithdrawFactRegisterAddress string true none L1 Fact registered contract address
»» crossChainAccountId string true none Cross chain withdraw account id
»» crossChainL2Key string true none Cross chain withdraw system l2Key
»» registerChainId integer true 5 The 'envId' is initially filled during onboarding, serving to differentiate environments, with 1 indicating the production environment and 5 representing testing environments.
» currency [object] true none none
»» id string true none Token name
»» stepSize string true none Minimum step size
»» starkExAssetId string false none StarkEx asset id
»» starkExResolution string false none StarkEx resolution
» multiChain object true none none
»» maxWithdraw string true none Maximum withdrawal amount
»» minWithdraw string true none Minimum withdrawal amount
»» minDeposit string true none Minimum deposit amount
»» currency string true USDC Currency
»» chains [object] true none none
»»» chain string true none Chain
»»» contractAddress string true none Contract address
»»» chainIconUrl string true none Chain icon url
»»» gasToken string true none Gas token name
»»» rpcUrl string true none Chain RPC service Url
»»» chainId integer true none Chain ID
»»» feeLess boolean true none Enable trading fees
»»» depositGasFeeLess boolean false none Enable deposit gas fees
»»» withdrawGasFeeLess boolean false none Enable withdraw gas fees
»»» minFee string true none Minimum deposit gas fee: If gas+value*fee_rate is lesser than min_fee, min_fee amount will be charged instead
»»» feeRate string true none Fee rate
»»» webTxUrl string true none Transaction tx URL
»»» tokens [object] true none none
»»»» token string true none Token name
»»»» tokenAddress string true none Token address
»»»» decimals integer true none Token decimal point accuracy
»»»» iconUrl string true none Token icon URL
»»»» pullOff bool true none Enable taking down of listing, default as FALSE
»»» gasLess boolean true none Enable gas free transaction
» perpetualContract [object] true none none
»» symbol string true none Symbol id
»» symbolDisplayName string true none Symbol display name
»» settleCurrencyId string true none Settlement asset id
»» underlyingCurrencyId string true none Underlying asset id
»» tickSize string true none Minimum tick size
»» stepSize string true none Minimum step size
»» minOrderSize string true none Minimum order size
»» maxOrderSize string true none Maximum order size
»» maxPositionSize string true none Maximum position size
»» maxMarketPriceRange string true none Maximum market price rangee
»» initialMarginRate string true none Initial margin rate
»» maintenanceMarginRate string true none Maintenance margin rate
»» baselinePositionValue string true none Baseline position vaue
»» incrementalPositionValue string true none Incremental position value
»» incrementalInitialMarginRate string true none Incremental initial margin rate
»» incrementalMaintenanceMarginRate string true none Incremental maintenance margin rate
»» enableTrade boolean true none Enable trade
»» enableDisplay boolean true none Enable display
»» enableOpenPosition boolean true none Enable open position
»» digitMerge string true none Depth digit merge
»» crossId integer true none Quote API use id for symbol
»» crossSymbolId integer true none Quote API use symbolId for symbol
»» crossSymbolName string true none Quote API use symbolName for symbol
»» fundingInterestRate string true none Funding rate ratio
»» fundingImpactMarginNotional string true none Not required on frontend
»» displayMaxLeverage string true none Maximum leverage
»» displayMinLeverage string true none Minimum leverage
»» starkExSyntheticAssetId string true none Currency synthetic asset id
»» starkExResolution string true none Currency resolution
»» starkExRiskFactor string true none none
»» starkExOraclePriceQuorum string true none none

GET Market Depth V2

GET /v2/depth

Retrieve all active orderbook for one symbol, inclue all bids and asks.

Request Parameters

Parameter Position Type Required Comment
symbol query string true use crossSymbolName responded from All Config Data
limit query string false Default at 100
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.depth(symbol="BTCUSDC")
curl "https://pro.apex.exchange/api/v2/depth?symbol=BTCUSDC" 

Successful Response Generation

success

{
  "data": [
    {
      "a": [
        [
          "6250",
          "0.01"
        ],
        [
          "6300",
          "0.01"
        ]
      ],
      "b": [
        [
          "1520",
          "0.02"
        ],
        [
          "1535",
          "0.01"
        ]
      ],
      "s": "BTCUSDC",
      "u": 103681
    }
  ]
}

Response Status Code

Status Code Value Comment Data Model
200 OK success Inline

Response Parameters

status code 200

Parameter Type Required Limit Comment
» data [object] true none none
»» a [array] false none Sell
»» b [array] false none Buy
»» s string false none Symbol
»» u integer false none none

GET Newest Trading Data V2

GET /v2/trades

Retrieve trading data.

Request Parameters

Parameter Position type required comment
symbol query string true use crossSymbolName responded from All Config Data
limit query string false Limit
from query string false Return to latest data as default
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.trades(symbol="BTCUSDT")
curl "https://pro.apex.exchange/api/v2/trades?symbol=BTCUSDT" 

Successful Response Generation

success

{
  "data": [
    {
      "S": "BUY",
      "v": "0.001",
      "p": "29000",
      "s": "BTCUSDT",
      "T": 1647502440973
    }
  ]
}

Response Status Code

Status Code Value Comment Data Model
200 OK success Inline

Response Parameters

status code 200

Parameter Type Required Limit Comment
» data [object] true none none
»» S string false none Side
»» v string false none Size
»» p string false none Price
»» s string false none Symbol
»» T integer false none Trade time

GET Candlestick Chart Data V2

GET /v2/klines

Retrieves all candlestick chart data.
Candlestick chart time indicators: Numbers represent minutes, D for Days, M for Month and W for Week — 1 5 15 30 60 120 240 360 720 "D" "M" "W"

Request Parameters

Parameter Position Type Required Comment
interval query string false Candlestick chart time indicators: Numbers represent minutes, D for Days, M for Month and W for Week — 1 5 15 30 60 120 240 360 720 "D" "M" "W"
start query string false Start time
end query string false End time
limit query string false Limit
symbol query string false use crossSymbolName responded from All Config Data
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.klines(symbol="BTCUSDC",interval=5)
curl "https://pro.apex.exchange/api/v2/klines?symbol=BTCUSDC?interval=5" 

Successful Response Generation

success

{
  "data": [
    {
      "start": 1647511440000,
      "symbol": "BTCUSDC",
      "interval": "1",
      "low": "40000",
      "high": "45000",
      "open": "45000",
      "close": "40000",
      "volume": "1.002",
      "turnover": "3"
    }
  ]
}

Response Status Code

Status Code Value Comment Data Model
200 OK success Inline

Response Parameters

status code 200

Parameter Type Required Limit Comment
» klines [object] true none none
»» start integer false none Start time
»» symbol string true none Currency
»» interval string true none Chart interval
»» low string false none Low price
»» high string false none High price
»» open string false none Open price
»» close string false none Close price
»» volume string false none Trading volume
»» turnover string false none Turnover

GET Ticker Data V2

GET /v2/ticker

Get the latest data on symbol tickers.

Request Parameters

Parameter Position Type Required Comment
symbol query string true use crossSymbolName responded from All Config Data
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.ticker(symbol="BTCUSDC")
curl "https://pro.apex.exchange/api/v2/ticker?symbol=BTCUSDC" 

Successful Response Generation

success

{
  "data": [
    {
      "symbol": "BTCUSDC",
      "price24hPcnt": "0.450141",
      "lastPrice": "43511.50",
      "highPrice24h": "43513.50",
      "lowPrice24h": "29996.00",
      "oraclePrice": "43513.50",
      "indexPrice": "40828.94",
      "openInterest": "2036854775808",
      "turnover24h": "5626085.23749999",
      "volume24h": "169.317",
      "fundingRate": "0",
      "predictedFundingRate": "0",
      "nextFundingTime": "10:00:00",
      "tradeCount": 100
    }
  ]
}

Response Status Code

Status Code Value Comment Data Model
200 OK success Inline

Response Parameters

status code 200

Parameter Type Required Limit Comment
» tickers [object] true none none
»» symbol string false none Symbol
»» price24hPcnt string false none 24H change (%)
»» lastPrice string false none Last price
»» highPrice24h string false none 24H highest price
»» lowPrice24h string false none 24H lowest price
»» oraclePrice string false none Oracle price
»» indexPrice string false none Index price
»» openInterest string false none Open interest
»» turnover24h string false none 24H turnover
»» volume24h string false none 24H trading volume
»» fundingRate string false none Funding rate
»» predictedFundingRate string false none Predicted funding rate
»» nextFundingTime string false none Next funding rate
»» tradeCount string false none 24H trade count

GET Funding Rate History V2

GET /v2/history-funding

Request Parameters

Parameter Position Type Required Comment
symbol query string true use crossSymbolName responded from All Config Data
Limit query string false Default at 100
beginTimeInclusive query string false Start time
endTimeExclusive query string false End time
page query string false Page numbers start from 0
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.history_funding_v2(symbol="BTC-USDT")
curl "https://pro.apex.exchange/api/v2/history-funding?symbol=BTC-USDT" 

Successful Response Generation

success

{
  "historyFunds": [
    {
      "symbol": "BTC-USDT",
      "rate": "0.0000125000",
      "price": "31297.5000008009374142",
      "fundingTime": 12315555,
      "fundingTimestamp": 12315555
    }
  ],
  "totalSize": 11
}

Response Status Code

Status Code Value Comment Data Model
200 OK success Inline

Response Parameters

status code 200

Parameter Type Required Limit Comment
» historicalFunds [object] true none none
»» symbol string false none none
»» rate string false none Funding rate
»» price string false none Price
»» fundingTime integer false none Time
»» fundingTimestamp integer false none Funding timestamp
» totalSize integer true none Size

GET Check If User Exists V2

GET /v2/check-user-exist

Request Parameters

Parameter Position type required comment
ethAddress query string FALSE 0x111111

Successful Response Generation

success

{
  "data": false
}

Response Status Code

Status Code Value Comment Data Model
200 OK success Inline

Response Parameters

status code 200

Parameter Type Required Limit Comment
» data boolean true none none

PublicApi

v1.0.0

GET System Time

GET /v1/time

from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.server_time()
curl "https://pro.apex.exchange/api/v1/time" 

Successful Response

{
  "data": {
    "time": 1648626529
  }
}

Response Status Code

status code value comment data model
200 OK Success Inline

Response Parameters

status code 200

Parameter type required limit comment
» time integer true none none

GET All Config Data

GET /v1/symbols

from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.configs()
curl "https://pro.apex.exchange/api/v1/symbols" 

Successful Response

{
  "data": {
    "currency": [
      {
        "id": "USDC",
        "starkExAssetId": "0xa21edc9d9997b1b1956f542fe95922518a9e28ace11b7b2972a1974bf5971f",
        "starkExResolution": "1000000",
        "stepSize": "0.000001",
        "showStep": "0.0001",
        "iconUrl": "https://l2dex-image-static.dev.apexplus.exchange/icon/USDC.svg"
      },
      {
        "id": "BTC",
        "starkExAssetId": "",
        "starkExResolution": "",
        "stepSize": "0.0001",
        "showStep": "",
        "iconUrl": "https://l2dex-image-static.dev.apexplus.exchange/icon/BTC.svg"
      },

    ],
    "global": {
      "feeAccountId": "10240000",
      "feeAccountL2Key": "0x05d08ae9202f9e19ffa0211676536ba3e4c5f1e433a4c01d60fceae00a095100",
      "starkExCollateralCurrencyId": "USDC",
      "starkExFundingValidityPeriod": 604800,
      "starkExMaxFundingRate": "1120",
      "starkExOrdersTreeHeight": 64,
      "starkExPositionsTreeHeight": 0,
      "starkExPriceValidityPeriod": 31536000,
      "starkExContractAddress": "0x7478037C3a1F44f0Add4Ae06158fefD10d44Bb63",
      "registerEnvId": 5,
      "crossChainAccountId": "349914288015540743",
      "crossChainL2Key": "0x0486880561f5ddb979c92dcd4eefdedeb050bc5aad3522b00b211855f3c2ca87",
      "fastWithdrawAccountId": "349914288015540743",
      "fastWithdrawFactRegisterAddress": "0x5070F5d37419AEAd10Df2252421e457336561269",
      "fastWithdrawL2Key": "0x0486880561f5ddb979c92dcd4eefdedeb050bc5aad3522b00b211855f3c2ca87",
      "fastWithdrawMaxAmount": "100000"
    },
    "perpetualContract": [
      {
        "baselinePositionValue": "1000000.0000",
        "crossId": 30000,
        "crossSymbolId": 10,
        "crossSymbolName": "BTCUSDC",
        "digitMerge": "0.5,1,2,5",
        "displayMaxLeverage": "20",
        "displayMinLeverage": "1",
        "enableDisplay": true,
        "enableOpenPosition": true,
        "enableTrade": true,
        "fundingImpactMarginNotional": "10",
        "fundingInterestRate": "0.0003",
        "incrementalInitialMarginRate": "0.0075",
        "incrementalMaintenanceMarginRate": "0.0000",
        "incrementalPositionValue": "1000000.0000",
        "initialMarginRate": "0.0500",
        "maintenanceMarginRate": "0.0300",
        "maxOrderSize": "100.0000",
        "maxPositionSize": "500.0000",
        "minOrderSize": "0.0010",
        "maxMarketPriceRange": "0.03",
        "settleCurrencyId": "USDC",
        "starkExOraclePriceQuorum": "1",
        "starkExResolution": "10000000000",
        "starkExRiskFactor": "128849019",
        "starkExSyntheticAssetId": "0x4254432d3130000000000000000000",
        "stepSize": "0.001",
        "symbol": "BTC-USDC",
        "symbolDisplayName": "BTCUSDC",
        "tickSize": "0.5",
        "underlyingCurrencyId": "BTC",
        "maxMaintenanceMarginRate":"0.03000",
        "maxPositionValue":"10150000.0000"
      }
    ],
    "multiChain": {
      "chains": [
        {
          "chain": "Goerli - Testnet",
          "chainId": 5,
          "chainIconUrl": "https://l2dex-image-static.dev.apexplus.exchange/chains/chain_logos/Goerli.svg",
          "contractAddress": "0x4c0023E8c570D4c3Bd357e7869027cF0106Ed3B7",
          "depositGasFeeLess": false,
          "feeLess": false,
          "feeRate": "0.001",
          "gasLess": false,
          "gasToken": "ETH",
          "minFee": "10",
          "rpcUrl": "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161",
          "webTxUrl": "https://goerli.etherscan.io/tx/",
          "txConfirm": 30,
          "tokens": [
            {
              "decimals": 6,
              "iconUrl": "https://l2dex-image-static.dev.apexplus.exchange/icon/USDC.svg",
              "token": "USDC",
              "tokenAddress": "0xd44BB808bfE43095dBb94c83077766382D63952a",
              "pullOff": false
            },
            {
              "decimals": 18,
              "iconUrl": "https://l2dex-image-static.dev.apexplus.exchange/icon/ETH.svg",
              "token": "ETH",
              "tokenAddress": "",
              "pullOff": true
            }
          ],
          "withdrawGasFeeLess": false
        }
      ],
      "currency": "USDC",
      "maxWithdraw": "100000",
      "minDeposit": "10",
      "minWithdraw": "10"
    }
  },
  "timeCost": 266616
}

Response Status Code

status code value comment data model
200 OK success Inline

Response Parameters

status code 200

Parameter type required limit comment
» global object true none none
»» feeAccountId string true none Trading fee system account id
»» feeAccountL2Key string true none Trading fee system l2Key
»» starkExCollateralCurrencyId string true none Starkex supported collateral asset id
»» starkExMaxFundingRate string true none Maximum funding rate
»» starkExOrdersTreeHeight integer true none Order merkle tree height
»» starkExPositionsTreeHeight integer true none Account merkle tree height
»» starkExFundingValidityPeriod integer true none L2 funding validity period
»» starkExPriceValidityPeriod integer true none L2 price validity period
»» fastWithdrawAccountId string true none Fast withdraw system account id
»» fastWithdrawL2Key string true none Fast withdraw system l2Key
»» fastWithdrawMaxAmount string true none Maximum Fast withdraw amount
»» fastWithdrawFactRegisterAddress string true none L1 Fact registered contract address
»» crossChainAccountId string true none Cross chain withdraw account id
»» crossChainL2Key string true none Cross chain withdraw system l2Key
»» registerChainId integer true 5 envId initially filled during onboarding: Differentiate by environment with 1 as production and 5 as testing environments
» currency [object] true none none
»» id string true none Token name
»» stepSize string true none Minimum step size
»» starkExAssetId string false none StarkEx asset id
»» starkExResolution string false none StarkEx resolution
» multiChain object true none none
»» maxWithdraw string true none Maximum withdrawal amount
»» minWithdraw string true none Minimum withdrawal amount
»» minDeposit string true none Minimum deposit amount
»» currency string true USDC Currency
»» chains [object] true none none
»»» chain string true none Chain
»»» contractAddress string true none Contract address
»»» chainIconUrl string true none Chain icon url
»»» gasToken string true none Gas token name
»»» rpcUrl string true none Chain RPC service Url
»»» chainId integer true none Chain ID
»»» feeLess boolean true none Enable trading fees
»»» depositGasFeeLess boolean false none Enable deposit gas fees
»»» withdrawGasFeeLess boolean false none Enable withdraw gas fees
»»» minFee string true none Minimum deposit gas fee: If gas+value*fee_rate is lesser than min_fee, min_fee amount will be charged instead
»»» feeRate string true none Fee rate
»»» webTxUrl string true none Transaction tx URL
»»» tokens [object] true none none
»»»» token string true none Token name
»»»» tokenAddress string true none Token address
»»»» decimals integer true none Token decimal point accuracy
»»»» iconUrl string true none Token icon URL
»»»» pullOff bool true none Enable taking down of listing, default as FALSE
»»» gasLess boolean true none Enable gas free transaction
» perpetualContract [object] true none none
»» symbol string true none Symbol id
»» symbolDisplayName string true none Symbol display name
»» settleCurrencyId string true none Settlement asset id
»» underlyingCurrencyId string true none Underlying asset id
»» tickSize string true none Minimum tick size
»» stepSize string true none Minimum step size
»» minOrderSize string true none Minimum order size
»» maxOrderSize string true none Maximum order size
»» maxPositionSize string true none Maximum position size
»» maxMarketPriceRange string true none Maximum Market Price rangee
»» initialMarginRate string true none Initial margin rate
»» maintenanceMarginRate string true none Maintenance margin rate
»» baselinePositionValue string true none Baseline position vaue
»» incrementalPositionValue string true none Incremental position value
»» incrementalInitialMarginRate string true none Incremental initial margin rate
»» incrementalMaintenanceMarginRate string true none Incremental maintenance margin rate
»» enableTrade boolean true none Enable trade
»» enableDisplay boolean true none Enable display
»» enableOpenPosition boolean true none Enable open position
»» digitMerge string true none Depth digit merge
»» crossId integer true none Quote API use id for symbol
»» crossSymbolId integer true none Quote API use symbolId for symbol
»» crossSymbolName string true none Quote API use symbolName for symbol
»» fundingInterestRate string true none Funding rate ratio
»» fundingImpactMarginNotional string true none Not required on frontend
»» displayMaxLeverage string true none Maximum leverage
»» displayMinLeverage string true none Minimum leverage
»» starkExSyntheticAssetId string true none Currency synthetic asset id
»» starkExResolution string true none Currency resolution
»» starkExRiskFactor string true none none
»» starkExOraclePriceQuorum string true none none

GET Market Depth

GET /v1/depth

Retrieve all active orderbook for one symbol, inclue all bids and asks.

Request Parameters

Parameter Position type required comment
symbol query string true use crossSymbolName responded from All Config Data
limit query string false Default at 100
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.depth(symbol="BTCUSDC")
curl "https://pro.apex.exchange/api/v1/depth?symbol=BTCUSDC" 

Successful Response Generation

success

{
  "data": [
    {
      "a": [
        [
          "6250",
          "0.01"
        ],
        [
          "6300",
          "0.01"
        ]
      ],
      "b": [
        [
          "1520",
          "0.02"
        ],
        [
          "1535",
          "0.01"
        ]
      ],
      "s": "BTCUSDC",
      "u": 103681
    }
  ]
}

Response Status Code

status code value comment data model
200 OK success Inline

Response Parameters

status code 200

Parameter type required limit comment
» data [object] true none none
»» a [array] false none Sell
»» b [array] false none Buy
»» s string false none Symbol
»» u integer false none none

GET Newest Trading Data

GET /v1/trades

Retrieve trading data.

Request Parameters

Parameter Position type required comment
symbol query string true use crossSymbolName responded from All Config Data
limit query string false Limit
from query string false Return to latest data as default
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.trades(symbol="BTCUSDC")
curl "https://pro.apex.exchange/api/v1/trades?symbol=BTCUSDC" 

Successful Response Generation

success

{
  "data": [
    {
      "S": "BUY",
      "v": "0.001",
      "p": "29000",
      "s": "BTCUSDC",
      "T": 1647502440973
    }
  ]
}

Response Status Code

status code value comment data model
200 OK success Inline

Response Parameters

status code 200

Parameter type required limit comment
» data [object] true none none
»» S string false none Side
»» v string false none Size
»» p string false none Price
»» s string false none Symbol
»» T integer false none Trade time

GET Candlestick Chart Data

GET /v1/klines

Retrieves all candlestick chart data.
Candlestick chart time indicators: Numbers represent minutes, D for Days, M for Month and W for Week — 1 5 15 30 60 120 240 360 720 "D" "M" "W"

Request Parameters

Parameter Position type required comment
interval query string false Candlestick chart time indicators: Numbers represent minutes, D for Days, M for Month and W for Week — 1 5 15 30 60 120 240 360 720 "D" "M" "W"
start query string false Start time
end query string false End time
limit query string false Limit
symbol query string false use crossSymbolName responded from All Config Data
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.klines(symbol="BTCUSDC",interval=5)
curl "https://pro.apex.exchange/api/v1/klines?symbol=BTCUSDC?interval=5" 

Successful Response Generation

success

{
  "data": [
    {
      "start": 1647511440000,
      "symbol": "BTCUSDC",
      "interval": "1",
      "low": "40000",
      "high": "45000",
      "open": "45000",
      "close": "40000",
      "volume": "1.002",
      "turnover": "3"
    }
  ]
}

Response Status Code

status code value comment data model
200 OK success Inline

Response Parameters

status code 200

Parameter type required limit comment
» klines [object] true none none
»» start integer false none Start time
»» symbol string true none Currency
»» interval string true none Chart interval
»» low string false none Low price
»» high string false none High price
»» open string false none Open price
»» close string false none Close price
»» volume string false none Trading volume
»» turnover string false none Turnover

GET Ticker Data

GET /v1/ticker

Get the latest data on symbol tickers.

Request Parameters

Parameter Position type required comment
symbol query string true use crossSymbolName responded from All Config Data
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.ticker(symbol="BTCUSDC")
curl "https://pro.apex.exchange/api/v1/ticker?symbol=BTCUSDC" 

Successful Response Generation

success

{
  "data": [
    {
      "symbol": "BTCUSDC",
      "price24hPcnt": "0.450141",
      "lastPrice": "43511.50",
      "highPrice24h": "43513.50",
      "lowPrice24h": "29996.00",
      "oraclePrice": "43513.50",
      "indexPrice": "40828.94",
      "openInterest": "2036854775808",
      "turnover24h": "5626085.23749999",
      "volume24h": "169.317",
      "fundingRate": "0",
      "predictedFundingRate": "0",
      "nextFundingTime": "10:00:00",
      "tradeCount": 100
    }
  ]
}

Response Status Code

status code value comment data model
200 OK success Inline

Response Parameters

status code 200

Parameter type required limit comment
» tickers [object] true none none
»» symbol string false none Symbol
»» price24hPcnt string false none 24H change (%)
»» lastPrice string false none Last price
»» highPrice24h string false none 24H highest price
»» lowPrice24h string false none 24H lowest price
»» oraclePrice string false none Oracle price
»» indexPrice string false none Index price
»» openInterest string false none Open interest
»» turnover24h string false none 24H turnover
»» volume24h string false none 24H trading volume
»» fundingRate string false none Funding rate
»» predictedFundingRate string false none Predicted funding rate
»» nextFundingTime string false none Next funding rate
»» tradeCount string false none 24H trade count

GET Funding Rate History

GET /v1/history-funding

Request Parameters

Parameter Position type required comment
symbol query string true use crossSymbolName responded from All Config Data
Limit query string false Default at 100
beginTimeInclusive query string false Start time
endTimeExclusive query string false End time
page query string false Page numbers start from 0
from apexpro.http_public import HttpPublic

client = HttpPublic("https://pro.apex.exchange")
client.history_funding(symbol="BTC-USDC")
curl "https://pro.apex.exchange/api/v1/history-funding?symbol=BTC-USDC" 

Successful Response Generation

success

{
  "historyFunds": [
    {
      "symbol": "BTC-USD",
      "rate": "0.0000125000",
      "price": "31297.5000008009374142",
      "fundingTime": 12315555,
      "fundingTimestamp": 12315555
    }
  ],
  "totalSize": 11
}

Response Status Code

status code value comment data model
200 OK success Inline

Response Parameters

status code 200

Parameter type required limit comment
» historicalFunds [object] true none none
»» symbol string false none none
»» rate string false none Funding rate
»» price string false none Price
»» fundingTime integer false none Time
»» fundingTimestamp integer false none Funding timestamp
» totalSize integer true none Size

GET Check If User Exists

GET /v1/check-user-exist

Request Parameters

Parameter Position type required comment
ethAddress query string FALSE 0x111111

Successful Response Generation

success

{
  "data": false
}

Response Status Code

status code value comment data model
200 OK success Inline

Response Parameters

status code 200

Parameter Type Required Limit Comment
» data boolean true none none

PrivateApi_V2

v2.0

POST Generate nonce V2

POST /v2/generate-nonce

Before registering, generate and obtain a nonce. The nonce serves the purpose of assembling the signature field during the registration process.

from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key="0x*****")
configs = client.configs_v2()
stark_key_pair_with_y_coordinate = client.derive_stark_key(client.default_address)
nonceRes = client.generate_nonce(starkKey=stark_key_pair_with_y_coordinate['public_key'],ethAddress=client.default_address,chainId="5")
curl https://pro.apex.exchange/api/v2/generate-nonce -X POST -d 'starkKey={starkKey}&ethAddress={ethAddress}&chainId={chainId}'

Request Parameters

Parameter Position Type Required Comment
body body object false none
» starkKey body string true User's starkKey
» ethAddress body string true User's Ethereum address
» chainId body string true API trading users to enter "1" on mainnet

Successful Response Generation

{
  "data": {
    "nonce": "1123940951220551680",
    "nonceExpired": 1648727402292
  }
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» nonce string true none nonce
» nonceExpired integer true none The time at which nonce expires, please complete registration before this time

POST Registration & Onboarding V2

POST /v2/onboarding

  1. Consolidate onboarding data and generate a digital signature using your wallet. Refer to the Python SDK, specifically derive_stark_key, for more information.
  2. Create your Stark Key pair with your signature, comprising (publicKey, publicKeyYCoordinate, privateKey).
  3. Send the consolidated onboarding data request to the server for a response, including API keys for user registration.
curl https://pro.apex.exchange/api/v2/onboarding -H 'APEX-SIGNATURE: ***' -H 'APEX-ETHEREUM-ADDRESS: ***' -X POST -d 'starkKey={starkKey}&starkKeyYCoordinate={starkKeyYCoordinate}&ethereumAddress={ethereumAddress}&referredByAffiliateLink={referredByAffiliateLink}&country={country}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key="0xb7daaaaaaaaaaaaaaaa")

configs = client.configs_v2()

stark_key_pair_with_y_coordinate = client.derive_stark_key(client.default_address)

nonceRes = client.generate_nonce(starkKey=stark_key_pair_with_y_coordinate['public_key'],ethAddress=client.default_address,chainId="5")

regRes = client.register_user_v2(nonce=nonceRes['data']['nonce'],starkKey=stark_key_pair_with_y_coordinate['public_key'],stark_public_key_y_coordinate=stark_key_pair_with_y_coordinate['public_key_y_coordinate'],ethereum_address=client.default_address)

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Onboarding signature
APEX-ETHEREUM-ADDRESS header string true Ethereum address
body body object false none
» starkKey body string true Public starkKey associated with the key-pair you created.
» starkKeyYCoordinate body string true Public starkKey Y-Coordinate associated with the key-pair you created.
» ethereumAddress body string true Ethereum address associated with the user being created.
» referredByAffiliateLink body string false Referred affiliate link
» country body string false Country code: Must be ISO 3166-1 Alpha-2 compliant

Successful Response Generation

{
  "apiKey": {
    "key": "290xxxxxx",
    "passphrase": "S6xxxxx",
    "secret": "KQ3xxxx"
  },
  "user": {
    "ethereumAddress": "0x09xxxxxx",
    "isRegistered": true,
    "email": "email@apex.exchange",
    "username": "man",
    "referredByAffiliateLink": "url",
    "isEmailVerified": false,
    "emailNotifyGeneralEnable": false,
    "emailNotifyTradingEnable": false,
    "emailNotifyAccountEnable": false,
    "popupNotifyTradingEnable": false
  },
  "account": {
    "starkKey": "180913017c740260fea4b2c62828a4008ca8b0d6e4",
    "positionId": "1812",
    "id": "1812",
    "takerFeeRate": "0.0005",
    "makerFeeRate": "0.0005",
    "createdAt": 1647502440973,
    "experienceMoney": [
      {
        "availableAmount": "0.000000",
        "totalNumber": "0",
        "totalAmount": "0.000000",
        "recycledAmount": "0.000000",
        "token": "USDC"
      }
    ],
   "accounts": [
      {
        "createdAt": 1690365436385,
        "takerFeeRate": "0.00050",
        "makerFeeRate": "0.00020",
        "minInitialMarginRate": "0",
        "status": "NORMAL",
        "token": "USDC"
      },
      {
        "createdAt": 1690365436385,
        "takerFeeRate": "0.00050",
        "makerFeeRate": "0.00020",
        "minInitialMarginRate": "0",
        "status": "NORMAL",
        "token": "USDT"
      }
    ],
    "wallets": [
      {
        "userId": "12137",
        "accountId": "350",
        "balance": "1191781.577364",
        "asset": "USDC",
        "token": "USDC",
        "pendingDepositAmount": "0.000000",
        "pendingWithdrawAmount": "0.000000",
        "pendingTransferOutAmount": "0.000000",
        "pendingTransferInAmount": "0.000000"
      },
      {
        "userId": "12137",
        "accountId": "350",
        "balance": "1191781.577364",
        "asset": "USDT",
        "token": "USDT",
        "pendingDepositAmount": "0.000000",
        "pendingWithdrawAmount": "0.000000",
        "pendingTransferOutAmount": "0.000000",
        "pendingTransferInAmount": "0.000000"
      }
    ],
    "openPositions": [
      {
        "symbol": "BTC-USD",
        "side": "LONG",
        "size": "1000",
        "entryPrice": "100",
        "fee": "50",
        "fundingFee": "100",
        "createdAt": 1647502440973,
        "updatedTime": 1647502440973,
        "lightNumbers": "1"
      }
    ],
    "id": "id"
  }
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» apiKey object true none none
»» key string true none Placed in request header for sending to server
»» passphrase string true none Placed in request header for sending to server
»» secret string true none Used to generate signature
» user object true none none
»» ethereumAddress string true none Ethereum address
»» isRegistered boolean true none Registration confirmation
»» email string true none Email
»» username string true none Username
»» referredByAffiliateLink string true none referred Affiliate Link
»» isEmailVerified boolean true none Email binding confirmation
»» emailNotifyGeneralEnable boolean true none Newsletter, Market Updates, Product notify
»» emailNotifyTradingEnable boolean true none Deposits、Withdrawals, Account notify
»» emailNotifyAccountEnable boolean true none Order and Liquidation notify
»» popupNotifyTradingEnable boolean true none Trading pop-up notify
» account object true none none
»» starkKey string true none User's starkKey
»» positionId string true none User's account ID
»» id string true none User's account ID
»» experienceMoney [object] true none
»»» availableAmount string false none
»»» totalNumber string false none
»»» totalAmount string false none
»»» recycledAmount string false none
»»» token string false none
»» accounts [object] true none
»»» makerFeeRate string true none Maker fee rate
»»» takerFeeRate string true none Taker fee rate
»»» createdAt integer true none Created time
»»» minInitialMarginRate string true none
»»» status string false none
»»» token string true none
»» wallets [object] true none User wallet
»»» userId string false none User ID
»»» accountId string false none Account ID
»»» asset string false none Asset
»»» balance string false none Wallet balance
»» pendingDepositAmount string true none Pending deposit amount
»» pendingWithdrawAmount string true none Pending withdrawal amount
»» pendingTransferOutAmount string true none Pending outbound transfer amount
»» pendingTransferInAmount string true none Pending inbound transfer amount
»» openPositions [object] true none Open positions
»» symbol string false none Symbol
»» side string false none Side
»» size string false none Size
»» entryPrice string false none Entry price
»» fee string false none Order fee
»» createdAt integer false none Created at
»» updatedTime integer false none Updated time
»» fundingFee string false none Funding fee
»» lightNumbers string false none ADL ranking

GET Retrieve User Data V2

GET /v2/user

curl https://pro.apex.exchange/api/v2/user -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

userRes = client.get_user()

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "ethereumAddress": "0x091aaaaaaaaaa",
  "isRegistered": true,
  "email": "email@apex.exchange",
  "username": "supersam15o",
  "userData": {},
  "isEmailVerified": false,
  "emailNotifyGeneralEnable": false,
  "emailNotifyTradingEnable": false,
  "emailNotifyAccountEnable": false,
  "popupNotifyTradingEnable": false
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» ethereumAddress string true none Ethereum address
» isRegistered boolean true none Registration completed
» email string true none Email
» username string true none Username
» userData object true none none
» isEmailVerified boolean true none none
» emailNotifyGeneralEnable string true none Newsletter, market and product updates
» emailNotifyTradingEnable string true none Order and liquidation updates
» emailNotifyAccountEnable string true none Deposit, withdrawal and account updates
» popupNotifyTradingEnable string true none Enable trading notifications

POST Edit User Data V2

POST /v2/modify-user

curl https://pro.apex.exchange/api/v2/modify-user -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'userData={userData}&email={email}&username={username}&isSharingUsername={isSharingUsername}&isSharingAddress={isSharingAddress}&country={country}&emailNotifyGeneralEnable={emailNotifyGeneralEnable}&emailNotifyTradingEnable={emailNotifyTradingEnable}&emailNotifyAccountEnable={emailNotifyAccountEnable}&popupNotifyTradingEnable={popupNotifyTradingEnable}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

userRes = client.modify_user(username="pythonTest",email="11@aa.com",emailNotifyGeneralEnable="true")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» userData body string false none
» email body string false Email
» username body string false Username
» isSharingUsername body string false none
» isSharingAddress body string false none
» country body string false country
» emailNotifyGeneralEnable body string false Newsletter, market and product updates
» emailNotifyTradingEnable body string false Order and liquidation updates
» emailNotifyAccountEnable body string false Deposit, withdrawal and account updates
» popupNotifyTradingEnable body string false Enable trading notifications

Successful Response Generation

{
  "ethereumAddress": "0x091aaaaaaaaaa",
  "isRegistered": true,
  "email": "email@apex.exchange",
  "username": "supersam15o",
  "userData": {},
  "isEmailVerified": false,
  "emailNotifyGeneralEnable": false,
  "emailNotifyTradingEnable": false,
  "emailNotifyAccountEnable": false,
  "popupNotifyTradingEnable": false
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» ethereumAddress string true none Ethereum address
» isRegistered boolean true none Registration completed
» email string true none Email
» username string true none Username
» userData object true none none
» isEmailVerified boolean true none none
» emailNotifyGeneralEnable string true none Newsletter, market and product updates
» emailNotifyTradingEnable string true none Order and liquidation updates
» emailNotifyAccountEnable string true none Deposit, withdrawal and account updates
» popupNotifyTradingEnable string true none Enable trading notifications

GET Retrieve User Account Data V2

GET /v2/account

Retrieve a user's account by their ID. Utilize the client, where the ID is generated with client information and an Ethereum address.

curl https://pro.apex.exchange/api/v1/account -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

accountRes = client.get_account()

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none

Successful Response Generation

{
  "starkKey": "1234567",
  "positionId": "350522584833",
  "ethereumAddress": "0xc4c5036b68a42d8f1c6ba9ba8e5dd49ad5c1ef5c",
  "id": "350522584833",
  "experienceMoney": [
    {
      "availableAmount": "0.000000",
      "totalNumber": "0",
      "totalAmount": "0.000000",
      "recycledAmount": "0.000000",
      "token": "USDC"
    }
  ],
  "accounts": [
    {
      "createdAt": 1690365436385,
      "takerFeeRate": "0.00050",
      "makerFeeRate": "0.00020",
      "minInitialMarginRate": "0",
      "status": "NORMAL",
      "token": "USDC"
    },
    {
      "createdAt": 1690365436385,
      "takerFeeRate": "0.00050",
      "makerFeeRate": "0.00020",
      "minInitialMarginRate": "0",
      "status": "NORMAL",
      "token": "USDT"
    }
  ],
  "wallets": [
    {
      "userId": "121372485302",
      "accountId": "350522584833",
      "balance": "1191778.137753",
      "asset": "USDC",
      "token": "USDC",
      "pendingDepositAmount": "0.000000",
      "pendingWithdrawAmount": "0.000000",
      "pendingTransferOutAmount": "0.000000",
      "pendingTransferInAmount": "0.000000"
    }
  ],
  "positions": [
    {
      "token": "USDC",
      "symbol": "BTC-USDC",
      "status": "",
      "side": "LONG",
      "size": "0.000",
      "entryPrice": "0.00",
      "exitPrice": "",
      "createdAt": 1690366452416,
      "updatedTime": 1690366452416,
      "fee": "0.000000",
      "fundingFee": "0.000000",
      "lightNumbers": "",
      "customInitialMarginRate": "0"
    }
  ]
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
»» starkKey string true none User's starkKey
»» positionId string true none User's account ID
»» id string true none User's account ID
»» makerFeeRate string true none Maker fee rate
»» takerFeeRate string true none Taker fee rate
»» createdAt integer true none Created time
»» wallets [object] true none User wallet
»»» userId string false none User ID
»»» accountId string false none Account ID
»»» asset string false none Asset
»»» balance string false none Wallet balance
»» pendingDepositAmount string true none Pending deposit amount
»» pendingWithdrawAmount string true none Pending withdrawal amount
»» pendingTransferOutAmount string true none Pending outbound transfer amount
»» pendingTransferInAmount string true none Pending inbound transfer amount
»» openPositions [object] true none Open positions
»» symbol string false none Symbol
»» side string false none Side
»» size string false none Size
»» entryPrice string false none Entry price
»» fee string false none Order fee
»» createdAt integer false none Created at
»» updatedTime integer false none Updated time
»» fundingFee string false none Funding fee
»» lightNumbers string false none ADL ranking

GET Retrieve User Account balance V2

GET /v2/account-balance

curl https://pro.apex.exchange/api/v2/account-balance -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

accountRes = client.get_account_balance()

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "usdtBalance": {
    "totalEquityValue": "100.000000",
    "availableBalance": "100.000000",
    "initialMargin": "100.000000",
    "maintenanceMargin": "100.000000",
    "symbolToOraclePrice": {
      "BTC-USDC": {
        "oraclePrice": "20000",
        "createdTime": 124566
      }
    }
  },
  "usdcBalance": {
    "totalEquityValue": "100.000000",
    "availableBalance": "100.000000",
    "initialMargin": "100.000000",
    "maintenanceMargin": "100.000000",
    "symbolToOraclePrice": {
      "BTC-USDC": {
        "oraclePrice": "20000",
        "createdTime": 124566
      }
    }
  }
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status code 200

Parameter Type Required Limit Comment
» usdtBalance object true none
»» totalEquityValue string true none
»» availableBalance string true none
»» initialMargin string true none
»» maintenanceMargin string true none
»» symbolToOraclePrice object true none
»»» BTC-USDC object true none
»»»» oraclePrice string true none
»»»» createdTime integer true none
» usdcBalance object true none
»» totalEquityValue string true none
»» availableBalance string true none
»» initialMargin string true none
»» maintenanceMargin string true none
»» symbolToOraclePrice object true none
»»» BTC-USDC object true none
»»»» oraclePrice string true none
»»»» createdTime integer true none

GET Retrieve User Deposit Data V2

GET /v2/transfers

Please note, the currency is required to retrieve user deposit data.

curl https://pro.apex.exchange/api/v2/transfers?limit={limit}&page={page}&currencyId={currencyId}&chainIds={chainIds} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

transfersRes = client.transfers_v2(limit=100,page=0,currencyId="USDT",chainIds="1,5,13")
Deposit Status{   
UNKNOWN_DEPOSIT_STATUS 0 // Unknown.  
PENDING_L1_CREATING 1 // Deposit pending on L1, awaiting confirmation.   
PENDING_RISK_CHECKING 2 // Confirmed, risk check in progress.  
PENDING_CENSORING 3 // Risk check complete, awaiting verification.  
SUCCESS 4 // Deposit success, your funds have been sent to your wallet. Awaiting L2 validation.   
SUCCESS_L2_APPROVED 5 // L2 approved.   
CANCELED 6 // L1 confirmation failure, deposit has been canceled.  
FAILED_RISK_CHECK_FAILURE 7 // Deposit has failed due to failed risk check.     
FAILED_CENSOR_FAILURE 8 // Deposit has failed due to inaccurate data, data entries have been rolled back.   
FAILED_L2_REJECTED 9 // Deposit has failed due to failed L2 approval. Deposited funds have been removed from your account.   
}  

Withdrawal Status{   
UNKNOWN_WITHDRAW_STATUS 0 // Unknown.  
PENDING_RISK_CHECKING 1 // Risk check in progress.  
PENDING_CENSORING 2 // Pending verification.  
PENDING_L2_APPROVING 3 // Approved, awaiting L2 validation.  
PENDING_L1_CONFIRMING 4 // L2 validation complete, pending L1 confirmation.  
PENDING_L1_WITHDRAWING 5 // Withdrawal request on L1 complete, awaiting user withdrawal.  
SUCCESS 6 // Withdrawal success, your withdrawn funds can now be found in your wallet.   
FAILED_RISK_CHECK_FAILURE 7 // Withdrawal unsuccessful due to failed risk check.   
FAILED_CENSOR_FAILURE 8 // Withdrawal unsuccessful due to inaccurate data, data entries have been rolled back.   
FAILED_L2_REJECTED 9 // Withdrawal unsuccessful due to failed L2 approval and roll back has commenced.   
}  

Cross-Chain Withdrawal Status{   
UNKNOWN_CROSS_WITHDRAW_STATUS 0 // Unknown.  
PENDING_CROSS_WITHDRAW_CHECKING 1 // Pending chain verification.  
SUCCESS_CROSS_WITHDRAW_SUBMIT_CENSOR 2  
PENDING_CROSS_WITHDRAW__CENSOR_CHECKING_ACCOUNT 3 //  
PENDING_CROSS_WITHDRAW_CENSORING 4 // Pending data verification.  
PENDING_CROSS_WITHDRAW_L2_APPROVING 5 // Verification successful, awaiting L2 approval.  
PENDING_CROSS_WITHDRAW_L1_SUBMIT 6 //Approved, submitting to L1.  
PENDING_CROSS_WITHDRAW_L1_CONFIRMING 7 // L1 submission successful, pending L1 validation.  
CROSS_WITHDRAW_SUCCESS 8 // Withdrawal successful.  
FAILED_CROSS_WITHDRAW_TRANSFER_REJECTED 9 /Transfer rejected.  
FAILED_CROSS_WITHDRAW__CENSOR_CHECKING_ACCOUNT_REJECTED 10 //Account verification rejected.   
FAILED_CROSS_WITHDRAW_CENSORING 11 //Inaccurate validation data.   
FAILED_CROSS_L2_REJECTED 12 // Transfer has failed. L2 validation rejection, roll back has commenced.   
FAILED_CROSS_WITHDRAW_L1_SUBMIT_REJECTED 13  
FAILED_CROSS_WITHDRAW_L1_REJECTED 14// Withdrawal request failed, L1 transfer unsuccessful.   
}  

Cross-Chain Deposit Status{   
UNKNOWN_CROSS_DEPOSIT_STATUS 0 //  Unknown.  
PENDING_CROSS_DEPOSIT_L1_CREATING 1 // Deposit confirmed on L1, creating transaction.  
PENDING_CROSS_DEPOSIT_L2_TRIGGER 2 // Awaiting trigger for transfer to L2.  
PENDING_CROSS_DEPOSIT_CENSOR_CHECKING 3 // L1 deposit successful, awaiting transfer to L2.  
SUCCESS_CROSS_DEPOSIT_SUBMIT_CENSOR 4  
PENDING_CROSS_DEPOSIT_CENSOR_CHECKING_ACCOUNT 5 //  
PENDING_CROSS_DEPOSIT_CENSORING 6 // Confirmed, verification in progress.  
PENDING_CROSS_DEPOSIT_L2_APPROVING 7 // Pending L2 approval.  
CROSS_DEPOSIT_SUCCESS 8 //Deposit successful.   
FAILED_CROSS_DEPOSIT_TRANSFER_REJECTED 9 //Transfer rejected.  
FAILED_CROSS_DEPOSIT_CENSOR_CHECKING_ACCOUNT_REJECTED 10 //User account error found.  
CROSS_DEPOSIT_CENSORING 11 //Inaccurate validation data.   
FAILED_CROSS_L2_REJECTED 12 // Transfer has failed. L2 validation rejection, roll back has commenced.   
}  

Fast Withdrawal Status{   
UNKNOWN_FAST_WITHDRAW_STATUS 0 // Unknown.  
PENDING_FAST_WITHDRAW_CHECKING 1 //Pending checks.  
PENDING_FAST_WITHDRAW_SUBMIT 2 //Submitted for checking, creating txid.  
PENDING_FAST_WITHDRAW_CHECKING_ACCOUNT 3 // PENDING_FAST_WITHDRAW_CENSORING 4 //Pending data verification.  
PENDING_FAST_WITHDRAW_L1_SUBMIT 5 //Confirmed, awaiting send to L1 .  
PENDING_FAST_WITHDRAW_L1_CONFIRMING 6 // Confirmed, pending L1 confirmation.  
PENDING_FAST_WITHDRAW_CENSORING_CONFIRMING 7 //Pending verification, awaiting confirmation of transfer.  
PENDING_FAST_WITHDRAW_L2_APPROVING 8 // Verification successful, pending L2 approval.  
FAST_WITHDRAW_SUCCESS 9 // Withdrawal successful, your funds can be found in your wallet.   
FAILED_FAST_WITHDRAW_TRANSFER_REJECTED 10 //Transfer rejected.  
FAILED_FAST_WITHDRAW_CHECKING_ACCOUNT_REJECTED 11 //User account error found.  
FAILED_FAST_WITHDRAW_CENSORING 12 //Inaccurate validation data.   
FAILED_FAST_WITHDRAW_L1_SUBMIB_REJECTED 13 // Withdrawal has failed, unsuccessful transfer to L1.  
FAILED_FAST_WITHDRAW_L1_REJECTED 14 // Withdrawal unsuccessful, request rejected on L1.  
FAILED_FAST_WITHDRAW_L2_REJECTED 15 // L2 validation rejection, roll back has commenced.
PENDING_L1_WITHDRAWING  16 // Status: Click for withdrawal smart contract.  
}  

Request Parameters

Parameters Position Type Required Comments
limit query integer false Page limit default at 100
page query integer false Page numbers start from 0
currencyId query string true Filter to show only currency ID, all will be searched if the field is empty
beginTimeInclusive query integer false Start time
endTimeExclusive query string false End time
chainIds query string false Check for multiple chainID records, separated by commas
transferType query string false Check for multiple transferType records, separated by commas
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "transfers": [
    {
      "id": "foo",
      "type": "DEPOSIT",
      "currencyId": "USDC",
      "amount": "3000",
      "transactionHash": "0x12aaaaaaaa",
      "status": "PENDING",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "confirmedAt": 1647502440973,
      "clientId": "12345",
      "confirmedCount": 12,
      "requiredCount": 12,
      "orderId": "12345",
      "chainId": "1",
      "fee": "10.0"
    }
  ],
  "totalSize": 123
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» transfers [object] true none none
»» id string false none none
»» type string false none DEPOSIT, WITHDRAW or FAST_WITHDRAW
»» CurrencyId string false none Currency ID
»» Amount string false none Amount
»» transactionHash string false none Transaction hash
»» status string false none Status
»» createdAt integer false none Created at
»» confirmedAt integer false none Confirmed time (only for withdrawals)
»» updatedTime string true none Only applicable for deposits
»» confirmedCount string true none Number of confirmations on L1, only for deposits
»» requiredCount string true none Number of confirmations required for deposits on L1, only for deposits
»» clientId string false none Client to create a randomized id (only for withdrawal)
»» orderId string true none Success Wallet Transaction Id
»» chainId string true none Supported chainId
»» fee string true none Fee
» totalSize string true none Total size

GET Retrieve User Withdrawal List V2

GET /v2/withdraw-list

Please note, the token is required to retrieve the user withdrawal list.

curl https://pro.apex.exchange/api/v2/withdraw-list?limit={limit}&page={page}&beginTimeInclusive={beginTimeInclusive}&endTimeExclusive={endTimeExclusive} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

withdrawListRes = client.withdraw_list(limit=100,page=0,beginTimeInclusive=1651406864000,endTimeExclusive=1657105971171)

Request Parameters

Parameter Position Type Required Comment
limit query integer false Page limit default at 100
page query integer false Page numbers start from 0
beginTimeInclusive query integer false Start time
endTimeExclusive query string false End time
transferType query string false Check for multiple transferType records, separated by commas
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "transfers": [
    {
      "id": "foo",
      "type": "WITHDRAW",
      "currencyId": "USDC",
      "amount": "3000",
      "transactionHash": "0x12aaaaaaaa",
      "status": "PENDING_L2_APPROVING",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "confirmedAt": 1647502440973,
      "clientId": "12345",
      "orderId": "12345",
      "chainId": "1",
      "fee": "10.0"
    }
  ],
  "totalSize": 123
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» transfers [object] true none none
»» id string false none none
»» type string false none DEPOSIT, WITHDRAW or FAST_WITHDRAW
»» CurrencyId string false none Currency ID
»» Amount string false none Amount
»» transactionHash string false none Transaction hash
»» status string false none Status
»» createdAt integer false none Created at
»» confirmedAt integer false none Confirmed time (only for withdrawals)
»» updatedTime string false none Only applicable for deposits
»» confirmedCount string false none Number of confirmations on L1, only for deposits
»» requiredCount string false none Number of confirmations required for deposits on L1, only for deposits
»» clientId string false none client create the Randomized id (only for withdrawal)
»» orderId string true none Success Wallet Transaction Id
»» chainId string false none Supported chainId
»» fee string false none Fee
»» withdrawStatus string false none PENDING_L2_APPROVING,SUCCESS : Withdrawal status, search for multiple statuses separated by commas
» totalSize string true none none

POST User Withdrawal V2

POST /v2/create-withdrawal

withdrawalToSign = {  
humanAmount: params.amount,  
expirationIsoTimestamp: params.expiration,  
clientId,  
positionId,  
};  

example

curl https://pro.apex.exchange/api/v2/create-withdrawal -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'amount={amount}&clientId={clientId}&asset={asset}&expiration={expiration}&signature={signature}'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()

createWithdrawRes = client.create_withdrawal_v2(amount='1001',expirationEpochSeconds=currentTime,asset='USDT')

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» amount body string true Amount
» clientId body string true Unique id of the client associated with the withdrawal. Must be <= 40 characters. When using the client, if not included, will be randomly generated by the client.
» expiration body string true Date and time at which the withdrawal expires if it has not been completed. Expiration must be at least seven days in the future.
» asset body string true Asset (in USDC) being withdrawn.
» signature body string true The signature for the transfer, signed with the account's STARK private key.

Successful Response Generation

{
  "id": "1234455",
  "type": "WITHDRAW"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string true none id
» type string true none type

POST User Withdrawal to Designated Address V2

POST /v2/create-withdrawal-to-address

Transfer funds from L1 to a designated Ethereum address without the need to register for a corresponding StarkKey associated with the Ethereum address.

withdrawalToSign = {
humanAmount: params.amount,
expirationIsoTimestamp: params.expiration,
clientId,
positionId,
ethAddress,
};

example

curl https://pro.apex.exchange/api/v2/create-withdrawal -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'amount={amount}&clientId={clientId}&asset={asset}&expiration={expiration}&signature={signature}&ethAddress={ethAddress}'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()

createWithdrawRes = client.create_withdrawal_v2(amount='1001',expirationEpochSeconds=currentTime,asset='USDT',ethAddress="0x***")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string Request signature Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» amount body string true Withdraw Amount
» clientId body string true Unique id of the client associated with the withdrawal. Must be <= 40 characters. When using the client, if not included, will be randomly generated by the client.
» expiration body string true Date and time at which the withdrawal expires if it has not been completed. Expiration must be at least seven days in the future.
» asset body string true Asset(in USDC) being withdrawn.
» signature body string true The signature for the transfer, signed with the account's STARK private key.
» ethAddress body string false Withdraw only to your registered Ethereum address.

Successful Response Generation

{
  "id": "1234455",
  "type": "WITHDRAW"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string true none none
» type string true none Withdrawal type

POST User Fast Withdrawal V2

POST /v2/fast-withdraw

fact = this.starkLib.factRegistry.getTransferErc20Fact({  
recipient: toEthAddress,  
tokenAddress: usdcAddress,  
tokenDecimals: 6,  
humanAmount: params.Amount,  
salt: nonceFromClientId(clientId),  
});     

const transferToSign = {  
senderPositionId: accountId,  
receiverPositionId: fastWithdrawAccountId,  
receiverPublicKey: fastWithdrawL2Key,  
factRegistryAddress: fastWithdrawFactRegisterAddress,  
fact,  
humanAmount: params.amount,  
clientId,  
expirationIsoTimestamp: params.expiration,  
};

example

curl https://pro.apex.exchange/api/v2/fast-withdraw -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'amount={amount}&clientId={clientId}&asset={asset}&expiration={expiration}&signature={signature}&ethAddress={ethAddress}&erc20Address={erc20Address}&fee={fee}&lpAccountId={lpAccountId}&chainId={chainId}'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()
feeRes = client.uncommon_withdraw_fee_v2(amount='1002',chainId='56', token='USDT')
fastWithdrawRes = client.fast_withdrawal_v2(amount='1002',expirationEpochSeconds=currentTime,asset='USDT',fee=feeRes['data']['fee'])

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» amount body string false Withdrawal amount
» clientId body string false Unique id of the client associated with the withdrawal. Must be <= 40 characters. When using the client, if not included, will be randomly generated by the client.
» expiration body string false Date and time at which the withdrawal expires if it has not been completed. Expiration must be at least seven days in the future.
» asset body string false Asset(in USDC) being withdrawn.
» signature body string false The signature for the transfer, signed with the account's STARK private key.
» erc20Address body string false USDC address
» fee body string false Fees
» chainId body string true chainId
» lpAccountId body string false Attach documents to retrieve fast_withdraw_account_id

Successful Response Generation

{
  "id": "1234455",
  "type": "FAST_WITHDRAW"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string true none id
» type string true none type

POST Cross-Chain Withdrawals V2

POST /v2/cross-chain-withdraw

withdrawalToSign = {
  humanAmount: params.amount,
  expirationIsoTimestamp: params.expiration,
  clientId,
  positionId,
  fee
};

example

curl https://pro.apex.exchange/api/v2/cross-chain-withdraw -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'amount={amount}&clientId={clientId}&asset={asset}&expiration={expiration}&signature={signature}&ethAddress={ethAddress}&erc20Address={erc20Address}&fee={fee}&lpAccountId={lpAccountId}&chainId={chainId}'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()
feeRes = client.uncommon_withdraw_fee(amount='1003',chainId='56', token='USDT')
crossWithdrawRes = client.cross_chain_withdraw(amount='1003',expirationEpochSeconds= currentTime,asset='USDT',fee=feeRes['data']['fee'],chainId='56')

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» amount body string true Withdrawal amount
» clientId body string true Unique id of the client associated with the withdrawal. Must be <= 40 characters. When using the client, if not included, will be randomly generated by the client.
» expiration body string true Date and time at which the withdrawal expires if it has not been completed. Expiration must be at least seven days in the future.
» asset body string true Asset(in USDC) being withdrawn.
» signature body string true The signature for the transfer, signed with the account's STARK private key.
» erc20Address body string true USDC address
» chainId body string true Randomized clientId
» fee body string true Fees
» lpAccountId body string true Attach documents to retrieve fast_withdraw_account_id

Successful Response Generation

{
  "id": "1234455",
  "type": "CROSS_WITHDRAW"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string true none none
» type string true none Withdrawal type

GET Fast & Cross-Chain Withdrawal Fees V2

GET /v2/uncommon-withdraw-fee

curl https://pro.apex.exchange/api/v2/uncommon-withdraw-fee?amount={amount}&chainId={chainId}&token=USDC -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' 
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

feeRes = client.uncommon_withdraw_fee(amount='1003',chainId='56', token='USDT')

Request Parameters

Please note, the token is required to request parameters.

Parameter Position Type Required Comment
amount query string false USDC
chainId query string false chainId
token query string true USDC USDT
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "fee": "1.1",
  "poolAvailableAmount": "10"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» fee string true none Fees calculated
» poolAvailableAmount string true none Available balance in pool

GET Withdrawal & Transfer Limits V2

GET /v2/transfer-limit

curl https://pro.apex.exchange/api/v1/transfer-limit?currencyId=USDC -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

transfer_limitRes = client.transfer_limit(currencyId="USDC")

Request Parameters

Parameter Position Type Required Comment
currencyId query string true USDC
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "withdrawAvailableAmount": "100.1",
  "transferAvailableAmount": "100.1"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» withdrawAvailableAmount string true none Withdraw available amount
» transferAvailableAmount string true none Transfer available amount

GET Trade History

GET /v2/fills

Please note, the token is required to retrieve a trade history.

curl https://pro.apex.exchange/api/v2/fills?limit=100&page=0&symbol=BTC-USDC&side=BUY&token=USDC -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' 
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

fillsRes = client.fills_v2(limit=100,page=0,symbol="BTC-USDC",side="BUY")
Order Type  
 "UNKNOWN_ORDER_TYPE"    
 "LIMIT", //Limit price   
 "MARKET", //Market price   
 "STOP_LIMIT", //Stop limit order   
 "STOP_MARKET", //Stop market order   
 "TAKE_PROFIT_LIMIT",//Take profit limit orders   
 "TAKE_PROFIT_MARKET",//Take profit market orders  

Order Status   
 "PENDING", // Order submitted but not yet processesd     
 "OPEN", // Order pending, partially filled   
 "FILLED", // Order has been completely filled    
 "CANCELED", //Order is canceled and may have been partially filled.   
 "EXPIRED", // Order has expired and may have been partially filled.  
 "UNTRIGGERED", // Order conditions have not been triggered  

Order Cancelation Reason {   
 "UNKNOWN_ORDER_CANCEL_REASON"  // Unknown   
 "EXPIRED"  // Order has expired   
 "USER_CANCELED"  // User manually canceled order     
 "COULD_NOT_FILL"  // Unable to fill FOK/IOC/Post-only orders   
 "REDUCE_ONLY_CANCELED"  // Unable to fulfil reduce-only orders    
 "LIQUIDATE_CANCELED"  // Account or orders triggered liquidation resulting in automatic order cancelation  
 "INTERNAL_FAILED"  // Internal processing issues including order matching failure or L2 validation failure   
}

Request Parameters

Parameter Position Type Required Comment
symbol query string false Symbol
token query string true USDC USDT
side query string false BUY or SELL
limit query string false default at 100
beginTimeInclusive query string false Start time
endTimeExclusive query string false End time
page query string false Page numbers start from 0
orderType query string false orderType
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "orders": [
    {
      "id": "1234",
      "clientId": "1234",
      "accountId": "12345",
      "symbol": "BTC-USD",
      "side": "SELL",
      "price": "18000",
      "limitFee": "100",
      "fee": "100",
      "triggerPrice": "1.2",
      "trailingPercent": "0.12",
      "size": "100",
          "type": "LIMIT",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "expiresAt": 1647502440973,
      "status": "PENDING",
      "timeInForce": "GOOD_TIL_CANCEL",
      "postOnly": false,
      "reduceOnly": false,
      "latestMatchFillPrice": "reason",
      "cumMatchFillSize": "0.1",
      "cumMatchFillValue": "1000",
      "cumMatchFillFee": "1",
      "cumSuccessFillSize": "0.1",
      "cumSuccessFillValue": "1000",
      "cumSuccessFillFee": "1"
    }
  ],
  "totalSize": 12
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» orders [object] true none none
»» id string false none Order id
»» orderId string false none Order id
»» clientOrderId string false none Client create the Randomized id
»» accountId string false none Account ID
»» symbol string false none Symbol
»» side string false none BUY or SELL
»» price string false none Order open price
»» limitFee string false none Order open max. fee
»» fee string false none Order open actual fee
»» triggerPrice string false none Conditional order trigger price
»» trailingPercent string false none Conditional order trailing-stop
»» size string false none Order open size
»» type string false none Order type
»» createdAt integer false none Order create at
»» updatedTime integer false none Order update time
»» expiresAt integer false none Order expires at
»» status string false none Order status
»» timeInForce string false none Open order timeInForce
»» postOnly boolean false none Open Post-only order
»» reduceOnly boolean false none Open Reduce-only order
»» latestMatchFillPrice string false none Latest match fill price
»» cumMatchFillSize string false none Cumulative match fill size
»» cumMatchFillValue string false none Cumulative match fill value
»» cumMatchFillFee string false none Cumulative match fill fee
»» cumSuccessFillSize string false none Cumulative success fill size
»» cumSuccessFillValue string false none Cumulative success fill value
»» cumSuccessFillFee string false none Cumulative success fill fee
» totalSize integer true none Total order size

GET Worst Price V2

GET /v2/get-worst-price

Obtain the market price from the order book.

Request Parameters

Parameter Position Type Required Comment
symbol query string true Symbol
size query string true Order open size
side query string true BUY or SELL order
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "worstPrice": "123.00",
  "bidOnePrice": "123.00",
  "askOnePrice": "123.00"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» worstPrice string true none Lowest price
» bidOnePrice string true none Bid price
» askOnePrice string true none Ask price

POST Creating Orders V2

POST /v2/create-order


Signature content:   
orderToSign:   
OrderWithClientId = {  
humanSize: params.size,   
humanPrice: params.price,   
limitFee: params.limitFee,   
symbol: params.symbol,   
side: params.side,   
expirationIsoTimestamp: params.expiration,
clientOrderId,   
positionId, };  

TimeInForce (  
GOOD_TIL_CANCEL // Effective until canceled, default.   
FILL_OR_KILL // Immediately and completely filled or canceled.   
IMMEDIATE_OR_CANCEL // Immediately executed or canceled.    
)  

example

curl https://pro.apex.exchange/api/v2/create-order -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'symbol={symbol}&side={side}&type={type}&size={size}&price={price}&limitFee={limitFee}&expiration={expiration}&timeInForce={timeInForce}&triggerPrice={triggerPrice}&trailingPercent={trailingPercent}&clientOrderId={clientOrderId}&signature={signature}&reduceOnly=false'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()

createOrderRes = client.create_order_v2(symbol="BTC-USDC", side="BUY",
                                           type="LIMIT", size="0.01",
                                           price="20001", limitFee="0.001",
                                            accountId="330547708362228116",reduceOnly=False,
                                     expirationEpochSeconds= currentTime, timeInForce="GOOD_TIL_CANCEL")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» symbol body string true Symbol
» side body string true BUY or SELL
» type body string true "LIMIT", "MARKET","STOP_LIMIT", "STOP_MARKET", "TAKE_PROFIT_LIMIT", "TAKE_PROFIT_MARKET"
» size body string true Size
» price body string true Price
» limitFee body string true limitFee = price * size * takerFeeRate( from GET /v1/account)
» expiration body string true Order expiry time
» timeInForce body string false "GOOD_TIL_CANCEL", "FILL_OR_KILL", "IMMEDIATE_OR_CANCEL", "POST_ONLY"
» triggerPrice body string false Trigger price
» trailingPercent body string false Conditional order trailing-stop
» clientOrderId body string true Randomized client id
» signature body string true starkKey signature
» reduceOnly body string false Reduce-only

Successful Response Generation

{
  "id": "1234",
  "clientOrderId": "1234",
  "accountId": "12345",
  "symbol": "BTC-USD",
  "side": "SELL",
  "price": "18000",
  "limitFee": "100",
  "fee": "100",
  "triggerPrice": "1.2",
  "trailingPercent": "0.12",
  "size": "100",
  "type": "LIMIT",
  "createdAt": 1647502440973,
  "updatedTime": 1647502440973,
  "expiresAt": 1647502440973,
  "status": "PENDING",
  "timeInForce": "GOOD_TIL_CANCEL",
  "postOnly": false,
  "reduceOnly": false,
  "latestMatchFillPrice": "reason",
  "cumMatchFillSize": "0.1",
  "cumMatchFillValue": "1000",
  "cumMatchFillFee": "1",
  "cumSuccessFillSize": "0.1",
  "cumSuccessFillValue": "1000",
  "cumSuccessFillFee": "1"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string false none Order id
»» orderId string false none Order id
» clientOrderId string false none Client create the Randomized id
» accountId string false none Account ID
» symbol string false none Symbol
» side string false none BUY or SELL
» price string false none Order open price
» limitFee string false none Order open max. fee
» fee string false none Order open actual fee
» triggerPrice string false none Conditional order trigger price
» trailingPercent string false none Conditional order trailing-stop
» size string false none Order open size
» type string false none Order type
» createdAt integer false none Order create at
» updatedTime integer false none Order update time
» expiresAt integer false none Order expires at
» status string false none Order status
» timeInForce string false none Open order timeInForce
» postOnly boolean false none Open Post-only order
» reduceOnly boolean false none Open Reduce-only order
» latestMatchFillPrice string false none Latest match fill price
» cumMatchFillSize string false none Cumulative match fill size
» cumMatchFillValue string false none Cumulative match fill value
» cumMatchFillFee string false none Cumulative match fill fee
» cumSuccessFillSize string false none Cumulative success fill size
» cumSuccessFillValue string false none Cumulative success fill value
» cumSuccessFillFee string false none Cumulative success fill fee

POST Cancel Order V2

POST /v2/delete-order

curl https://pro.apex.exchange/api/v2/delete-order -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'id={id}&token={USDC}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

deleteOrderRes = client.delete_order(id="123456",token="USDT")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» id body string true none
» token body string true USDT or USDC

Successful Response Generation

{
  "data": "123456"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» data string true none Order ID

POST Cancel Order By ClientOrderId

POST /v2/delete-client-order-id

curl https://pro.apex.exchange/api/v2/delete-client-order-id` -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'id={id}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

deleteOrderRes = client.delete_order_by_client_order_id_v2(id="123456",token="USDT")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» id body string true none
» token body string true USDT or USDC

Successful Response Generation

{
  "data": "123456"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» data string true none Order ID

GET Open Orders V2

GET /v2/open-orders

Order type   
"UNKNOWN_ORDER_TYPE",   
 "LIMIT", //Limit price   
 "MARKET", //Market price   
 "STOP_LIMIT", //Stop limit order   
 "STOP_MARKET", //Stop market order   
 "TAKE_PROFIT_LIMIT",//Take profit limit orders   
 "TAKE_PROFIT_MARKET",//Take profit market orders  

Order Status   
 "PENDING", // Order submitted but not yet processesd   
 "OPEN", // Order pending, partially filled   
 "FILLED", // Order has been completely filled   
 "CANCELED", //Order is canceled and may have been partially filled.   
 "EXPIRED", // Order has expired and may have been partially filled.   
 "UNTRIGGERED", // Order conditions have not been triggered  

Order Cancelation Reason {   
 "UNKNOWN_ORDER_CANCEL_REASON"  // Unknown   
 "EXPIRED"  // Order has expired   
 "USER_CANCELED"  // User manually canceled order     
 "COULD_NOT_FILL"  // Unable to fill FOK/IOC/Post-only orders   
 "REDUCE_ONLY_CANCELED"  // Unable to fulfil reduce-only orders    
 "LIQUIDATE_CANCELED"  // Account or orders triggered liquidation resulting in automatic order cancelation  
 "INTERNAL_FAILED"  // Internal processing issues including order matching failure or L2 validation failure   
}

example

curl https://pro.apex.exchange/api/v2/open-orders -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

openOrdersRes = client.open_orders_v2(token="USDT")

Request Parameters

Parameter Position Type Required Comment
token query string true USDT or USDC
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none

Successful Response Generation

{
  "data": [
    {
      "id": "1234",
      "clientOrderId": "1234",
      "accountId": "12345",
      "symbol": "BTC-USDT",
      "side": "SELL",
      "price": "18000",
      "limitFee": "100",
      "fee": "100",
      "triggerPrice": "1.2",
      "trailingPercent": "0.12",
      "size": "100",
      "type": "LIMIT",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "expiresAt": 1647502440973,
      "status": "PENDING",
      "timeInForce": "GOOD_TIL_CANCEL",
      "postOnly": false,
      "reduceOnly": false,
      "latestMatchFillPrice": "reason",
      "cumMatchFillSize": "0.1",
      "cumMatchFillValue": "1000",
      "cumMatchFillFee": "1",
      "cumSuccessFillSize": "0.1",
      "cumSuccessFillValue": "1000",
      "cumSuccessFillFee": "1"
    }
  ]
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» orders [object] true none none
»» id string false none Order id
»» orderId string false none Order id
»» clientOrderId string false none Client create the Randomized id
»» accountId string false none Account ID
»» symbol string false none Symbol
»» side string false none BUY or SELL
»» price string false none Order open price
»» limitFee string false none Order open max. fee
»» fee string false none Order open actual fee
»» triggerPrice string false none Conditional order trigger price
»» trailingPercent string false none Conditional order trailing-stop
»» size string false none Order open size
»» type string false none Order type
»» createdAt integer false none Order create at
»» updatedTime integer false none Order update time
»» expiresAt integer false none Order expires at
»» status string false none Order status
»» timeInForce string false none Open order timeInForce
»» postOnly boolean false none Open Post-only order
»» reduceOnly boolean false none Open Reduce-only order
»» latestMatchFillPrice string false none Latest match fill price
»» cumMatchFillSize string false none Cumulative match fill size
»» cumMatchFillValue string false none Cumulative match fill value
»» cumMatchFillFee string false none Cumulative match fill fee
»» cumSuccessFillSize string false none Cumulative success fill size
»» cumSuccessFillValue string false none Cumulative success fill value
»» cumSuccessFillFee string false none Cumulative success fill fee

POST Cancel all Open Orders V2

POST /v2/delete-open-orders

Body Request Parameters

symbol: BTC-USDC,ETH-USDC
token: USDC

curl https://pro.apex.exchange/api/v2/delete-open-orders -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'symbol={BTC-USDC,ETH-USDC}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

deleteOrdersRes = client.delete_open_orders_v2(symbol="BTC-USDC,ETH-USDC", token="USDC")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» symbol body string false "BTC-USDC,ETH-USDC", Cancel all orders if none
» token body string true USDT or USDC

Successful Response Generation

{

}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

GET All Order History V2

GET /v2/history-orders

Order type 
 "UNKNOWN_ORDER_TYPE",   
 "LIMIT", //Limit price   
 "MARKET", //Market price   
 "STOP_LIMIT", //Stop limit order   
 "STOP_MARKET", //Stop market order   
 "TAKE_PROFIT_LIMIT",//Take profit limit orders   
 "TAKE_PROFIT_MARKET",//Take profit market orders  

Order Status   
 "PENDING", // Order submitted but not yet processesd   
 "OPEN", // Order pending, partially filled   
 "FILLED", // Order has been completely filled    
 "CANCELED", //Order is canceled and may have been partially filled.    
 "EXPIRED", // Order has expired and may have been partially filled.   
 "UNTRIGGERED", // Order conditions have not been triggered  

Order Cancelation Reason {   
 "UNKNOWN_ORDER_CANCEL_REASON"  // Unknown   
 "EXPIRED"  // Order has expired   
 "USER_CANCELED"  // User manually canceled order     
 "COULD_NOT_FILL"  // Unable to fill FOK/IOC/Post-only orders   
 "REDUCE_ONLY_CANCELED"  // Unable to fulfil reduce-only orders    
 "LIQUIDATE_CANCELED"  // Account or orders triggered liquidation resulting in automatic order cancelation  
 "INTERNAL_FAILED"  // Internal processing issues including order matching failure or L2 validation failure   
}

example

curl https://pro.apex.exchange/api/v2/history-orders -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

historyOrdersRes = client.history_orders_v2(token="USDT")

Request Parameters

Parameter Position Type Required Comment
token query string true USDT or USDC
symbol query string false none
status query string false none
side query string false BUY or SELL
type query string false "LIMIT", "MARKET","STOP_LIMIT", "STOP_MARKET", "TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"
limit query string false default 100
beginTimeInclusive query string false Start time
endTimeExclusive query string false End time
page query string false Page numbers start from 0
orderType query string false "ACTIVE","CONDITION","HISTORY"
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "orders": [
    {
      "id": "1234",
      "clientOrderId": "1234",
      "accountId": "12345",
      "symbol": "BTC-USD",
      "side": "SELL",
      "price": "18000",
      "limitFee": "100",
      "fee": "100",
      "triggerPrice": "1.2",
      "trailingPercent": "0.12",
      "size": "100",
      "type": "LIMIT",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "expiresAt": 1647502440973,
      "status": "PENDING",
      "timeInForce": "GOOD_TIL_CANCEL",
      "postOnly": false,
      "reduceOnly": false,
      "latestMatchFillPrice": "reason",
      "cumMatchFillSize": "0.1",
      "cumMatchFillValue": "1000",
      "cumMatchFillFee": "1",
      "cumSuccessFillSize": "0.1",
      "cumSuccessFillValue": "1000",
      "cumSuccessFillFee": "1"
    }
  ],
  "totalSize": 12
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» orders [object] true none none
»» id string false none Order id
»» orderId string false none Order id
»» clientOrderId string false none Client create the Randomized id
»» accountId string false none Account ID
»» symbol string false none Symbol
»» side string false none BUY or SELL
»» price string false none Order open price
»» limitFee string false none Order open max. fee
»» fee string false none Order open actual fee
»» triggerPrice string false none Conditional order trigger price
»» trailingPercent string false none Conditional order trailing-stop
»» size string false none Order open size
»» type string false none Order type
»» createdAt integer false none Order create at
»» updatedTime integer false none Order update time
»» expiresAt integer false none Order expires at
»» status string false none Order status
»» timeInForce string false none Open order timeInForce
»» postOnly boolean false none Open Post-only order
»» reduceOnly boolean false none Open Reduce-only order
»» latestMatchFillPrice string false none Latest match fill price
»» cumMatchFillSize string false none Cumulative match fill size
»» cumMatchFillValue string false none Cumulative match fill value
»» cumMatchFillFee string false none Cumulative match fill fee
»» cumSuccessFillSize string false none Cumulative success fill size
»» cumSuccessFillValue string false none Cumulative success fill value
»» cumSuccessFillFee string false none Cumulative success fill fee
» totalSize integer true none total order size

GET Order ID V2

GET /v2/get-order

curl https://pro.apex.exchange/api/v2/get-order?id={id} -h 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

getOrderRes = client.get_order_v2(id="123456",token="USDT")

Request Parameters

Parameter Position Type Required Comment
id query string true none
token query string true USDT or USDC
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "id": "123456",
  "clientOrderId": "1234",
  "accountId": "afoo",
  "symbol": "BTC-USDT",
  "side": "SELL",
  "price": "18000",
  "triggerPrice": "1.2",
  "trailingPercent": "0.12",
  "size": "100",
  "type": "LIMIT",
  "createdAt": 1647502440973,
  "unfillableAt": 1647502440973,
  "expiresAt": 1647502440973,
  "status": "PENDING",
  "timeInForce": "GOOD_TIL_CANCEL",
  "postOnly": false,
  "cancelReason": "reason"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string false none Order id
» orderId string false none Order id
» clientOrderId string false none Client create the Randomized id
» accountId string false none Account ID
» symbol string false none Symbol
» side string false none BUY or SELL
» price string false none Order open price
» limitFee string false none Order open max. fee
» fee string false none Order open actual fee
» triggerPrice string false none Conditional order trigger price
» trailingPercent string false none Conditional order trailing-stop
» size string false none Order open size
» type string false none Order type
» createdAt integer false none Order create at
» updatedTime integer false none Order update time
» expiresAt integer false none Order expires at
» status string false none Order status
» timeInForce string false none Open order timeInForce
» postOnly boolean false none Open Post-only order
» reduceOnly boolean false none Open Reduce-only order
» latestMatchFillPrice string false none Latest match fill price
» cumMatchFillSize string false none Cumulative match fill size
» cumMatchFillValue string false none Cumulative match fill value
» cumMatchFillFee string false none Cumulative match fill fee
» cumSuccessFillSize string false none Cumulative success fill size
» cumSuccessFillValue string false none Cumulative success fill value
» cumSuccessFillFee string false none Cumulative success fill fee

GET Order by clientOrderId V2

GET /v2/order-by-client-order-id"

curl https://pro.apex.exchange/api/v2/order-by-client-order-id?id={id} -h 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

getOrderRes = client.get_order_by_client_order_id_v2(id="123456",token="USDT")

Request Parameters

Parameter Position Type Required Comment
id query string true none
token query string true USDC or USDT
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "id": "123456",
  "clientOrderId": "1234",
  "accountId": "afoo",
  "symbol": "BTC-USD",
  "side": "SELL",
  "price": "18000",
  "triggerPrice": "1.2",
  "trailingPercent": "0.12",
  "size": "100",
  "type": "LIMIT",
  "createdAt": 1647502440973,
  "unfillableAt": 1647502440973,
  "expiresAt": 1647502440973,
  "status": "PENDING",
  "timeInForce": "GOOD_TIL_CANCEL",
  "postOnly": false,
  "cancelReason": "reason"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string false none Order id
» orderId string false none Order id
» clientOrderId string false none Client create the Randomized id
» accountId string false none Account ID
» symbol string false none Symbol
» side string false none BUY or SELL
» price string false none Order open price
» limitFee string false none Order open max. fee
» fee string false none Order open actual fee
» triggerPrice string false none Conditional order trigger price
» trailingPercent string false none Conditional order trailing-stop
» size string false none Order open size
» type string false none Order type
» createdAt integer false none Order create at
» updatedTime integer false none Order update time
» expiresAt integer false none Order expires at
» status string false none Order status
» timeInForce string false none Open order timeInForce
» postOnly boolean false none Open Post-only order
» reduceOnly boolean false none Open Reduce-only order
» latestMatchFillPrice string false none Latest match fill price
» cumMatchFillSize string false none Cumulative match fill size
» cumMatchFillValue string false none Cumulative match fill value
» cumMatchFillFee string false none Cumulative match fill fee
» cumSuccessFillSize string false none Cumulative success fill size
» cumSuccessFillValue string false none Cumulative success fill value
» cumSuccessFillFee string false none Cumulative success fill fee

GET Funding Rate V2

GET /v2/funding

curl https://pro.apex.exchange/api/v2/funding?limit={limit}&page={page}&symbol={symbol}&side={side}&token={token} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

fundingRes = client.funding_v2(limit=100,page=0,symbol="BTC-USDC",side="BUY", token="USDT")

Request Parameters

Parameter Position Type Required Comment
symbol query string false none
token query string true USDT or USDC
limit query string false Default at 100
page query string false Page numbers start from 0
beginTimeInclusive query string false Start time
endTimeExclusive query string false End time
side query string false Side
status query string false Order status
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "fundingValues": [
    {
      "id": "1234",
      "symbol": "BTC-USD",
      "fundingValue": "10000",
      "rate": "0.0000125000",
      "positionSize": "500",
      "price": "90",
      "side": "LONG",
      "status": "SUCCESS",
      "fundingTime": 1647502440973,
      "transactionId": "1234556"
    }
  ],
  "totalSize": 11
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» fundingValues [object] true none none
»» id string false none id
»» symbol string false none Symbol
»» fundingValue string false none Funding fee value
»» rate string false none Funding rate
»» positionSize string false none Open position size
»» price string false none Symbol price
»» side string false none Position side
»» status string false none Position funding status
»» fundingTime integer false none Funding fee time
»» transactionId string false none Successful wallet transaction ID
» totalSize integer true none Total size

GET User Historial Profit and Loss V2

GET /v2/historical-pnl

curl https://pro.apex.exchange/api/v1/historical-pnl?limit={limit}&page={page}&beginTimeInclusive={beginTimeInclusive}&endTimeExclusive={endTimeExclusive}&type={type}&symbol={symbol}&token={token} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

historicalPnlRes = client.historical_pnl_v2(limit=100,page=0,beginTimeInclusive=1651406864000,endTimeExclusive=1657105971171,symbol="BTC-USDC", token="USDT")

Request Parameters

Parameter Position Type Required Comment
token query string true USDT or USDC
beginTimeInclusive query string false StartTime
endTimeExclusive query string false EndTime
type query string false Position type
symbol query string false Symbol
page query string false Page numbers start from 0
limit query string false Default at 100
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "historicalPnl": [
    { "symbol": "BTC-USDC",
      "size": "1.0000",
      "totalPnl": "1.0000",
      "price": "1.0000",
      "createdAt": 1647502440973,
      "type": "CLOSE_POSITION",
      "isLiquidate": false,
      "isDeleverage": false
    }
  ],
  "totalSize": 12
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Position Type Required Comment
» historicalPnl [object] true none none
»» size string false none Size
»» totalPnl string false none Closing profit and loss
»» price string false none Price
»» exitPrice string false none Closing price
»» createdAt integer false none Time
»» type string false none postion type
»» isLiquidate boolean false none Liquidate
»» isDeleverage boolean false none ADL
» totalSize integer true none none

GET Yesterday's Profit & Loss V2

GET /v2/yesterday-pnl

curl https://pro.apex.exchange/api/v2/yesterday-pnl?token={token} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

yesterdayPnlRes = client.yesterday_pnl_v2()

Request Parameters

Parameter Position Type Required Comment
token query string true USDT or USDC
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "data": "11.11"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» data string true none Profit and loss value

GET Historical Asset Value

GET /v2/history-value

curl https://pro.apex.exchange/api/v2/history-value?token={token} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

historyValueRes = client.history_value_v2(token="USDT")

Request Parameters

Parameter Position Type Required Comment
token query string true USDT or USDC
endTime query int64 false Start time
startTime query int64 false End time
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "historyValues": [
    {
      "accountTotalValue": "123.11",
      "dateTime": 1651406864000
    }
  ]
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» historyValues [object] true none none
»» accountTotalValue string false none Assets
»» dateTime integer false none Assets date and time snapshot

POST Sets the initial margin rate of a contract V2

POST /v1/set-initial-margin-rate

curl https://pro.apex.exchange/api/v2/set-initial-margin-rate?token={token} -H "Content-Type: application/x-www-form-urlencoded" -H "APEX-SIGNATURE: ***" -H "APEX-TIMESTAMP: ***" -H "APEX-API-KEY: ***" -H "APEX-PASSPHRASE: ***" -X POST -d "symbol=BTC-USDC&initialMarginRate=0.02"

from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

setInitialMarginRateRes = client.set_initial_margin_rate_v2(symbol="BTC-USDT",initialMarginRate="0.1",token='USDT')
print(setInitialMarginRateRes)

Body

symbol: string
initialMarginRate: string
token: string

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» symbol body string true symbol
» token body string true USDC or USDT
» initialMarginRate body string true initialMarginRate(the reciprocal of the opening leverage)

Successful Response Generation

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

PrivateApi

v1.0.0

POST Generate nonce

POST /v1/generate-nonce

Generate and obtain nonce before registration. The nonce is used to assemble the signature field upon registration.

from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key="0x*****")
configs = client.configs()
stark_key_pair_with_y_coordinate = client.derive_stark_key(client.default_address)
nonceRes = client.generate_nonce(starkKey=stark_key_pair_with_y_coordinate['public_key'],ethAddress=client.default_address,chainId="5")
curl https://pro.apex.exchange/api/v1/generate-nonce -X POST -d 'starkKey={starkKey}&ethAddress={ethAddress}&chainId={chainId}'

Request Parameters

Parameter Position Type Required Comment
body body object false none
» starkKey body string true User's starkKey
» ethAddress body string true User's Ethereum address
» chainId body string true API trading users to enter "1" on mainnet

Successful Response Generation

{
  "data": {
    "nonce": "1123940951220551680",
    "nonceExpired": 1648727402292
  }
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» nonce string true none nonce
» nonceExpired integer true none The time at which nonce expires, please complete registration before this time

POST Registration & Onboarding

POST /v1/onboarding

  1. Consolidate onboarding data and generate digital signature via your wallet. You can refer to python sdk, derive_stark_key for more information
  2. Create your Stark Key pair with your signature, including (publicKey, publicKeyYCoordinate, privateKey)
  3. Send consolidated onboarding data request to the server for response to user registration data, including API keys
curl https://pro.apex.exchange/api/v1/onboarding -H 'APEX-SIGNATURE: ***' -H 'APEX-ETHEREUM-ADDRESS: ***' -X POST -d 'starkKey={starkKey}&starkKeyYCoordinate={starkKeyYCoordinate}&ethereumAddress={ethereumAddress}&referredByAffiliateLink={referredByAffiliateLink}&country={country}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key="0xb7daaaaaaaaaaaaaaaa")

configs = client.configs()

stark_key_pair_with_y_coordinate = client.derive_stark_key(client.default_address)

nonceRes = client.generate_nonce(starkKey=stark_key_pair_with_y_coordinate['public_key'],ethAddress=client.default_address,chainId="5")

regRes = client.register_user(nonce=nonceRes['data']['nonce'],starkKey=stark_key_pair_with_y_coordinate['public_key'],stark_public_key_y_coordinate=stark_key_pair_with_y_coordinate['public_key_y_coordinate'],ethereum_address=client.default_address)

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Onboarding signature
APEX-ETHEREUM-ADDRESS header string true Ethereum address
body body object false none
» starkKey body string true Public starkKey associated with the key-pair you created.
» starkKeyYCoordinate body string true Public starkKey Y-Coordinate associated with the key-pair you created.
» ethereumAddress body string true Ethereum address associated with the user being created.
» referredByAffiliateLink body string false Referred affiliate link
» country body string false Country code: Must be ISO 3166-1 Alpha-2 compliant

Successful Response Generation

{
  "apiKey": {
    "key": "290xxxxxx",
    "passphrase": "S6xxxxx",
    "secret": "KQ3xxxx"
  },
  "user": {
    "ethereumAddress": "0x09xxxxxx",
    "isRegistered": true,
    "email": "email@apex.exchange",
    "username": "man",
    "referredByAffiliateLink": "url",
    "isEmailVerified": false,
    "emailNotifyGeneralEnable": false,
    "emailNotifyTradingEnable": false,
    "emailNotifyAccountEnable": false,
    "popupNotifyTradingEnable": false
  },
  "account": {
    "starkKey": "180913017c740260fea4b2c62828a4008ca8b0d6e4",
    "positionId": "1812",
    "id": "1812",
    "takerFeeRate": "0.0005",
    "makerFeeRate": "0.0005",
    "createdAt": 1647502440973,
    "wallets": [
      {
        "userId": "123456",
        "accountId": "123455667",
        "asset": "USDC",
        "balance": "1000",
        "pendingDepositAmount": "100.1",
        "pendingWithdrawAmount": "100.1",
        "pendingTransferOutAmount": "100.1",
        "pendingTransferInAmount": "100.1"
      }
    ],
    "openPositions": [
      {
        "symbol": "BTC-USD",
        "side": "LONG",
        "size": "1000",
        "entryPrice": "100",
        "fee": "50",
        "fundingFee": "100",
        "createdAt": 1647502440973,
        "updatedTime": 1647502440973,
        "lightNumbers": "1"
      }
    ],
    "id": "id"
  }
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» apiKey object true none none
»» key string true none Placed in request header for sending to server
»» passphrase string true none Placed in request header for sending to server
»» secret string true none Used to generate signature
» user object true none none
»» ethereumAddress string true none Ethereum address
»» isRegistered boolean true none Registration confirmation
»» email string true none Email
»» username string true none Username
»» referredByAffiliateLink string true none referred Affiliate Link
»» isEmailVerified boolean true none Email binding confirmation
»» emailNotifyGeneralEnable boolean true none Newsletter, Market Updates, Product notify
»» emailNotifyTradingEnable boolean true none Deposits、Withdrawals, Account notify
»» emailNotifyAccountEnable boolean true none Order and Liquidation notify
»» popupNotifyTradingEnable boolean true none Trading pop-up notify
» account object true none none
»» starkKey string true none User's starkKey
»» positionId string true none User's account ID
»» id string true none User's account ID
»» makerFeeRate string true none Maker fee rate
»» takerFeeRate string true none Taker fee rate
»» createdAt integer true none Created time
»» wallets [object] true none User wallet
»»» userId string false none User ID
»»» accountId string false none Account ID
»»» asset string false none Asset
»»» balance string false none Wallet balance
»» pendingDepositAmount string true none Pending deposit amount
»» pendingWithdrawAmount string true none Pending withdrawal amount
»» pendingTransferOutAmount string true none Pending outbound transfer amount
»» pendingTransferInAmount string true none Pending inbound transfer amount
»» openPositions [object] true none Open positions
»» symbol string false none Symbol
»» side string false none Side
»» size string false none Size
»» entryPrice string false none Entry price
»» fee string false none Order fee
»» createdAt integer false none Created at
»» updatedTime integer false none Updated time
»» fundingFee string false none Funding fee
»» lightNumbers string false none ADL ranking

GET Retrieve User Data

GET /v1/user

curl https://pro.apex.exchange/api/v1/user -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

userRes = client.get_user()

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "ethereumAddress": "0x091aaaaaaaaaa",
  "isRegistered": true,
  "email": "email@apex.exchange",
  "username": "supersam15o",
  "userData": {},
  "isEmailVerified": false,
  "emailNotifyGeneralEnable": false,
  "emailNotifyTradingEnable": false,
  "emailNotifyAccountEnable": false,
  "popupNotifyTradingEnable": false
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» ethereumAddress string true none Ethereum address
» isRegistered boolean true none Registration completed
» email string true none Email
» username string true none Username
» userData object true none none
» isEmailVerified boolean true none none
» emailNotifyGeneralEnable string true none Newsletter, market and product updates
» emailNotifyTradingEnable string true none Order and liquidation updates
» emailNotifyAccountEnable string true none Deposit, withdrawal and account updates
» popupNotifyTradingEnable string true none Enable trading notifications

POST Edit User Data

POST /v1/modify-user

curl https://pro.apex.exchange/api/v1/modify-user -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'userData={userData}&email={email}&username={username}&isSharingUsername={isSharingUsername}&isSharingAddress={isSharingAddress}&country={country}&emailNotifyGeneralEnable={emailNotifyGeneralEnable}&emailNotifyTradingEnable={emailNotifyTradingEnable}&emailNotifyAccountEnable={emailNotifyAccountEnable}&popupNotifyTradingEnable={popupNotifyTradingEnable}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

userRes = client.modify_user(username="pythonTest",email="11@aa.com",emailNotifyGeneralEnable="true")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» userData body string false none
» email body string false Email
» username body string false Username
» isSharingUsername body string false none
» isSharingAddress body string false none
» country body string false country
» emailNotifyGeneralEnable body string false Newsletter, market and product updates
» emailNotifyTradingEnable body string false Order and liquidation updates
» emailNotifyAccountEnable body string false Deposit, withdrawal and account updates
» popupNotifyTradingEnable body string false Enable trading notifications

Successful Response Generation

{
  "ethereumAddress": "0x091aaaaaaaaaa",
  "isRegistered": true,
  "email": "email@apex.exchange",
  "username": "supersam15o",
  "userData": {},
  "isEmailVerified": false,
  "emailNotifyGeneralEnable": false,
  "emailNotifyTradingEnable": false,
  "emailNotifyAccountEnable": false,
  "popupNotifyTradingEnable": false
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» ethereumAddress string true none Ethereum address
» isRegistered boolean true none Registration completed
» email string true none Email
» username string true none Username
» userData object true none none
» isEmailVerified boolean true none none
» emailNotifyGeneralEnable string true none Newsletter, market and product updates
» emailNotifyTradingEnable string true none Order and liquidation updates
» emailNotifyAccountEnable string true none Deposit, withdrawal and account updates
» popupNotifyTradingEnable string true none Enable trading notifications

GET Retrieve User Account Data

GET /v1/account

Get an account for a user by id. Using the client, the id will be generated with client information and an Ethereum address.

curl https://pro.apex.exchange/api/v1/account -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

accountRes = client.get_account()

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none

Successful Response Generation

{
  "starkKey": "180913017c740260fea4b2c62828a4008ca8b0d6e4",
  "positionId": "1812",
  "takerFeeRate": "0.0005",
  "makerFeeRate": "0.0005",
  "createdAt": 1647502440973,
  "wallets": [
    {
      "userId": "123456",
      "accountId": "123455667",
      "asset": "USDC",
      "balance": "1000",
      "pendingDepositAmount": "100.1",
      "pendingWithdrawAmount": "100.1",
      "pendingTransferOutAmount": "100.1",
      "pendingTransferInAmount": "100.1"
    }
  ],
  "openPositions": [
    {
            "symbol": "BTC-USD",
            "side": "LONG",
            "size": "1000",
            "entryPrice": "100",
            "fee": "50",
            "fundingFee": "100",
            "createdAt": 1647502440973,
            "updatedTime": 1647502440973,
            "lightNumbers": "1"
    }
  ],
  "id": "id"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
»» starkKey string true none User's starkKey
»» positionId string true none User's account ID
»» id string true none User's account ID
»» makerFeeRate string true none Maker fee rate
»» takerFeeRate string true none Taker fee rate
»» createdAt integer true none Created time
»» wallets [object] true none User wallet
»»» userId string false none User ID
»»» accountId string false none Account ID
»»» asset string false none Asset
»»» balance string false none Wallet balance
»» pendingDepositAmount string true none Pending deposit amount
»» pendingWithdrawAmount string true none Pending withdrawal amount
»» pendingTransferOutAmount string true none Pending outbound transfer amount
»» pendingTransferInAmount string true none Pending inbound transfer amount
»» openPositions [object] true none Open positions
»» symbol string false none Symbol
»» side string false none Side
»» size string false none Size
»» entryPrice string false none Entry price
»» fee string false none Order fee
»» createdAt integer false none Created at
»» updatedTime integer false none Updated time
»» fundingFee string false none Funding fee
»» lightNumbers string false none ADL ranking

GET Retrieve User Account balance

GET /v1/account-balance

curl https://pro.apex.exchange/api/v1/account-balance -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

accountRes = client.get_account_balance()

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "totalEquityValue": "100.000000",
  "availableBalance": "100.000000",
  "initialMargin": "100.000000",
  "maintenanceMargin": "100.000000",
  "symbolToOraclePrice": {
    "BTC-USDC": {
      "oraclePrice": "20000",
      "createdTime": 124566
    }
  }
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status code 200

Parameter Type Required Limit Comment
» totalEquityValue string true none
» availableBalance string true none
» initialMargin string true none
» maintenanceMargin string true none
» symbolToOraclePrice object true none
»» BTC-USDC object true none
»»» oraclePrice string true none
»»» createdTime integer true none

GET Retrieve User Deposit Data

GET /v1/transfers

curl https://pro.apex.exchange/api/v1/transfers?limit={limit}&page={page}&currencyId={currencyId}&chainIds={chainIds} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

transfersRes = client.transfers(limit=100,page=0,currencyId="USDC",chainIds="1,5,13")
Deposit Status{   
UNKNOWN_DEPOSIT_STATUS 0 // Unknown.  
PENDING_L1_CREATING 1 // Deposit pending on L1, awaiting confirmation.   
PENDING_RISK_CHECKING 2 // Confirmed, risk check in progress.  
PENDING_CENSORING 3 // Risk check complete, awaiting verification.  
SUCCESS 4 // Deposit success, your funds have been sent to your wallet. Awaiting L2 validation.   
SUCCESS_L2_APPROVED 5 // L2 approved.   
CANCELED 6 // L1 confirmation failure, deposit has been canceled.  
FAILED_RISK_CHECK_FAILURE 7 // Deposit has failed due to failed risk check.     
FAILED_CENSOR_FAILURE 8 // Deposit has failed due to inaccurate data, data entries have been rolled back.   
FAILED_L2_REJECTED 9 // Deposit has failed due to failed L2 approval. Deposited funds have been removed from your account.   
}  

Withdrawal Status{   
UNKNOWN_WITHDRAW_STATUS 0 // Unknown.  
PENDING_RISK_CHECKING 1 // Risk check in progress.  
PENDING_CENSORING 2 // Pending verification.  
PENDING_L2_APPROVING 3 // Approved, awaiting L2 validation.  
PENDING_L1_CONFIRMING 4 // L2 validation complete, pending L1 confirmation.  
PENDING_L1_WITHDRAWING 5 // Withdrawal request on L1 complete, awaiting user withdrawal.  
SUCCESS 6 // Withdrawal success, your withdrawn funds can now be found in your wallet.   
FAILED_RISK_CHECK_FAILURE 7 // Withdrawal unsuccessful due to failed risk check.   
FAILED_CENSOR_FAILURE 8 // Withdrawal unsuccessful due to inaccurate data, data entries have been rolled back.   
FAILED_L2_REJECTED 9 // Withdrawal unsuccessful due to failed L2 approval and roll back has commenced.   
}  

Cross-Chain Withdrawal Status{   
UNKNOWN_CROSS_WITHDRAW_STATUS 0 // Unknown.  
PENDING_CROSS_WITHDRAW_CHECKING 1 // Pending chain verification.  
SUCCESS_CROSS_WITHDRAW_SUBMIT_CENSOR 2  
PENDING_CROSS_WITHDRAW__CENSOR_CHECKING_ACCOUNT 3 //  
PENDING_CROSS_WITHDRAW_CENSORING 4 // Pending data verification.  
PENDING_CROSS_WITHDRAW_L2_APPROVING 5 // Verification successful, awaiting L2 approval.  
PENDING_CROSS_WITHDRAW_L1_SUBMIT 6 //Approved, submitting to L1.  
PENDING_CROSS_WITHDRAW_L1_CONFIRMING 7 // L1 submission successful, pending L1 validation.  
CROSS_WITHDRAW_SUCCESS 8 // Withdrawal successful.  
FAILED_CROSS_WITHDRAW_TRANSFER_REJECTED 9 /Transfer rejected.  
FAILED_CROSS_WITHDRAW__CENSOR_CHECKING_ACCOUNT_REJECTED 10 //Account verification rejected.   
FAILED_CROSS_WITHDRAW_CENSORING 11 //Inaccurate validation data.   
FAILED_CROSS_L2_REJECTED 12 // Transfer has failed. L2 validation rejection, roll back has commenced.   
FAILED_CROSS_WITHDRAW_L1_SUBMIT_REJECTED 13  
FAILED_CROSS_WITHDRAW_L1_REJECTED 14// Withdrawal request failed, L1 transfer unsuccessful.   
}  

Cross-Chain Deposit Status{   
UNKNOWN_CROSS_DEPOSIT_STATUS 0 //  Unknown.  
PENDING_CROSS_DEPOSIT_L1_CREATING 1 // Deposit confirmed on L1, creating transaction.  
PENDING_CROSS_DEPOSIT_L2_TRIGGER 2 // Awaiting trigger for transfer to L2.  
PENDING_CROSS_DEPOSIT_CENSOR_CHECKING 3 // L1 deposit successful, awaiting transfer to L2.  
SUCCESS_CROSS_DEPOSIT_SUBMIT_CENSOR 4  
PENDING_CROSS_DEPOSIT_CENSOR_CHECKING_ACCOUNT 5 //  
PENDING_CROSS_DEPOSIT_CENSORING 6 // Confirmed, verification in progress.  
PENDING_CROSS_DEPOSIT_L2_APPROVING 7 // Pending L2 approval.  
CROSS_DEPOSIT_SUCCESS 8 //Deposit successful.   
FAILED_CROSS_DEPOSIT_TRANSFER_REJECTED 9 //Transfer rejected.  
FAILED_CROSS_DEPOSIT_CENSOR_CHECKING_ACCOUNT_REJECTED 10 //User account error found.  
CROSS_DEPOSIT_CENSORING 11 //Inaccurate validation data.   
FAILED_CROSS_L2_REJECTED 12 // Transfer has failed. L2 validation rejection, roll back has commenced.   
}  

Fast Withdrawal Status{   
UNKNOWN_FAST_WITHDRAW_STATUS 0 // Unknown.  
PENDING_FAST_WITHDRAW_CHECKING 1 //Pending checks.  
PENDING_FAST_WITHDRAW_SUBMIT 2 //Submitted for checking, creating txid.  
PENDING_FAST_WITHDRAW_CHECKING_ACCOUNT 3 // PENDING_FAST_WITHDRAW_CENSORING 4 //Pending data verification.  
PENDING_FAST_WITHDRAW_L1_SUBMIT 5 //Confirmed, awaiting send to L1 .  
PENDING_FAST_WITHDRAW_L1_CONFIRMING 6 // Confirmed, pending L1 confirmation.  
PENDING_FAST_WITHDRAW_CENSORING_CONFIRMING 7 //Pending verification, awaiting confirmation of transfer.  
PENDING_FAST_WITHDRAW_L2_APPROVING 8 // Verification successful, pending L2 approval.  
FAST_WITHDRAW_SUCCESS 9 // Withdrawal successful, your funds can be found in your wallet.   
FAILED_FAST_WITHDRAW_TRANSFER_REJECTED 10 //Transfer rejected.  
FAILED_FAST_WITHDRAW_CHECKING_ACCOUNT_REJECTED 11 //User account error found.  
FAILED_FAST_WITHDRAW_CENSORING 12 //Inaccurate validation data.   
FAILED_FAST_WITHDRAW_L1_SUBMIB_REJECTED 13 // Withdrawal has failed, unsuccessful transfer to L1.  
FAILED_FAST_WITHDRAW_L1_REJECTED 14 // Withdrawal unsuccessful, request rejected on L1.  
FAILED_FAST_WITHDRAW_L2_REJECTED 15 // L2 validation rejection, roll back has commenced.
PENDING_L1_WITHDRAWING  16 // Status: Click for withdrawal smart contract.  
}  

Request Parameters

Parameters Position Type Required Comments
limit query integer false Page limit default at 100
page query integer false Page numbers start from 0
currencyId query string false Filter to show only currency ID, all will be searched if the field is empty
beginTimeInclusive query integer false Start time
endTimeExclusive query string false End time
chainIds query string false Check for multiple chainID records, separated by commas
transferType query string false Check for multiple transferType records, separated by commas
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "transfers": [
    {
      "id": "foo",
      "type": "DEPOSIT",
      "currencyId": "USDC",
      "amount": "3000",
      "transactionHash": "0x12aaaaaaaa",
      "status": "PENDING",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "confirmedAt": 1647502440973,
      "clientId": "12345",
      "confirmedCount": 12,
      "requiredCount": 12,
      "orderId": "12345",
      "chainId": "1",
      "fee": "10.0"
    }
  ],
  "totalSize": 123
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» transfers [object] true none none
»» id string false none none
»» type string false none DEPOSIT, WITHDRAW or FAST_WITHDRAW
»» CurrencyId string false none Currency ID
»» Amount string false none Amount
»» transactionHash string false none Transaction hash
»» status string false none Status
»» createdAt integer false none Created at
»» confirmedAt integer false none Confirmed time (only for withdrawals)
»» updatedTime string true none Only applicable for deposits
»» confirmedCount string true none Number of confirmations on L1, only for deposits
»» requiredCount string true none Number of confirmations required for deposits on L1, only for deposits
»» clientId string false none Client to create a randomized id (only for withdrawal)
»» orderId string true none Success Wallet Transaction Id
»» chainId string true none Supported chainId
»» fee string true none Fee
» totalSize string true none Total size

GET Retrieve User Withdrawal List

GET /v1/withdraw-list

curl https://pro.apex.exchange/api/v1/withdraw-list?limit={limit}&page={page}&beginTimeInclusive={beginTimeInclusive}&endTimeExclusive={endTimeExclusive} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

withdrawListRes = client.withdraw_list(limit=100,page=0,beginTimeInclusive=1651406864000,endTimeExclusive=1657105971171)

Request Parameters

Parameter Position Type Required Comment
limit query integer false Page limit default at 100
page query integer false Page numbers start from 0
beginTimeInclusive query integer false Start time
endTimeExclusive query string false End time
transferType query string false Check for multiple transferType records, separated by commas
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "transfers": [
    {
      "id": "foo",
      "type": "WITHDRAW",
      "currencyId": "USDC",
      "amount": "3000",
      "transactionHash": "0x12aaaaaaaa",
      "status": "PENDING_L2_APPROVING",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "confirmedAt": 1647502440973,
      "clientId": "12345",
      "orderId": "12345",
      "chainId": "1",
      "fee": "10.0"
    }
  ],
  "totalSize": 123
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» transfers [object] true none none
»» id string false none none
»» type string false none DEPOSIT, WITHDRAW or FAST_WITHDRAW
»» CurrencyId string false none Currency ID
»» Amount string false none Amount
»» transactionHash string false none Transaction hash
»» status string false none Status
»» createdAt integer false none Created at
»» confirmedAt integer false none Confirmed time (only for withdrawals)
»» updatedTime string false none Only applicable for deposits
»» confirmedCount string false none Number of confirmations on L1, only for deposits
»» requiredCount string false none Number of confirmations required for deposits on L1, only for deposits
»» clientId string false none client create the Randomized id (only for withdrawal)
»» orderId string true none Success Wallet Transaction Id
»» chainId string false none Supported chainId
»» fee string false none Fee
»» withdrawStatus string false none PENDING_L2_APPROVING,SUCCESS : Withdrawal status, search for multiple statuses separated by commas
» totalSize string true none none

POST User Withdrawal

POST /v1/create-withdrawal

withdrawalToSign = {  
humanAmount: params.amount,  
expirationIsoTimestamp: params.expiration,  
clientId,  
positionId,  
};  

example

curl https://pro.apex.exchange/api/v1/create-withdrawal -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'amount={amount}&clientId={clientId}&asset={asset}&expiration={expiration}&signature={signature}'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()

createWithdrawRes = client.create_withdrawal(amount='1001',expirationEpochSeconds=currentTime,asset='USDC')

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» amount body string true Amount
» clientId body string true Unique id of the client associated with the withdrawal. Must be <= 40 characters. When using the client, if not included, will be randomly generated by the client.
» expiration body string true Date and time at which the withdrawal expires if it has not been completed. Expiration must be at least seven days in the future.
» asset body string true Asset (in USDC) being withdrawn.
» signature body string true The signature for the transfer, signed with the account's STARK private key.

Successful Response Generation

{
  "id": "1234455",
  "type": "WITHDRAW"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string true none id
» type string true none type

POST User Withdrawal to Designated Address

POST /v1/create-withdrawal-to-address

Transfer funds from L1 to a designated Ethereum address without registering for a corresponding StarkKey tagged to the Ethereum address.

withdrawalToSign = {
humanAmount: params.amount,
expirationIsoTimestamp: params.expiration,
clientId,
positionId,
ethAddress,
};

example

curl https://pro.apex.exchange/api/v1/create-withdrawal -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'amount={amount}&clientId={clientId}&asset={asset}&expiration={expiration}&signature={signature}&ethAddress={ethAddress}'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()

createWithdrawRes = client.create_withdrawal(amount='1001',expirationEpochSeconds=currentTime,asset='USDC',ethAddress="0x***")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string Request signature Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» amount body string true Withdraw Amount
» clientId body string true Unique id of the client associated with the withdrawal. Must be <= 40 characters. When using the client, if not included, will be randomly generated by the client.
» expiration body string true Date and time at which the withdrawal expires if it has not been completed. Expiration must be at least seven days in the future.
» asset body string true Asset(in USDC) being withdrawn.
» signature body string true The signature for the transfer, signed with the account's STARK private key.
» ethAddress body string false Withdraw only to your registered Ethereum address.

Successful Response Generation

{
  "id": "1234455",
  "type": "WITHDRAW"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string true none none
» type string true none Withdrawal type

POST User Fast Withdrawal

POST /v1/fast-withdraw

fact = this.starkLib.factRegistry.getTransferErc20Fact({  
recipient: toEthAddress,  
tokenAddress: usdcAddress,  
tokenDecimals: 6,  
humanAmount: params.Amount,  
salt: nonceFromClientId(clientId),  
});     

const transferToSign = {  
senderPositionId: accountId,  
receiverPositionId: fastWithdrawAccountId,  
receiverPublicKey: fastWithdrawL2Key,  
factRegistryAddress: fastWithdrawFactRegisterAddress,  
fact,  
humanAmount: params.amount,  
clientId,  
expirationIsoTimestamp: params.expiration,  
};

example

curl https://pro.apex.exchange/api/v1/fast-withdraw -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'amount={amount}&clientId={clientId}&asset={asset}&expiration={expiration}&signature={signature}&ethAddress={ethAddress}&erc20Address={erc20Address}&fee={fee}&lpAccountId={lpAccountId}&chainId={chainId}'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()
feeRes = client.uncommon_withdraw_fee(amount='1002',chainId='56')
fastWithdrawRes = client.fast_withdrawal(amount='1002',expirationEpochSeconds=currentTime,asset='USDC',fee=feeRes['data']['fee'])

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» amount body string false Withdrawal amount
» clientId body string false Unique id of the client associated with the withdrawal. Must be <= 40 characters. When using the client, if not included, will be randomly generated by the client.
» expiration body string false Date and time at which the withdrawal expires if it has not been completed. Expiration must be at least seven days in the future.
» asset body string false Asset(in USDC) being withdrawn.
» signature body string false The signature for the transfer, signed with the account's STARK private key.
» erc20Address body string false USDC address
» fee body string false Fees
» chainId body string true chainId
» lpAccountId body string false Attach documents to retrieve fast_withdraw_account_id

Successful Response Generation

{
  "id": "1234455",
  "type": "FAST_WITHDRAW"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string true none id
» type string true none type

POST Cross-Chain Withdrawals

POST /v1/cross-chain-withdraw

withdrawalToSign = {
  humanAmount: params.amount,
  expirationIsoTimestamp: params.expiration,
  clientId,
  positionId,
  fee
};

example

curl https://pro.apex.exchange/api/v1/cross-chain-withdraw -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'amount={amount}&clientId={clientId}&asset={asset}&expiration={expiration}&signature={signature}&ethAddress={ethAddress}&erc20Address={erc20Address}&fee={fee}&lpAccountId={lpAccountId}&chainId={chainId}'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()
feeRes = client.uncommon_withdraw_fee(amount='1003',chainId='56')
crossWithdrawRes = client.cross_chain_withdraw(amount='1003',expirationEpochSeconds= currentTime,asset='USDC',fee=feeRes['data']['fee'],chainId='56')

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» amount body string true Withdrawal amount
» clientId body string true Unique id of the client associated with the withdrawal. Must be <= 40 characters. When using the client, if not included, will be randomly generated by the client.
» expiration body string true Date and time at which the withdrawal expires if it has not been completed. Expiration must be at least seven days in the future.
» asset body string true Asset(in USDC) being withdrawn.
» signature body string true The signature for the transfer, signed with the account's STARK private key.
» erc20Address body string true USDC address
» chainId body string true Randomized clientId
» fee body string true Fees
» lpAccountId body string true Attach documents to retrieve fast_withdraw_account_id

Successful Response Generation

{
  "id": "1234455",
  "type": "CROSS_WITHDRAW"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string true none none
» type string true none Withdrawal type

GET Fast & Cross-Chain Withdrawal Fees

GET /v1/uncommon-withdraw-fee

curl https://pro.apex.exchange/api/v1/uncommon-withdraw-fee?amount={amount}&chainId={chainId} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' 
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

feeRes = client.uncommon_withdraw_fee(amount='1003',chainId='56')

Request Parameters

Parameter Position Type Required Comment
amount query string false USDC
chainId query string false chainId
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "fee": "1.1",
  "poolAvailableAmount": "10"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» fee string true none Fees calculated
» poolAvailableAmount string true none Available balance in pool

GET Withdrawal & Transfer Limits

GET /v1/transfer-limit

curl https://pro.apex.exchange/api/v1/transfer-limit -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

transfer_limitRes = client.transfer_limit(currencyId="USDC")

Request Parameters

Parameter Position Type Required Comment
currencyId query string true USDC
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "withdrawAvailableAmount": "100.1",
  "transferAvailableAmount": "100.1"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» withdrawAvailableAmount string true none Withdraw available amount
» transferAvailableAmount string true none Transfer available amount

GET Trade History

GET /v1/fills

curl https://pro.apex.exchange/api/v1/fills?limit=100&page=0&symbol=BTC-USDC&side=BUY -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' 
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

fillsRes = client.fills(limit=100,page=0,symbol="BTC-USDC",side="BUY")
Order Type  
 "UNKNOWN_ORDER_TYPE"    
 "LIMIT", //Limit price   
 "MARKET", //Market price   
 "STOP_LIMIT", //Stop limit order   
 "STOP_MARKET", //Stop market order   
 "TAKE_PROFIT_LIMIT",//Take profit limit orders   
 "TAKE_PROFIT_MARKET",//Take profit market orders  

Order Status   
 "PENDING", // Order submitted but not yet processesd     
 "OPEN", // Order pending, partially filled   
 "FILLED", // Order has been completely filled    
 "CANCELED", //Order is canceled and may have been partially filled.   
 "EXPIRED", // Order has expired and may have been partially filled.  
 "UNTRIGGERED", // Order conditions have not been triggered  

Order Cancelation Reason {   
 "UNKNOWN_ORDER_CANCEL_REASON"  // Unknown   
 "EXPIRED"  // Order has expired   
 "USER_CANCELED"  // User manually canceled order     
 "COULD_NOT_FILL"  // Unable to fill FOK/IOC/Post-only orders   
 "REDUCE_ONLY_CANCELED"  // Unable to fulfil reduce-only orders    
 "LIQUIDATE_CANCELED"  // Account or orders triggered liquidation resulting in automatic order cancelation  
 "INTERNAL_FAILED"  // Internal processing issues including order matching failure or L2 validation failure   
}

Request Parameters

Parameter Position Type Required Comment
symbol query string false Symbol
side query string false BUY or SELL
limit query string false default at 100
beginTimeInclusive query string false Start time
endTimeExclusive query string false End time
page query string false Page numbers start from 0
orderType query string false orderType
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "orders": [
    {
      "id": "1234",
      "clientId": "1234",
      "accountId": "12345",
      "symbol": "BTC-USD",
      "side": "SELL",
      "price": "18000",
      "limitFee": "100",
      "fee": "100",
      "triggerPrice": "1.2",
      "trailingPercent": "0.12",
      "size": "100",
          "type": "LIMIT",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "expiresAt": 1647502440973,
      "status": "PENDING",
      "timeInForce": "GOOD_TIL_CANCEL",
      "postOnly": false,
      "reduceOnly": false,
      "latestMatchFillPrice": "reason",
      "cumMatchFillSize": "0.1",
      "cumMatchFillValue": "1000",
      "cumMatchFillFee": "1",
      "cumSuccessFillSize": "0.1",
      "cumSuccessFillValue": "1000",
      "cumSuccessFillFee": "1"
    }
  ],
  "totalSize": 12
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» orders [object] true none none
»» id string false none Order id
»» orderId string false none Order id
»» clientOrderId string false none Client create the Randomized id
»» accountId string false none Account ID
»» symbol string false none Symbol
»» side string false none BUY or SELL
»» price string false none Order open price
»» limitFee string false none Order open max. fee
»» fee string false none Order open actual fee
»» triggerPrice string false none Conditional order trigger price
»» trailingPercent string false none Conditional order trailing-stop
»» size string false none Order open size
»» type string false none Order type
»» createdAt integer false none Order create at
»» updatedTime integer false none Order update time
»» expiresAt integer false none Order expires at
»» status string false none Order status
»» timeInForce string false none Open order timeInForce
»» postOnly boolean false none Open Post-only order
»» reduceOnly boolean false none Open Reduce-only order
»» latestMatchFillPrice string false none Latest match fill price
»» cumMatchFillSize string false none Cumulative match fill size
»» cumMatchFillValue string false none Cumulative match fill value
»» cumMatchFillFee string false none Cumulative match fill fee
»» cumSuccessFillSize string false none Cumulative success fill size
»» cumSuccessFillValue string false none Cumulative success fill value
»» cumSuccessFillFee string false none Cumulative success fill fee
» totalSize integer true none Total order size

GET Worst Price

GET /v1/get-worst-price

get market price from orderbook

Request Parameters

Parameter Position Type Required Comment
symbol query string true Symbol
size query string true Order open size
side query string true BUY or SELL order
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "worstPrice": "123.00",
  "bidOnePrice": "123.00",
  "askOnePrice": "123.00"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» worstPrice string true none Lowest price
» bidOnePrice string true none Bid price
» askOnePrice string true none Ask price

POST Creating Orders

POST /v1/create-order


Signature content:   
orderToSign:   
OrderWithClientId = {  
humanSize: params.size,   
humanPrice: params.price,   
limitFee: params.limitFee,   
symbol: params.symbol,   
side: params.side,   
expirationIsoTimestamp: params.expiration,
clientOrderId,   
positionId, };  

TimeInForce (  
GOOD_TIL_CANCEL // Effective until canceled, default.   
FILL_OR_KILL // Immediately and completely filled or canceled.   
IMMEDIATE_OR_CANCEL // Immediately executed or canceled.    
)  

example

curl https://pro.apex.exchange/api/v1/create-order -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'symbol={symbol}&side={side}&type={type}&size={size}&price={price}&limitFee={limitFee}&expiration={expiration}&timeInForce={timeInForce}&triggerPrice={triggerPrice}&trailingPercent={trailingPercent}&clientOrderId={clientOrderId}&signature={signature}&reduceOnly=false'
from apexpro.http_private_stark_key_sign import HttpPrivateStark
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

public_key = '0x1cf0000000000'
public_key_y_coordinate = '0x7615000000000'
private_key = '0x488a6000000000'

client = HttpPrivateStark(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN,
                     stark_public_key=public_key,
                     stark_private_key=private_key,
                     stark_public_key_y_coordinate=public_key_y_coordinate,
                     api_key_credentials={'key': key, 'secret': secret, 'passphrase': passphrase})

currentTime = time.time()

createOrderRes = client.create_order(symbol="BTC-USDC", side="BUY",
                                           type="LIMIT", size="0.01",
                                           price="20001", limitFee="0.001",
                                            accountId="330547708362228116",reduceOnly=False,
                                     expirationEpochSeconds= currentTime, timeInForce="GOOD_TIL_CANCEL")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» symbol body string true Symbol
» side body string true BUY or SELL
» type body string true "LIMIT", "MARKET","STOP_LIMIT", "STOP_MARKET", "TAKE_PROFIT_LIMIT", "TAKE_PROFIT_MARKET"
» size body string true Size
» price body string true Price
» limitFee body string true limitFee = price * size * takerFeeRate( from GET /v1/account)
» expiration body string true Order expiry time
» timeInForce body string false "GOOD_TIL_CANCEL", "FILL_OR_KILL", "IMMEDIATE_OR_CANCEL", "POST_ONLY"
» triggerPrice body string false Trigger price
» trailingPercent body string false Conditional order trailing-stop
» clientOrderId body string true Randomized client id
» signature body string true starkKey signature
» reduceOnly body string false Reduce-only

Successful Response Generation

{
  "id": "1234",
  "clientOrderId": "1234",
  "accountId": "12345",
  "symbol": "BTC-USD",
  "side": "SELL",
  "price": "18000",
  "limitFee": "100",
  "fee": "100",
  "triggerPrice": "1.2",
  "trailingPercent": "0.12",
  "size": "100",
  "type": "LIMIT",
  "createdAt": 1647502440973,
  "updatedTime": 1647502440973,
  "expiresAt": 1647502440973,
  "status": "PENDING",
  "timeInForce": "GOOD_TIL_CANCEL",
  "postOnly": false,
  "reduceOnly": false,
  "latestMatchFillPrice": "reason",
  "cumMatchFillSize": "0.1",
  "cumMatchFillValue": "1000",
  "cumMatchFillFee": "1",
  "cumSuccessFillSize": "0.1",
  "cumSuccessFillValue": "1000",
  "cumSuccessFillFee": "1"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string false none Order id
»» orderId string false none Order id
» clientOrderId string false none Client create the Randomized id
» accountId string false none Account ID
» symbol string false none Symbol
» side string false none BUY or SELL
» price string false none Order open price
» limitFee string false none Order open max. fee
» fee string false none Order open actual fee
» triggerPrice string false none Conditional order trigger price
» trailingPercent string false none Conditional order trailing-stop
» size string false none Order open size
» type string false none Order type
» createdAt integer false none Order create at
» updatedTime integer false none Order update time
» expiresAt integer false none Order expires at
» status string false none Order status
» timeInForce string false none Open order timeInForce
» postOnly boolean false none Open Post-only order
» reduceOnly boolean false none Open Reduce-only order
» latestMatchFillPrice string false none Latest match fill price
» cumMatchFillSize string false none Cumulative match fill size
» cumMatchFillValue string false none Cumulative match fill value
» cumMatchFillFee string false none Cumulative match fill fee
» cumSuccessFillSize string false none Cumulative success fill size
» cumSuccessFillValue string false none Cumulative success fill value
» cumSuccessFillFee string false none Cumulative success fill fee

POST Cancel Order

POST /v1/delete-order

curl https://pro.apex.exchange/api/v1/delete-order -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'id={id}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

deleteOrderRes = client.delete_order(id="123456")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» id body string false none

Successful Response Generation

{
  "data": "123456"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» data string true none Order ID

POST Cancel Order By ClientOrderId

POST /v1/delete-client-order-id

curl https://pro.apex.exchange/api/v1/delete-client-order-id` -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'id={id}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

deleteOrderRes = client.delete_order_by_client_order_id(id="123456")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» id body string false none

Successful Response Generation

{
  "data": "123456"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» data string true none Order ID

GET Open Orders

GET /v1/open-orders

Order type   
"UNKNOWN_ORDER_TYPE",   
 "LIMIT", //Limit price   
 "MARKET", //Market price   
 "STOP_LIMIT", //Stop limit order   
 "STOP_MARKET", //Stop market order   
 "TAKE_PROFIT_LIMIT",//Take profit limit orders   
 "TAKE_PROFIT_MARKET",//Take profit market orders  

Order Status   
 "PENDING", // Order submitted but not yet processesd   
 "OPEN", // Order pending, partially filled   
 "FILLED", // Order has been completely filled   
 "CANCELED", //Order is canceled and may have been partially filled.   
 "EXPIRED", // Order has expired and may have been partially filled.   
 "UNTRIGGERED", // Order conditions have not been triggered  

Order Cancelation Reason {   
 "UNKNOWN_ORDER_CANCEL_REASON"  // Unknown   
 "EXPIRED"  // Order has expired   
 "USER_CANCELED"  // User manually canceled order     
 "COULD_NOT_FILL"  // Unable to fill FOK/IOC/Post-only orders   
 "REDUCE_ONLY_CANCELED"  // Unable to fulfil reduce-only orders    
 "LIQUIDATE_CANCELED"  // Account or orders triggered liquidation resulting in automatic order cancelation  
 "INTERNAL_FAILED"  // Internal processing issues including order matching failure or L2 validation failure   
}

example

curl https://pro.apex.exchange/api/v1/open-orders -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

openOrdersRes = client.open_orders()

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none

Successful Response Generation

{
  "data": [
    {
      "id": "1234",
      "clientOrderId": "1234",
      "accountId": "12345",
      "symbol": "BTC-USD",
      "side": "SELL",
      "price": "18000",
      "limitFee": "100",
      "fee": "100",
      "triggerPrice": "1.2",
      "trailingPercent": "0.12",
      "size": "100",
      "type": "LIMIT",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "expiresAt": 1647502440973,
      "status": "PENDING",
      "timeInForce": "GOOD_TIL_CANCEL",
      "postOnly": false,
      "reduceOnly": false,
      "latestMatchFillPrice": "reason",
      "cumMatchFillSize": "0.1",
      "cumMatchFillValue": "1000",
      "cumMatchFillFee": "1",
      "cumSuccessFillSize": "0.1",
      "cumSuccessFillValue": "1000",
      "cumSuccessFillFee": "1"
    }
  ]
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» orders [object] true none none
»» id string false none Order id
»» orderId string false none Order id
»» clientOrderId string false none Client create the Randomized id
»» accountId string false none Account ID
»» symbol string false none Symbol
»» side string false none BUY or SELL
»» price string false none Order open price
»» limitFee string false none Order open max. fee
»» fee string false none Order open actual fee
»» triggerPrice string false none Conditional order trigger price
»» trailingPercent string false none Conditional order trailing-stop
»» size string false none Order open size
»» type string false none Order type
»» createdAt integer false none Order create at
»» updatedTime integer false none Order update time
»» expiresAt integer false none Order expires at
»» status string false none Order status
»» timeInForce string false none Open order timeInForce
»» postOnly boolean false none Open Post-only order
»» reduceOnly boolean false none Open Reduce-only order
»» latestMatchFillPrice string false none Latest match fill price
»» cumMatchFillSize string false none Cumulative match fill size
»» cumMatchFillValue string false none Cumulative match fill value
»» cumMatchFillFee string false none Cumulative match fill fee
»» cumSuccessFillSize string false none Cumulative success fill size
»» cumSuccessFillValue string false none Cumulative success fill value
»» cumSuccessFillFee string false none Cumulative success fill fee

POST Cancel all Open Orders

POST /v1/delete-open-orders

Body Request Parameters

symbol: BTC-USDC,ETH-USDC

curl https://pro.apex.exchange/api/v1/delete-open-orders -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***' -X POST -d 'symbol={BTC-USDC,ETH-USDC}'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

deleteOrdersRes = client.delete_open_orders(symbol="BTC-USDC,ETH-USDC")

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» symbol body string false "BTC-USDC,ETH-USDC", Cancel all orders if none

Successful Response Generation

{

}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

GET All Order History

GET /v1/history-orders

Order type 
 "UNKNOWN_ORDER_TYPE",   
 "LIMIT", //Limit price   
 "MARKET", //Market price   
 "STOP_LIMIT", //Stop limit order   
 "STOP_MARKET", //Stop market order   
 "TAKE_PROFIT_LIMIT",//Take profit limit orders   
 "TAKE_PROFIT_MARKET",//Take profit market orders  

Order Status   
 "PENDING", // Order submitted but not yet processesd   
 "OPEN", // Order pending, partially filled   
 "FILLED", // Order has been completely filled    
 "CANCELED", //Order is canceled and may have been partially filled.    
 "EXPIRED", // Order has expired and may have been partially filled.   
 "UNTRIGGERED", // Order conditions have not been triggered  

Order Cancelation Reason {   
 "UNKNOWN_ORDER_CANCEL_REASON"  // Unknown   
 "EXPIRED"  // Order has expired   
 "USER_CANCELED"  // User manually canceled order     
 "COULD_NOT_FILL"  // Unable to fill FOK/IOC/Post-only orders   
 "REDUCE_ONLY_CANCELED"  // Unable to fulfil reduce-only orders    
 "LIQUIDATE_CANCELED"  // Account or orders triggered liquidation resulting in automatic order cancelation  
 "INTERNAL_FAILED"  // Internal processing issues including order matching failure or L2 validation failure   
}

example

curl https://pro.apex.exchange/api/v1/history-orders -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

historyOrdersRes = client.history_orders()

Request Parameters

Parameter Position Type Required Comment
symbol query string false none
status query string false none
side query string false BUY or SELL
type query string false "LIMIT", "MARKET","STOP_LIMIT", "STOP_MARKET", "TAKE_PROFIT_LIMIT","TAKE_PROFIT_MARKET"
limit query string false default 100
beginTimeInclusive query string false Start time
endTimeExclusive query string false End time
page query string false Page numbers start from 0
orderType query string false "ACTIVE","CONDITION","HISTORY"
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "orders": [
    {
      "id": "1234",
      "clientOrderId": "1234",
      "accountId": "12345",
      "symbol": "BTC-USD",
      "side": "SELL",
      "price": "18000",
      "limitFee": "100",
      "fee": "100",
      "triggerPrice": "1.2",
      "trailingPercent": "0.12",
      "size": "100",
      "type": "LIMIT",
      "createdAt": 1647502440973,
      "updatedTime": 1647502440973,
      "expiresAt": 1647502440973,
      "status": "PENDING",
      "timeInForce": "GOOD_TIL_CANCEL",
      "postOnly": false,
      "reduceOnly": false,
      "latestMatchFillPrice": "reason",
      "cumMatchFillSize": "0.1",
      "cumMatchFillValue": "1000",
      "cumMatchFillFee": "1",
      "cumSuccessFillSize": "0.1",
      "cumSuccessFillValue": "1000",
      "cumSuccessFillFee": "1"
    }
  ],
  "totalSize": 12
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» orders [object] true none none
»» id string false none Order id
»» orderId string false none Order id
»» clientOrderId string false none Client create the Randomized id
»» accountId string false none Account ID
»» symbol string false none Symbol
»» side string false none BUY or SELL
»» price string false none Order open price
»» limitFee string false none Order open max. fee
»» fee string false none Order open actual fee
»» triggerPrice string false none Conditional order trigger price
»» trailingPercent string false none Conditional order trailing-stop
»» size string false none Order open size
»» type string false none Order type
»» createdAt integer false none Order create at
»» updatedTime integer false none Order update time
»» expiresAt integer false none Order expires at
»» status string false none Order status
»» timeInForce string false none Open order timeInForce
»» postOnly boolean false none Open Post-only order
»» reduceOnly boolean false none Open Reduce-only order
»» latestMatchFillPrice string false none Latest match fill price
»» cumMatchFillSize string false none Cumulative match fill size
»» cumMatchFillValue string false none Cumulative match fill value
»» cumMatchFillFee string false none Cumulative match fill fee
»» cumSuccessFillSize string false none Cumulative success fill size
»» cumSuccessFillValue string false none Cumulative success fill value
»» cumSuccessFillFee string false none Cumulative success fill fee
» totalSize integer true none total order size

GET Order ID

GET /v1/get-order

curl https://pro.apex.exchange/api/v1/get-order?id={id} -h 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

getOrderRes = client.get_order(id="123456")

Request Parameters

Parameter Position Type Required Comment
id query string true none
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "id": "123456",
  "clientOrderId": "1234",
  "accountId": "afoo",
  "symbol": "BTC-USD",
  "side": "SELL",
  "price": "18000",
  "triggerPrice": "1.2",
  "trailingPercent": "0.12",
  "size": "100",
  "type": "LIMIT",
  "createdAt": 1647502440973,
  "unfillableAt": 1647502440973,
  "expiresAt": 1647502440973,
  "status": "PENDING",
  "timeInForce": "GOOD_TIL_CANCEL",
  "postOnly": false,
  "cancelReason": "reason"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string false none Order id
» orderId string false none Order id
» clientOrderId string false none Client create the Randomized id
» accountId string false none Account ID
» symbol string false none Symbol
» side string false none BUY or SELL
» price string false none Order open price
» limitFee string false none Order open max. fee
» fee string false none Order open actual fee
» triggerPrice string false none Conditional order trigger price
» trailingPercent string false none Conditional order trailing-stop
» size string false none Order open size
» type string false none Order type
» createdAt integer false none Order create at
» updatedTime integer false none Order update time
» expiresAt integer false none Order expires at
» status string false none Order status
» timeInForce string false none Open order timeInForce
» postOnly boolean false none Open Post-only order
» reduceOnly boolean false none Open Reduce-only order
» latestMatchFillPrice string false none Latest match fill price
» cumMatchFillSize string false none Cumulative match fill size
» cumMatchFillValue string false none Cumulative match fill value
» cumMatchFillFee string false none Cumulative match fill fee
» cumSuccessFillSize string false none Cumulative success fill size
» cumSuccessFillValue string false none Cumulative success fill value
» cumSuccessFillFee string false none Cumulative success fill fee

GET Order by clientOrderId

GET /v1/order-by-client-order-id"

curl https://pro.apex.exchange/api/v1/order-by-client-order-id?id={id} -h 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

getOrderRes = client.get_order_by_client_order_id(id="123456")

Request Parameters

Parameter Position Type Required Comment
id query string true none
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "id": "123456",
  "clientOrderId": "1234",
  "accountId": "afoo",
  "symbol": "BTC-USD",
  "side": "SELL",
  "price": "18000",
  "triggerPrice": "1.2",
  "trailingPercent": "0.12",
  "size": "100",
  "type": "LIMIT",
  "createdAt": 1647502440973,
  "unfillableAt": 1647502440973,
  "expiresAt": 1647502440973,
  "status": "PENDING",
  "timeInForce": "GOOD_TIL_CANCEL",
  "postOnly": false,
  "cancelReason": "reason"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» id string false none Order id
» orderId string false none Order id
» clientOrderId string false none Client create the Randomized id
» accountId string false none Account ID
» symbol string false none Symbol
» side string false none BUY or SELL
» price string false none Order open price
» limitFee string false none Order open max. fee
» fee string false none Order open actual fee
» triggerPrice string false none Conditional order trigger price
» trailingPercent string false none Conditional order trailing-stop
» size string false none Order open size
» type string false none Order type
» createdAt integer false none Order create at
» updatedTime integer false none Order update time
» expiresAt integer false none Order expires at
» status string false none Order status
» timeInForce string false none Open order timeInForce
» postOnly boolean false none Open Post-only order
» reduceOnly boolean false none Open Reduce-only order
» latestMatchFillPrice string false none Latest match fill price
» cumMatchFillSize string false none Cumulative match fill size
» cumMatchFillValue string false none Cumulative match fill value
» cumMatchFillFee string false none Cumulative match fill fee
» cumSuccessFillSize string false none Cumulative success fill size
» cumSuccessFillValue string false none Cumulative success fill value
» cumSuccessFillFee string false none Cumulative success fill fee

GET /v1/verify-email

Parameter Position Type Required Comment
userId query string false User ID
token query string false Authentication token

Successful Response Generation

Status Code Definition Comment Data Model
200 OK Success Inline

POST Link Device

POST /v1/bind-device

Body Request Parameters

deviceToken: string
deviceType: 1 or 2

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» deviceToken body string true Device token
» deviceType body string true 1 (ios_firebase), 2 (android_firebase)

Successful Response Generation

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

GET Funding Rate

GET /v1/funding

curl https://pro.apex.exchange/api/v1/funding?limit={limit}&page={page}&symbol={symbol}&side={side} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

fundingRes = client.funding(limit=100,page=0,symbol="BTC-USDC",side="BUY")

Request Parameters

Parameter Position Type Required Comment
symbol query string false none
limit query string false Default at 100
page query string false Page numbers start from 0
beginTimeInclusive query string false Start time
endTimeExclusive query string false End time
side query string false Side
status query string false Order status
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "fundingValues": [
    {
      "id": "1234",
      "symbol": "BTC-USD",
      "fundingValue": "10000",
      "rate": "0.0000125000",
      "positionSize": "500",
      "price": "90",
      "side": "LONG",
      "status": "SUCCESS",
      "fundingTime": 1647502440973,
      "transactionId": "1234556"
    }
  ],
  "totalSize": 11
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» fundingValues [object] true none none
»» id string false none id
»» symbol string false none Symbol
»» fundingValue string false none Funding fee value
»» rate string false none Funding rate
»» positionSize string false none Open position size
»» price string false none Symbol price
»» side string false none Position side
»» status string false none Position funding status
»» fundingTime integer false none Funding fee time
»» transactionId string false none Successful wallet transaction ID
» totalSize integer true none Total size

GET User Historial Profit and Loss

GET /v1/historical-pnl

curl https://pro.apex.exchange/api/v1/historical-pnl?limit={limit}&page={page}&beginTimeInclusive={beginTimeInclusive}&endTimeExclusive={endTimeExclusive}&type={type}&symbol={symbol} -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

historicalPnlRes = client.historical_pnl(limit=100,page=0,beginTimeInclusive=1651406864000,endTimeExclusive=1657105971171,symbol="BTC-USDC")

Request Parameters

Parameter Position Type Required Comment
beginTimeInclusive query string false StartTime
endTimeExclusive query string false EndTime
type query string false Position type
symbol query string false Symbol
page query string false Page numbers start from 0
limit query string false Default at 100
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "historicalPnl": [
    { "symbol": "BTC-USDC",
      "size": "1.0000",
      "totalPnl": "1.0000",
      "price": "1.0000",
      "createdAt": 1647502440973,
      "type": "CLOSE_POSITION",
      "isLiquidate": false,
      "isDeleverage": false
    }
  ],
  "totalSize": 12
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Position Type Required Comment
» historicalPnl [object] true none none
»» size string false none Size
»» totalPnl string false none Closing profit and loss
»» price string false none Price
»» exitPrice string false none Closing price
»» createdAt integer false none Time
»» type string false none postion type
»» isLiquidate boolean false none Liquidate
»» isDeleverage boolean false none ADL
» totalSize integer true none none

GET Yesterday's Profit & Loss

GET /v1/yesterday-pnl

curl https://pro.apex.exchange/api/v1/yesterday-pnl -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

yesterdayPnlRes = client.yesterday_pnl()

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "data": "11.11"
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» data string true none Profit and loss value

GET Historical Asset Value

GET /v1/history-value

curl https://pro.apex.exchange/api/v1/history-value -H 'APEX-SIGNATURE: ***' -H 'APEX-TIMESTAMP: ***' -H 'APEX-API-KEY: ***' -H 'APEX-PASSPHRASE: ***'
from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

historyValueRes = client.history_value()

Request Parameters

Parameter Position Type Required Comment
endTime query int64 false Start time
startTime query int64 false End time
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase

Successful Response Generation

{
  "historyValues": [
    {
      "accountTotalValue": "123.11",
      "dateTime": 1651406864000
    }
  ]
}

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

Status Code 200

Parameter Type Required Limit Comment
» historyValues [object] true none none
»» accountTotalValue string false none Assets
»» dateTime integer false none Assets date and time snapshot

POST Sets the initial margin rate of a contract

POST /v1/set-initial-margin-rate

curl https://pro.apex.exchange/api/v1/set-initial-margin-rate -H "Content-Type: application/x-www-form-urlencoded" -H "APEX-SIGNATURE: ***" -H "APEX-TIMESTAMP: ***" -H "APEX-API-KEY: ***" -H "APEX-PASSPHRASE: ***" -X POST -d "symbol=BTC-USDC&initialMarginRate=0.02"

from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_MAIN, NETWORKID_MAIN

key = 'f16ddxxxxxxxxxxx'
secret = 'Kvckxxxxxxxxxxx'
passphrase = 'Yjjd1xxxxxxxxxx'

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, api_key_credentials={'key': key,'secret': secret, 'passphrase': passphrase})

setInitialMarginRateRes = client.set_initial_margin_rate(symbol="BTC-USDC",initialMarginRate="0.1")
print(setInitialMarginRateRes)

Body

symbol: string
initialMarginRate: string

Request Parameters

Parameter Position Type Required Comment
APEX-SIGNATURE header string true Request signature
APEX-TIMESTAMP header string true Request timestamp
APEX-API-KEY header string true apiKeyCredentials.key
APEX-PASSPHRASE header string true apiKeyCredentials.passphrase
body body object false none
» symbol body string true symbol
» initialMarginRate body string true initialMarginRate(the reciprocal of the opening leverage)

Successful Response Generation

Response Status Code

Status Code Definition Comment Data Model
200 OK Success Inline

Response Parameters

StarkKey Signature

Several endpoints require a starkKey signature authentication, please check the list below.

Create Order

Refer to required signature content.

{
    "amount_collateral": "4000000",
    "amount_fee": "4000",
    "amount_synthetic": "1000000",
    "asset_id_collateral": "0xa21edc9d9997b1b1956f542fe95922518a9e28ace11b7b2972a1974bf5971f",
    "asset_id_synthetic": "0x0",
    "expiration_timestamp": "1100000",
    "is_buying_synthetic": false,
    "nonce": "1001",
    "order_type": "LIMIT_ORDER_WITH_FEES",
    "position_id": "10000",
    "public_key": "0xf8c6635f9cfe85f46759dc2eebe71a45b765687e35dbe5e74e8bde347813ef",
    "signature": {
        "r": "0x07a15838aad9b20368dc4ba27613fd35ceec3b34be7a2cb913bca0fb06e98107",
        "s": "0x05007f40fddd9babae0c7362d3b4e9c152ed3fced7fe78435b302d825489298f"
    }
}

Transaction Signing & Validation

In ApeX Pro's testing environment, USDC is at 6 decimal places and BTC-USDC Perpetual Contract at 10 decimal places. For example, at the amount of 40,000 USDC and an open position of 0.0001 BTC with funding fee rate at 0.1%:

Hash Value Calculation Reference

https://github.com/starkware-libs/stark-perpetual/blob/d1edb2203440b54e71458b10bf0bb646d8597caf/src/services/perpetual/public/perpetual_messages.py#L163

Hash Value Calculation

Please refer to https://github.com/starkware-libs/stark-perpetual/blob/d1edb2203440b54e71458b10bf0bb646d8597caf/src/starkware/crypto/starkware/crypto/signature/signature.py#L124

Transaction Signing & Validation Result:

Withdrawal

Refer to required signature content for withdrawal to individual Ethereum address.

{
    "amount": "1000000",
    "expiration_timestamp": "660000",
    "nonce": "1650006339",
    "position_id": "10000",
    "public_key": "0xf8c6635f9cfe85f46759dc2eebe71a45b765687e35dbe5e74e8bde347813ef",
    "signature": {
        "r": "0x056a727b30d09f393acd968917bca78d92fb63a827db25747940916aa4074938",
        "s": "0x0775f575a71ff8f2c13dd522e605bd71652a709daa26db5a0f8218cc589fe8f9"
    },
    "type": "WITHDRAWAL"
}

Transaction Signing & Validation

USDC has 6 decimal places; timeout is calculated in hours; unix timestamp/3600, nonce UInt32 must be the only entry for generated client_Id

Hash Value Calculation Reference

https://docs.starkware.co/starkex-v4/starkex-deep-dive/message-encodings/in-perpetual#withdrawal

Reference code:
https://github.com/starkware-libs/stark-perpetual/blob/d1edb2203440b54e71458b10bf0bb646d8597caf/src/services/perpetual/public/perpetual_messages.py#L112

Hash Value Calculation

Transaction Signing & Validation Result

Withdrawal to Address

Refer to required signature content for withdrawal endpoint WITHDRAWAL_TO_ADDRESS.

{
    "amount": "1000000",
    "eth_address": "0x724f337bf0fa934db9aa3ec6dea49b03c54ad3cc",
    "expiration_timestamp": "660000",
    "nonce": "1651500987",
    "position_id": "10000",
    "public_key": "0xf8c6635f9cfe85f46759dc2eebe71a45b765687e35dbe5e74e8bde347813ef",
    "signature": {
        "r": "0x07edcc193f142ff8c78d700774fbccde8214c21f8fc1bd190390d367ce365696",
        "s": "0x06e5b54f17f56e65e21b00e83fd2b6f3da072ed6b6df3ca50747d8a0974d5033"
    },
    "type": "WITHDRAWAL_TO_ADDRESS"
}

Use a new WITHDRAWAL_TO_ADDRESS and transfer your assets from L1 to a designated Ethereum address. When requesting for a withdrawal endpoint on L1, you will need to enter eth_address in the required starkKey portion. You will not need to register a corresponding starkKey to manage the Ethereum address.

Transaction Signing & Validation

USDC has 6 decimal places; timeout is calculated in hours; unix timestamp/3600, nonce UInt32 must be the only entry for generated client_Id

Hash Value Calculation

def get_withdrawal_to_address_msg(
    asset_id_collateral: int,
    position_id: int,
    eth_address: str,
    nonce: int,
    expiration_timestamp: int,
    amount: int,
    hash_function: Callable[[VarArg(int)], int] = pedersen_hash,
) -> int:
    assert 0 <= asset_id_collateral < 2 ** 250
    assert 0 <= nonce < 2 ** 32
    assert 0 <= position_id < 2 ** 64
    assert 0 <= expiration_timestamp < 2 ** 32
    assert 0 <= amount < 2 ** 64
    assert 0 <= int(eth_address, 16) < 2 ** 160
    return get_withdrawal_to_address_msg_without_bounds(
        asset_id_collateral,
        position_id,
        eth_address,
        nonce,
        expiration_timestamp,
        amount,
        hash_function=hash_function,
    )
def get_withdrawal_to_address_msg_without_bounds(
    asset_id_collateral: int,
    position_id: int,
    eth_address: str,
    nonce: int,
    expiration_timestamp: int,
    amount: int,
    hash_function: Callable[[VarArg(int)], int] = pedersen_hash,
) -> int:
    eth_address_int = int(eth_address, 16)
    packed_message = WITHDRAWAL_TO_ADDRESS
    packed_message = packed_message * 2 ** 64 + position_id
    packed_message = packed_message * 2 ** 32 + nonce
    packed_message = packed_message * 2 ** 64 + amount
    packed_message = packed_message * 2 ** 32 + expiration_timestamp
    packed_message = packed_message * 2 ** 49  # Padding.
    return hash_function(hash_function(asset_id_collateral, eth_address_int), packed_message)

Transaction Signing & Validation Result

Cross-Chain Withdrawal

Refer to required signature content for this transfer endpoint, utilized for cross-chain deposits.

{
    "amount": "1000000",
    "asset_id": "0xa21edc9d9997b1b1956f542fe95922518a9e28ace11b7b2972a1974bf5971f",
    "expiration_timestamp": "660000",
    "nonce": "1652361581",
    "receiver_position_id": "30000",
    "receiver_public_key": "0x2f116d013fb6ecae90765a876a5bfcf66cd6a6be1f85c9841629cd0bd080ed3",
    "sender_position_id": "10000",
    "sender_public_key": "0xf8c6635f9cfe85f46759dc2eebe71a45b765687e35dbe5e74e8bde347813ef",
    "signature": {
        "r": "0xd4c14bb7bfd66785352c8b57c3864722e2137f51299e0a21dff495759c3902",
        "s": "0x01a7dcd09583e3261906ad1f039848e9ace4d3cc988e56e96bb8652e9c483517"
    },
    "type": "TRANSFER"
}

Transaction Signing & Validation

USDC has 6 decimal places; timeout is calculated in hours; unix timestamp/3600, nonce UInt32 must be the only entry for generated client_Id

Hash Value Reference (TRANSFER = 4)
https://github.com/starkware-libs/stark-perpetual/blob/d1edb2203440b54e71458b10bf0bb646d8597caf/src/services/perpetual/public/perpetual_messages.py#L69

Hash Value Calculation

Transaction Signing & Validation Result

Conditional Transfer

Refer to required signature content for this CONDITIONAL_TRANSFER endpoint, utilized for Fast Withdrawals.

{
    "amount": "1000000",
    "asset_id": "0xa21edc9d9997b1b1956f542fe95922518a9e28ace11b7b2972a1974bf5971f",
    "expiration_timestamp": "660000",
    "fact": "d7262d40a59d8bd081382e506f94230c73e3b81dc464bb02e7314b1afcca46d1",
    "fact_registry_address": "0x5070F5d37419AEAd10Df2252421e457336561269",
    "nonce": "1652361582",
    "receiver_position_id": "20000",
    "receiver_public_key": "0x2deb04eb807be0ec943e08d8f666521edb3f12833922fbbc7f93e1434ae810e",
    "sender_position_id": "10000",
    "sender_public_key": "0xf8c6635f9cfe85f46759dc2eebe71a45b765687e35dbe5e74e8bde347813ef",
    "signature": {
        "r": "0x07dbf7b64406bd4de0439dfd79a742d1703ce44b99dfbe5a99d792c11447a952",
        "s": "0x01c436232f1e938cdcfe661f580d6957cdbdb72a14e66021349dd6c2baa6ac36"
    },
    "type": "CONDITIONAL_TRANSFER"
}

Transaction Signing & Validation

USDC has 6 decimal places; timeout is calculated in hours; unix timestamp/3,600, nonce UInt32 must be the only entry for generated client_Id

Hash Value Reference (CondTransferType = 5)
https://github.com/starkware-libs/stark-perpetual/blob/d1edb2203440b54e71458b10bf0bb646d8597caf/src/services/perpetual/public/perpetual_messages.py#L24

Hash Value Calculation

Transaction Signing & Validation Result

Websocket

Websocket Endpoint:

Timestamp = Current Unix Timestamp

Testnet:

Public Websocket API
wss://quote-testnet.pro.apex.exchange/realtime_public?v=2&timestamp=1661415017232

Private Websocket API
wss://quote-testnet.pro.apex.exchange/realtime_private?v=2&timestamp=1661415017233

Mainnet:

Public Websocket API
wss://quote.pro.apex.exchange/realtime_public?v=2&timestamp=1661415017232

Private Websocket API
wss://quote.pro.apex.exchange/realtime_private?v=2&timestamp=1661415017233

Public Websocket

Due to network complexity, your may get disconnected at any time. Please follow the instructions below to ensure that you receive WebSocket messages on time: - Keep connection alive by sending heartbeat packet
- Reconnect as soon as possible if disconnected

Heartbeat Packet

To avoid networks or program issues, we recommend that you send the ping heartbeat packet every 15 seconds to maintain the WebSocket connection.

How to Send

ws.send('{"op":"ping","args":["1661415022821"]}');

Response Example

'{"op":"pong","args":["1661415030233"]}'

Server Check With Ping Pong Test:
- Check the connection ever 15 seconds and look at the client timestamp
- If the difference between the client timestamp and the current timestamp exceeds 150s, the connection will be closed

How to Subscribe to Topics

Understanding Websocket Filters

After establishing the connection, one can subscribe to a new topic by sending a JSON request. The specific formats are as follows:

ws.send('{"op": "subscribe", "args": ["topic.filter"]}');

The topic indicates the data you would like to receive whilst the filter parses for the specific data you desire, for example, the symbol. The topic is mandatory but the filter is optional.
To subscribe to more than one topic, simply list multiple topics out like this:

ws.send('{"op": "subscribe", "args": ["topic.filter", "topic.filter"]}');

Unsubscribing From Websocket Topics

You can dynamically subscribe and unsubscribe from topics (with or without filters) without websocket disconnection as follows:

ws.send('{"op": "unsubscribe", "args": ["topic.filter", "topic.filter"]}');

Intervals

Some topics are pushed out at specific intervals. If the args contains a millisecond parameter, such as 100ms, this topic is pushed at intervals. Otherwise, topis will be pushed constantly.

Understanding Subscription Response

Each subscription will have a response. You can determine whether the subscription is successful based on the response.

{
        "success":true, 
        "ret_msg":"",
        "conn_id":"647c3de8-6f66-44ab-a323-72067589372e",
        "request":{
            "op":"subscribe",
            "args":[
            "instrumentInfo.H.BTCUSDC"
        ]
        }
}

Depth

Fetches the orderbook with a depth of 25 or 200 orders per side.

After the subscription response, the first response will be the snapshot response. This shows the entire order book. The data is sorted by price, starting with the lowest buys and ending with the highest sells.

Following this, all responses are in the delta format, which represents updates to the order book relative to the last response.

Request Parameters

Parameter Type Limit Comment
» op string true Subscribe
» args string true Order book
» limit string true 25 or 200
» frequency string true H means High frequency, M means middle frequency
» symbol string true Symbol

How to Subscribe

ws.send('{"op":"subscribe","args":["orderBook200.H.BTCUSDC"]}');

response

{
    "topic":"orderBook200.H.BTCUSDC",
    "type":"delta",
    "data":{
        "s":"BTCUSDC",
        "b":[
            [
                "18990.5",
                "0"
            ],
            [
                "18979.5",
                "0"
            ]
        ],
        "a":[
            [
                "19010.5",
                "0"
            ],
            [
                "19037.5",
                "0"
            ]
        ],
        "u":249003
    },
    "cs":44132980,
    "ts":1661416027956272
}

Response data

Parameter Type Comment
» topic string Same as request args
» type string Snapshot or delta
» s string Symbol
» u int Update ID: According to whether the Update ID is continuous, the client will need to determine if there is a packet loss in the process of receiving data. Snapshot resets the Update ID and it will start counting again from 1.
» b array Buy[price,size], size set as 0 will delete this item
» a array Sell[price,size], size set as 0 will delete this item

Trade

Get Trades for symbol.

TickDirection {
"PlusTick"
"ZeroPlusTick"
"MinusTick"
"ZeroMinusTick"
}

Request Parameters

Parameter Type Limit Comment
» op string true Subscribe
» args string true Recently trade
» frequency string true H means High frequency, M means middle frequency
» symbol string true Symbol

How to Subscribe

ws.send('{"op":"subscribe","args":["recentlyTrade.H.BTCUSDC"]}');

response

{
    "topic":"recentlyTrade.H.BTCUSDC",
    "type":"snapshot",
    "data":[
        {
            "T":1647502440973,
            "s":"BTCPERP",
            "S":"Buy",
            "v":"1.000",
            "p":"43513.00",
            "L":"PlusTick",
            "i":"a3afbef7-d8de-5b87-a32f-d06f041a249d"
        }
    ],
    "cs":44132980,
    "ts":1661416027956272
}

Response data

Parameter Type Comment
» topic string Same as request args
» type string Snapshot
» s string Symbol
» T int Timestamp
» S string Buy or Sell
» v string Volume
» p string Price
» L string Tick direction
» i string Order ID

Ticker

Get latest information for symbol.

This topic only utilizes the update field. Both the delete and insert fields are null. If a key is not found in the update field, its value has not changed.

Request Parameters

Parameter Type Limit Comment
» op string true Subscribe
» args string true Instrument info
» frequency string true H means High frequency, M means middle frequency
» symbol string true Symbol

How to Subscribe

ws.send('{"op":"subscribe","args":["instrumentInfo.H.BTCUSDC"]}')

response

{
    "topic":"instrumentInfo.H.BTCUSDC",
        "type":"snapshot",
        "data":{
        "symbol":"BTCUSDC",
            "lastPrice":"21572.5",
            "price24hPcnt":"-0.0194318181818182",
            "highPrice24h":"25306.5",
            "lowPrice24h":"17001.5",
            "turnover24h":"1334891.4545",
            "volume24h":"64.896",
            "nextFundingTime":"2022-08-26T08:00:00Z",
            "oraclePrice":"21412.060000000002752512",
            "indexPrice":"21409.82",
            "openInterest":"49.598",
            "tradeCount":"0",
            "fundingRate":"0.0000125",
            "predictedFundingRate":"0.0000125"
    },
    "cs":44939063,
        "ts":1661500091955487
}

Response data

Parameter Type Comment
» topic string Same as request args
» type string Snapshot or delta
»» symbol string Symbol
»» price24hPcnt string 24H change (%)
»» lastPrice string Last price
»» highPrice24h string 24H highest price
»» lowPrice24h string 24H lowest price
»» oraclePrice string Oracle price
»» indexPrice string Index price
»» openInterest string Open interest
»» turnover24h string 24H turnover
»» volume24h string 24H trading volume
»» fundingRate string Funding rate
»» predictedFundingRate string Predicted funding rate
»» nextFundingTime string Next funding rate
»» tradeCount string 24H trade count

Candlestick Chart

Currently supported intervals:

If confirm is true, this will indicate the last ticker price within the specified interval.

request

Parameter Type Limit Comment
» op string true Subscribe
» args string true Candle
» interval string true Interval
» symbol string true Symbol

How to Subscribe

ws.send('{"op":"subscribe","args":["candle.1.BTCUSDC"]}')

response data

{
    "topic":"candle.1.BTCUSDC",
        "data":[
        {
            "start":1647511440000,
            "end":1647511499999,
            "interval":"1",
            "open":"44111",
            "close":"44111",
            "high":"44111",
            "low":"44111",
            "volume":"0",
            "turnover":"0",
            "confirm":true,
            "time":1647511500752
        }
    ],
        "ts":1647511500752,
        "type":"snapshot"
}

Response data

Parameter Type Comment
» topic string Same as request args
» type string Snapshot or delta
»» start integer Start time
»» symbol string Symbol
»» interval string Candlestick chart time indicators: Numbers represent minutes, D for Days, M for Month and W for Week — 1 5 15 30 60 120 240 360 720 "D" "M" "W"
»» low string Low price
»» high string High price
»» open string Open price
»» close string Close price
»» volume string Trading volume
»» turnover string Turnover
»» confirm string If it is the last tick of this candle
»» time string Current time

All Tickers

Get latest information for all symbols.

This topic only utilizes the update field. Both the delete and insert fields are null. If a key is not found in the update field, its value has not changed.

Request

Parameter Type Limit Comment
» op string true Subscribe
» args string true Instrument info
» frequency string true H means High frequency, M means middle frequency
» symbol string true Symbol

How to Subscribe

ws.send('{"op":"subscribe","args":["instrumentInfo.all"]}')

response

{
    "topic":"instrumentInfo.all",
        "data":[
        {
            "s":"LINKUSDC",
            "p":"6.966",
            "pr":"-0.0510829587249694",
            "h":"7.401",
            "l":"6.931",
            "op":"6.966",
            "xp":"6.965",
            "to":"37279.7137",
            "v":"5128.7",
            "fr":"0.0000125",
            "o":"5647.1",
            "tc":"0"
        },
        {
            "s":"BTCUSDC",
            "p":"21572.5",
            "pr":"-0.0194318181818182",
            "h":"25306.5",
            "l":"17001.5",
            "op":"21412.060000000002752512",
            "xp":"21409.83",
            "to":"1334891.4545",
            "v":"64.858",
            "fr":"0.0000125",
            "o":"49.598",
            "tc":"0"
        },
        {
            "s":"ETHUSDC",
            "p":"1680.45",
            "pr":"-0.0150631538844767",
            "h":"1805.65",
            "l":"1680.45",
            "op":"1654.64",
            "xp":"1654.1",
            "to":"664502.346",
            "v":"389.16",
            "fr":"0.0000125",
            "o":"375.87",
            "tc":"0"
        },
        {
            "s":"DOGEUSDC",
            "p":"0.0621",
            "pr":"-0.1013024602026049",
            "h":"0.1481",
            "l":"0.0501",
            "op":"0.06773",
            "xp":"0.0677",
            "to":"5007.69",
            "v":"70977",
            "fr":"0.0000125",
            "o":"43216",
            "tc":"0"
        }
    ],
        "type":"snapshot",
        "ts":1661500091389816
}

Response data

Parameter Type Comment
» topic string Same as request args
»» s string Symbol
»» pr string 24H change (%)
»» p string Last price
»» h string 24H highest price
»» l string 24H lowest price
»» op string Oracle price
»» xp string Index price
»» o string Open interest
»» to string 24H turnover
»» v string 24H trading volume
»» fr string Funding rate
»» tc string 24H trade count

Private Websocket

Send Authority Request


const apiKeyCredentials = {"key":"f6c1e736-fa6b-01df-2822-b9359b3918ae","secret":"sAVchdqy_n9zY7TOIDsqkyg0we3uF0_gGbvyIoob","passphrase":"Ri08mFrOt2Uaiym"}
const timestamp = 1647502440973;
const request_path = '/ws/accounts';
const http_method = 'GET';
const messageString: string = (
    timestamp +
    http_method +
    request_path);

const key = Buffer.from(this.apiKeyCredentials.secret).toString('base64');
const hash = cryptojs.HmacSHA256(messageString, key);
const signature = hash.toString(cryptojs.enc.Base64);

//auth sign
const req = {
    'type': 'login',
    'topics': ['ws_notify_v1','ws_accounts_v1'], 
    'httpMethod':http_method,
    'requestPath':request_path,
    'apiKey': apiKeyCredentials['key'],
    'passphrase': apiKeyCredentials['passphrase'],
    'timestamp': timestamp,
    'signature': signature,
}

sendStr = {
                "op": "login",
                "args": [JSON.stringify(req)]
            }
websocket.send(JSON.stringify(sendStr));


//add subscribe
websocket.send(JSON.stringify({"op":"subscribe","args":["ws_accounts_v1", "ws_notify_v1"]}));

//cancel subscribe
websocket.send({"op":"unsubscribe","args":["ws_accounts_v1","ws_notify_v1"]});

Response Errors:

Subscription Success Push Data

    {
      "topic":"ws_accounts_v1",
      "type":"snapshot",
      "timestamp":1652185029033,
      "contents":{
        "transfers":[
          {
            "createdAt":1652185839042, 
            "creditAsset":"USDC", 
            "id":"2048047104", 
            "type":"DEPOSIT", 
            "creditAmount":"100.000000", 
            "confirmedAt":1652185839042, 
            "transactionHash":"0x7369d3f8d860b10a443c6a6d55c0ea4f2ab106f264a8ad28b822a33cba6aead8", 
            "status":"SUCCESS_L2_APPROVED" 
          }
        ],
        "orders":[
          {
            "symbol":"ETH-USDC",
            "cumSuccessFillFee":"0.625000", 
            "trailingPercent":"0",
            "type":"LIMIT", 
            "unfillableAt":1654779600000, 
            "isDeleverage":false, 
            "createdAt":1652185521339, 
            "price":"2500.0", 
            "cumSuccessFillValue":"1250.0000", 
            "id":"2048046080",
            "cancelReason":"",
            "timeInForce":1, 
            "updatedAt":1652185521392, 
            "limitFee":"0.625000", 
            "side":"BUY", 
            "clientOrderId":"522843990", 
            "triggerPrice":"",
            "cumSuccessFillSize":"0.500", 
            "accountId":"1024000", 
            "size":"0.500", 
            "reduceOnly":false, 
            "isLiquidate":false, 
            "status":"FILLED" 
          }
        ],
        "positions":[
          {
            "symbol":"ETH-USDC",
            "entryPrice":"2500.0000",      
            "exitPrice":"0", 
            "size":"1.820", 
            "side":"LONG", 
            "maxSize":"2820.000", 
            "sumOpen":"1.820", 
            "sumClose":"0.000", 
            "netFunding":"0.000000", 
            "accountId":"1024000", 
            "createdAt":1652179377769, 
            "realizedPnl":"0", 
            "updatedAt":1652185521392
          }
        ],
        "wallets":[
          {

            "balance":"438.486000", 
            "asset":"USDC" 
            "pendingDepositAmount": "5000", 
            "pendingTransferInAmount": "2000",
            "pendingTransferOutAmount": "3003",
            "pendingWithdrawAmount": "3233",         
          }
        ],
        "accounts":[ 
          {
            "createdAt":1652174136588, 
            "positionId":"1024000", 
            "starkKeyYCoordinate":"0x070880c806d8adfc6ea3fafeb9ea269022f8d8aa797849d9f98660006f33e44f", 
            "userId":"1144093794426437632", 
            "starkKey":"0x0408e25bcadc4a25412258f851d171cb8cb9dfe529f69f2e1b93a9caaf983bc2",
            "updatedAt":1652174136588, 
            "status":"NORMAL" 
          }
        ],
        "fills": [
          {
            "symbol":"ETH-USDC",
            "side":"BUY", 
            "orderId":"2048046080",
            "fee":"0.625000", 
            "liquidity":"TAKER",
            "accountId":"1024000", 
            "createdAt":1652185521361, 
            "isOpen":true,
            "status":"SUCCESS", 
            "size":"0.500",
            "price":"2500.0", 
            "quoteAmount":"1250.0000",
            "id":"2048000182272", 
            "updatedAt":1652185678345 
          },
          "positionClosedTransactions": [{
            ""
          }]
        ],
        "deleverages": [
          {
            account_id = "1";
            symbol = "BTC-USDC"; 
            side = "LONG";
            profit_rate = "20"; 
            light_numbers = 5; 
            created_time = 1652185678345; 
          }          
        ]
      }
    }

Response Parameters

Parameter Type Comment
» account object none
»» starkKey string User starkKey
»» starkKeyYCoordinate string User starkKeyYCoordinate
»» positionId string User accountid
»» userId string User ID
»» makerFeeRate string Maker fee rate
»» takerFeeRate string Taker fee rate
»» createdAt integer Created at
»» status string Account status
» wallets [object] User wallet
»» asset string Asset
»» balance string Wallet balance
»» pendingDepositAmount string Pending deposit amount
»» pendingWithdrawAmount string Pending withdrawal amount
»» pendingTransferOutAmount string Pending outbound transfer amount
»» pendingTransferInAmount string Pending inbound transfer amount
» openPositions [object] Open positions
»» symbol string Symbol
»» side string Side
»» size string Size
»» entryPrice string Entry price
»» fee string Order fee
»» createdAt integer Created at
»» updatedTime integer Updated time
»» netFunding string Funding fee
»» maxSize string Max position size
»» realizedPnl string Close profit and loss
» fills [object]
»» symbol string Symbol
»» side string Order side
»» size string Fill size
»» price string Fill price
»» fee string Fill fee
»» createdAt integer Open order fill time
»» updatedAt integer Open order fill update time
»» isOpen bool Is this an open order?
»» id string Fill ID
»» orderId string Order ID
»» liquidity string Taker or Maker
»» status string Fill status
» orders [object]
»» symbol string Symbol
»» side string Order side
»» size string Order size
»» price string Order open price
»» type string Order Type
»» createdAt integer Open order time
»» updatedAt integer Order update time
»» isDeleverage bool Deleverage order?
»» isLiquidate bool Liquidate order?
»» reduceOnly bool Open reduce order only
»» unfillableAt int Order expired time
»» id string ID
»» orderId string Order ID
»» liquidity string Taker or MAKER
»» status string Order status
»» cumSuccessFillFee string Cumulative success fill fee
»» trailingPercent string Trailing-stop
»» cumSuccessFillValue string Cumulative success fill value
»» cancelReason string Reason for cancelation
»» timeInForce string Open order timeInForce
»» limitFee string Open order max. fee
»» clientOrderId string Client to create randomized ID
»» triggerPrice string Trigger Price
»» cumSuccessFillSize string Cumulative Success Fill Size
» transfers [object] Withdraw and deposit
»» createdAt integer Created time
»» confirmedAt integer Confirm time
»» creditAsset string Asset
»» type bool Transfer type
»» id string Transfer ID
»» creditAmount string Transfer amount
»» transactionHash string Tx hash
»» status string Status
» deleverages [object] / deleverages
»» symbol string Symbol
»» side string Postion side
»» profit_rate string Postion profit rate
»» light_numbers string ADL ranking
»» created_time int Created time

Order Submission Push

{
   "type":"delta",
   "timestamp":1647502440973,
   "topic":"ws_accounts_v1",
   "contents":{
      "orders":[
        {
          "symbol":"ETH-USDC",
          "cumSuccessFillFee":"0.625000",
          "trailingPercent":"0",
          "type":"LIMIT",
          "unfillableAt":1654779600000,
          "isDeleverage":false,
          "createdAt":1652185521339,
          "price":"2500.0",
          "cumSuccessFillValue":"0",
          "id":"2048046080",
          "cancelReason":"",
          "timeInForce":1,
          "updatedAt":1652185521392,
          "limitFee":"0.625000",
          "side":"BUY",
          "clientOrderId":"522843990",
          "triggerPrice":"",
          "expiresAt":1654779600000,
          "cumSuccessFillSize":"0",
          "accountId":"1024000",
          "size":"0.500",
          "reduceOnly":false,
          "isLiquidate":false,
          "remainingSize":"0.000",
          "status":"PENDING"
        }
      ]
   }
}

Post-Submission of Maker Order Push

{
   "type":"delta",
   "timestamp":1647502440973,
   "topic":"ws_accounts_v1",
   "contents":{
      "fills":[

      ],
      "positions":[

      ],
      "orders":[
        {
          "symbol":"ETH-USDC",
          "cumSuccessFillFee":"0.625000",
          "trailingPercent":"0",
          "type":"LIMIT",
          "unfillableAt":1654779600000,
          "isDeleverage":false,
          "createdAt":1652185521339,
          "price":"2500.0",
          "cumSuccessFillValue":"0",
          "id":"2048046080",
          "cancelReason":"",
          "timeInForce":1,
          "updatedAt":1652185521392,
          "limitFee":"0.625000",
          "side":"BUY",
          "clientOrderId":"522843990",
          "triggerPrice":"",
          "expiresAt":1654779600000,
          "cumSuccessFillSize":"0",
          "accountId":"1024000",
          "size":"0.500",
          "reduceOnly":false,
          "isLiquidate":false,
          "remainingSize":"0.000",
          "status":"OPEN"
        }
      ],
      "accounts":[

      ],
      "transfers":[

      ]
   }
}

Post-Cancel Order Push

{
   "type":"delta",
   "timestamp":1647502440973,
   "topic":"ws_accounts_v1",
   "contents":{
      "fills":[

      ],
      "positions":[

      ],
      "orders":[
         {
           "symbol":"ETH-USDC",
           "cumSuccessFillFee":"0.625000",
           "trailingPercent":"0",
           "type":"LIMIT",
           "unfillableAt":1654779600000,
           "isDeleverage":false,
           "createdAt":1652185521339,
           "price":"2500.0",
           "cumSuccessFillValue":"0",
           "id":"2048046080",
           "cancelReason":"",
           "timeInForce":1,
           "updatedAt":1652185521392,
           "limitFee":"0.625000",
           "side":"BUY",
           "clientOrderId":"522843990",
           "triggerPrice":"",
           "expiresAt":1654779600000,
           "cumSuccessFillSize":"0",
           "accountId":"1024000",
           "size":"0.500",
           "reduceOnly":false,
           "isLiquidate":false,
           "remainingSize":"0.000",
           "status":"CANCELED"
         }
      ],
      "accounts":[

      ],
      "transfers":[

      ]
   }
}

Successful Order Execution Push


{
   "type":"delta",
   "timestamp":1647502440973,
   "topic":"ws_accounts_v1",
   "contents":{
      "fills":[
         {
           "symbol":"ETH-USDC",
           "side":"BUY",
           "orderId":"2048046080",
           "fee":"0.625000",
           "liquidity":"TAKER",
           "accountId":"1024000",
           "createdAt":1652185521361,
           "isOpen":true,
           "size":"0.500",
           "price":"2500.0",
           "quoteAmount":"1250.0000",
           "id":"2048000182272",
           "updatedAt":1652185678345
         }
      ],
      "positions":[
         {
           "symbol":"ETH-USDC",
           "exitPrice":"0",
           "side":"LONG",
           "maxSize":"2820.000",
           "sumOpen":"1.820",
           "sumClose":"0.000",
           "netFunding":"0.000000",
           "entryPrice":"2500.000000000000000000",
           "accountId":"1024000",
           "createdAt":1652179377769,
           "size":"1.820",
           "realizedPnl":"0",
           "closedAt":1652185521392,
           "updatedAt":1652185521392
         }
      ],
      "orders":[
         {
           "symbol":"ETH-USDC",
           "cumSuccessFillFee":"0.625000",
           "trailingPercent":"0",
           "type":"LIMIT",
           "unfillableAt":1654779600000,
           "isDeleverage":false,
           "createdAt":1652185521339,
           "price":"2500.0",
           "cumSuccessFillValue":"1250.0000",
           "id":"2048046080",
           "cancelReason":"",
           "timeInForce":1,
           "updatedAt":1652185521392,
           "limitFee":"0.625000",
           "side":"BUY",
           "clientOrderId":"522843990",
           "triggerPrice":"",
           "expiresAt":1654779600000,
           "cumSuccessFillSize":"0.500",
           "accountId":"1024000",
           "size":"0.500",
           "reduceOnly":false,
           "isLiquidate":false,
           "remainingSize":"0.000",
           "status":"FILLED"
         }
      ],
      "accounts":[
      ],
      "transfers":[
      ]
   }
}

Deposit Success Push

{
   "type":"delta",
   "timestamp":1647502440973,
   "topic":"ws_accounts_v1",
   "contents":{
      "fills":[
      ],
      "positions":[
      ],
      "orders":[         
      ],
     "wallets":[
       {
         "balance":"438.486000",
         "asset":"USDC"
       }
     ]
   }
}

Withdrawal Request Submission Push


{
   "type":"delta",
   "timestamp":1647502440973,
   "topic":"ws_accounts_v1",
   "contents":{
      "fills":[

      ],
      "positions":[

      ],
      "orders":[

      ],
      "accounts":[
      ],
      "transfers":[
         {
            "status":"QUEUED",
            "transactionId":"39190120",
            "id":"89abf9d72432",
            "type":"WITHDRAWAL",
            "creditAsset":"USDC",
            "creditAmount":"100",
            "transactionHash":null,
            "confirmedAt":null,
            "createdAt":1647502440973,
            "expiresAt":1647502440973
         }
      ]
   }
}

Notify Message Push

{
  "contents": {
    "unreadNum": 24, 
    "notifyMsgList": [
      {
        "id": "1145486332832022528",  
        "category": 1, 
        "lang": "en",
        "title": "Deposit success ", 
        "content": "Your deposit of 100.000000 USDC has been confirmed.", 
        "androidLink": "", 
        "iosLink": "", 
        "webLink": "",  
        "read": false, 
        "createdTime": 1682357834534  
      }
      ...
    ]
  },
  "topic": "ws_notify_v1",
  "type": "snapshot"
}

Response Parameters

Parameter Type Comment
» notifyMsgList object Notification message list
»» id string Notification ID
»» category int Notification category
»» lang string Language
»» title string Title
»» content string Content
»» androidLink string Android link
»» iosLink string Ios link
»» webLink string Web link
»» read bool If notification has been read
»» createdTime int Created time

New Notification Message Push

Response

{
  "contents": {
    "notify_list": [
      {
        "id": "1145486332832022528",  
        "category": "NOTIFY_CATEGORY_ACCOUNT", 
        "lang": "en", 
        "title": "Deposit success ", 
        "content": "Your deposit of 100.000000 USDC has been confirmed.", 
        "androidLink": "", 
        "iosLink": "", 
        "webLink": "",  
        "read": false, 
        "createdTime": 1682357834534 
      }
    ]
  },
  "topic": "ws_notify_v1",
  "type": "delta"
}

Gnosis Multi-Sig Wallet Endpoint for Market Makers

v1.0.0

Creating a Gnosis Safe Multi-Sig Wallet

Click on https://gnosis-safe.io/app/ to access the application on desktop. Refer to the document gnosis_safe and create your multi-sig wallet according to the following steps:

StarkWare Smart Contract ABI Code

[
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "starkKey",
        "type": "uint256"
      },
      {
        "internalType": "uint256", "name": "assetType",
        "type": "uint256"
      },
      {
        "internalType": "uint256", "name": "vaultId",
        "type": "uint256"
      },
      {
        "internalType": "uint256", "name": "quantizedAmount", "type": "uint256"
      }
    ],
    "name": "depositERC20",
    "outputs":      [], "stateMutability": "nonpayable", "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "starkKey",
        "type": "uint256"
      }
    ],
    "name": "getEthKey",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "starkKey",
        "type": "uint256"
      },
      {
        "internalType": "uint256", "name": "assetId",
        "type": "uint256"
      }
    ],
    "name": "getWithdrawalBalance",
    "outputs": [
      {
        "internalType": "uint256", "name": "balance",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "ethKey",
        "type": "address"
      },
      {
        "internalType": "uint256", "name": "starkKey",
        "type": "uint256"
      },
      {
        "internalType": "bytes", "name": "starkSignature", "type": "bytes"
      }
    ],
    "name": "registerEthAddress",
    "outputs":      [], "stateMutability": "nonpayable", "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "starkKey",
        "type": "uint256"
      },
      {
        "internalType": "uint256", "name": "assetId",
        "type": "uint256"
      }
    ],
    "name": "withdraw",
    "outputs":      [], "stateMutability": "nonpayable", "type": "function"
  }
]

Generating ApexPro L2key Account

Generating starkKey

from apexpro.http_private import HttpPrivate
from apexpro.constants import APEX_HTTP_TEST, NETWORKID_TEST, APEX_HTTP_MAIN, NETWORKID_MAIN

priKey = "your eth private key"

client = HttpPrivate(APEX_HTTP_MAIN, network_id=NETWORKID_MAIN, eth_private_key=priKey)
configs = client.configs()

stark_key_pair_with_y_coordinate = client.derive_stark_key(client.default_address)

register_user method to generate account ID

nonceRes = client.generate_nonce(starkKey=stark_key_pair_with_y_coordinate['public_key'],ethAddress=client.default_address,chainId=NETWORKID_MAIN)

regRes = client.register_user(nonce=nonceRes['data']['nonce'],starkKey=stark_key_pair_with_y_coordinate['public_key'],stark_public_key_y_coordinate=stark_key_pair_with_y_coordinate['public_key_y_coordinate'],ethereum_address=client.default_address,
                              eth_mul_address="your mul eth address")


print(regRes['data']['account']['positionId'])  #account ID                          

Generating Stark Signature

from apexpro.helpers.request_helpers import calc_bind_owner_key_sig_hash, starkex_sign, starkex_verify

hash = calc_bind_owner_key_sig_hash("your stark_key_pair pubic key", "your eth address")
print(hash.hex())

signature = starkex_sign(hash, "your stark_key_pair private key")
print("signature:" + signature)

Authorize StarkWare Contract to Transfer USDC via Gnosis Safe

As deposits will be processed through StarkWare, you will need to authorize the StarkWare contract to transfer your USDC assets.

USDC Contract ABI

[{
"inputs": [{
"internalType": "address",
"name": "spender",
"type": "address" }, {
"internalType": "uint256", "name": "value",
"type": "uint256"
}],
"name": "approve", "outputs": [{
"internalType": "bool", "name": "",
"type": "bool"
}],
"stateMutability": "nonpayable", "type": "function"
}]

Deposit via Gnosis Safe

Checking for Withdrawable Balance With Gnosis Safe

Initiating Withdrawals With Gnosis Safe

Errors

The API uses the following error codes:

Error Code Meaning
400 Bad Request : Your request is invalid.
403 IP banned : Your IP is banned.
404 Not Found : The request path could not be found.
500 Internal Server Error: We're experiencing issues with our server. Please try again later.
503 Service Unavailable: We're temporarily offline for maintenance. Please try again later.
10001 Failed : error request.
10002 Requires Login : Your API key is wrong.
10003 Too Many Requests : Slow down!
10004 Request Timeout
Error Key Meaning
UNKNOWN ("Service Error ."),
INVALID_L2_SIGNATURE ("Invalid L2 signature."),
INVALID_ETH_ADDRESS ("Invalid ethAddress."),
INVALID_LP_ACCOUNT ("Invalid lp account id. {accountId}"),
INVALID_FEE ("Invalid fee request {fee}"),
INVALID_L2_TX ("Invalid l2 txhash"),
INVALID_USER_ID ("Invalid userId. {userId}"),
INVALID_ACCOUNT_ID ("Invalid accountId. {accountId}"),
INVALID_CURRENCY_ID ("invalid currencyId. {currencyId} "),
INVALID_CLIENT_WITHDRAW_ID ("Invalid clientWithdraw Id. {clientWithdrawId}"),
INVALID_CLIENT_TRANSFER_ID ("Invalid clientTransfer Id. {clientTransferId}"),
INVALID_PAGE_SIZE ("Invalid page size. {size}"),
EMPTY_CHAIN_ID ("Empty chainId."),
EMPTY_CLIENT_FAST_WITHDRAW_ID ("Empty clientFastWithdraw Id."),
EMPTY_PARAM ("{name}Empty request param."),
EMPTY_CLIENT_WITHDRAW_ID ("Empty clientWithdraw Id."),
EMPTY_CLIENT_TRANSFER_ID ("Empty clientTransfer Id."),
AMOUNT_MUST_GREETER_ZERO ("Amount must greater than 0. {amount}"),
ACCOUNT_NOT_FOUND ("The account does not exist. {accountId}"),
ACCOUNT_NOT_FOUND_L2KEY ("The account does not exist. {l2Key}"),
ACCOUNT_NOT_FOUND_LP ("The account does not exist. {lpAccountId}"),
ACCOUNT_CONFLICT_L2KEY ("The account already exists. Please select another account. {l2Key}"),
ORDER_NOT_FOUND ("This order does not exist. {orderId}"),
ORDER_NOT_CANCEL_MATCHED ("Order processing, please do not cancel. {orderId}"),
ORDER_NOT_CANCEL_FILLED ("Order successful, please do not cancel. {orderId}"),
ORDER_NOT_CANCEL_INVALID_STATUS ("Invalid order, please do not cancel. {orderId}"),
ORDER_INVALID_ORDER_TYPE ("This order type is invalid. {orderType}"),
ORDER_INVALID_TIME_IN_FORCE ("Invalid time-in-force. {timeInForce}"),
ORDER_INVALID_STATUS ("This order status is invalid. {orderStatus}"),
ORDER_INVALID_ORDER_SIDE ("This order direction is invalid. {orderSide}"),
ORDER_LIMIT_FEE_NOT_ENOUGH ("Insufficient gas fees on this order. {limitFee}"),
ORDER_FILL_TRANSACTION_ID_NOT_FOUND ("This order does not exist.{transactionId}"),
ORDER_FILL_TRANSACTION_CENSOR_ROUND_CONFLICT ("Order submission error. {censorRound}"),
ORDER_FILL_TRANSACTION_INVALID_STATUS ("Order submission status is invalid. {transactionStatus}"),
ORDER_EMPTY_CLIENT_ORDER_ID ("Empty clientOrderId."),
ORDER_INVALID_CLIENT_ORDER_ID ("Invalid clientOrderId. {clientOrderId}"),
ORDER_LIQUIDATE_ORDER_FAILED ("Liquidation Unsuccessful."),
ORDER_DELEVERAGE_WITH_SAME_ACCOUNT ("The deleveraging account and the liquidation account are the same, transaction has failed."),
ORDER_CLIENT_ORDER_DATA_CONFLICT ("Please resubmit your order. {clientOrderId}"),
ORDER_PRICE_MUST_GREETER_ZERO ("Price must greater than 0. {price}"),
ORDER_SIZE_MUST_GREETER_ZERO ("Size must greater than 0. {size}"),
ORDER_VALUE_MUST_GREETER_ZERO ("Value must greater than 0. {value}"),
ORDER_LIMIT_FEE_MUST_GREETER_ZERO ("LimitFee must greater than or equal 0. {limitFee}"),
ORDER_TRIGGER_PRICE_MUST_GREETER_ZERO ("TriggerPrice must greater than 0. {triggerPrice}"),
ORDER_SYMBOL_DISABLE_TRADE ("Symbol {symbol} disable trade"),
ORDER_SIZE_SMALLER_THAN_SYMBOL_MIN_ORDER_SIZE ("Order size {size} smaller than symbol {symbol} min order size {minOrderSize}"),
ORDER_SIZE_GREATER_THAN_SYMBOL_MAX_ORDER_SIZE ("Order size {size} greater than symbol {symbol} max order size {maxOrderSize}"),
ORDER_LIQUIDATING_ACCOUNT_CANNOT_CREATE_ORDER ("Account is liquidating, cannot create order"),
ORDER_OPEN_ORDER_COUNT_LIMIT_EXCEED ("You have {openOrderCount} open orders, cannot create new order"),
ORDER_WITH_THIS_PRICE_CANNOT_REDUCE_POSITION_ONLY ("Order with this price {price} cannot reduce position only"),
ORDER_SYMBOL_DISABLE_OPEN_POSITION ("Symbol '{symbol}' disable open position"),
ORDER_IS_REDUCE_ONLY_CANNOT_OPEN_POSITION ("Order is reduce-only, cannot open position"),
ORDER_IS_LIQUIDATE_ONLY_CANNOT_OPEN_POSITION ("Order liquidated, cannot open position"),
ORDER_IS_DELEVERAGE_ONLY_CANNOT_OPEN_POSITION ("Order auto deleveraged, cannot open position"),
ORDER_POSSIBLE_GREATER_THAN_SYMBOL_MAX_POSITION ("If order is filled, it can be greater than symbol '{symbol}' max. position size {maxPositionSize}"),
ORDER_IS_LIQUIDATE_NOT_MATCH_PRE_CONDITION ("Liquidation order not match pre-condition: beforeTV({beforeTV}) < beforeTR({beforeTR})"),
ORDER_IS_LIQUIDATE_AND_DELEVERAGE_NOT_MATCH_PRE_CONDITION ("Liquidation and ADL order not match pre-condition:beforeTV({beforeTV}) < 0"),
ORDER_POSSIBLE_LEAD_TO_ACCOUNT_LIQUIDATED ("If order is filled, your account may be liquidated."),
ORDER_POSSIBLE_LEAD_TO_ACCOUNT_LIQUIDATED_TV_TR_RATE_NOT_IMPROVED ("If order is filled and TV/TR does not improve, your account may be liquidated."),
ORDER_THERE_IS_NOT_ENOUGH_MARGIN_TO_OPEN_POSITION ("If order is filled, there is insufficient margin to open position"),
CROSS_DEPOSIT_DATA_ERROR ("Deposit error"),
CROSS_DEPOSIT_CURRENCY_ID_AMOUNT_CHANGED ("Deposit error. {currencyId}, {amount}"),
CROSS_WITHDRAW_WALLET_BALANCE_NOT_ENOUGH ("Insufficient wallet balance."),
CROSS_WITHDRAW_DATA_ERROR ("Cross-chain withdrawal error"),
CROSS_WITHDRAW_ID_NOT_FOUND ("Cross-chain withdrawal error. {withdrawId}"),
CROSS_WITHDRAW_INVALID_STATUS ("Cross-chain withdrawal error. {status}"),
CROSS_WITHDRAW_GREETER_MAX_ABLE_AMOUNT ("Your withdrawal amount has exceeded the max. withdrawal limit, please try again."),
CROSS_WITHDRAW_RISK_CHECK_FAILED ("Cross-chain withdrawal error"),
CROSS_WITHDRAW_INVALID_ARGUMENT ("Cross-chain withdrawal error"),
FAST_WITHDRAW_DATA_ERROR ("Fast withdrawal error."),
FAST_WITHDRAW_GREETER_MAX_ABLE_AMOUNT ("Your withdrawal amount has exceeded the max. withdrawal limit, please try again."),
FAST_WITHDRAW_RISK_CHECK_FAILED ("Fast withdrawal error."),
FAST_WITHDRAW_INVALID_ARGUMENT ("Fast withdrawal error."),
FAST_WITHDRAW_ID_NOT_FOUND ("Fast withdrawal error. {withdrawId}"),
FAST_WITHDRAW_INVALID_STATUS ("Fast withdrawal error. {status}"),
FAST_WITHDRAW_WALLET_BALANCE_NOT_ENOUGH ("Fast withdrawal unsuccessful, insufficient wallet balance."),
DEPOSIT_ASSET_ID_INVALID ("Deposit error. {assetId}"),
DEPOSIT_AMOUNT_INVALID ("Invalid deposit amount. {amount}"),
DEPOSIT_ASSET_ID_AMOUNT_CHANGED ("Data error! Incorrect deposit amount.. {assetId},{amount}"),
DEPOSIT_STATUS_INVALID ("Data error! Incorrect deposit status. {status}"),
DEPOSIT_CENSOR_ROUND_CONFLICT (" Deposit censor round conflict. {censorRound}"),
DEPOSIT_ID_NOT_FOUND ("Data error! Incorrect deposit ID. {depositId}"),
WITHDRAW_INVALID_ARGUMENT ("Client withdrawal data conflict."),
WITHDRAW_WALLET_BALANCE_NOT_ENOUGH ("Withdrawal unsuccessful, insufficient wallet balance."),
WITHDRAW_CANNOT_FIND_WITHDRAW ("Withdrawal error. ${withdrawId}"),
WITHDRAW_CENSOR_ROUND_CONFLICT ("Withdraw censor round conflict. ${censorRound}"),
WITHDRAW_INVALID_STATUS ("Withdrawal status invalid. ${status}"),
TRANSFER_WITH_SAME_ACCOUNT ("invalid parameters, transfer with same account. ${accountId}"),
TRANSFER_CONDITION_FACT_REG_ADDRESS_EMPTY ("conditionFactRegistryAddress is empty"),
TRANSFER_CONDITION_FACT_EMPTY ("conditionFact is empty"),
NOT_CONDITION_TRANSFER_IN ("Not condition transferIn. ${transferInId}"),
NOT_CONDITION_TRANSFER_OUT ("Not condition transferOut. ${transferOutId}"),
TRANSFER_IN_STATUS_INVALID ("transferIn status invalid. ${status}"),
TRANSFER_OUT_STATUS_INVALID ("transferOut status invalid. {status}"),
TRANSFER_OUT_CENSOR_ROUND_CONFLICT ("transferOut censor round conflict. ${censorRound}"),
TRANSFER_IN_CENSOR_ROUND_CONFLICT ("transferIn censor round conflict. {censorRound}"),
CLIENT_TRANSFER_OUT_DATA_CONFLICT ("Client transfer out data conflict. ${clientTransferId}"),
TRANSFER_WALLET_BALANCE_NOT_ENOUGH ("Cannot transfer out, wallet balance not enough."),