NAV
中文
HTTP Python

Overview

Welcome to our V5 API documentation. OKX TR provides REST and WebSocket APIs to suit your trading needs.

API Resources and Support

Tutorials


Python libraries


Customer service

V5 API Key Creation

Please refer to my API page regarding V5 API Key creation.

Generating an API Key

Create an API Key on the website before signing any requests. After creating an APIKey, keep the following information safe:

The system returns randomly-generated APIKeys and SecretKeys. You will need to provide the Passphrase to access the API. We store the salted hash of your Passphrase for authentication. We cannot recover the Passphrase if you have lost it. You will need to create a new set of APIKey.

There are three permissions below that can be associated with an API key. One or more permission can be assigned to any key.

REST Authentication

Making Requests

All private REST requests must contain the following headers:

Request bodies should have content type application/json and be in valid JSON format.

Signature

Signing Messages

The OK-ACCESS-SIGN header is generated as follows:

Example: sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(timestamp + 'GET' + '/api/v5/account/balance?ccy=BTC', SecretKey))

The timestamp value is the same as the OK-ACCESS-TIMESTAMP header with millisecond ISO format, e.g. 2020-12-08T09:08:57.715Z.

The request method should be in UPPERCASE: e.g. GET and POST.

The requestPath is the path of requesting an endpoint.

Example: /api/v5/account/balance

The body refers to the String of the request body. It can be omitted if there is no request body (frequently the case for GET requests).

Example: {"instId":"BTC-USDT","lever":"5","mgnMode":"isolated"}

The SecretKey is generated when you create an APIKey. Example: 22582BD0CFF14C41EDBF1AB98506286D

WebSocket

Overview

WebSocket is a new HTML5 protocol that achieves full-duplex data transmission between the client and server, allowing data to be transferred effectively in both directions. A connection between the client and server can be established with just one handshake. The server will then be able to push data to the client according to preset rules. Its advantages include:

Connect

Connection limit: 3 requests per second (based on IP)

When subscribing to a public channel, use the address of the public service. When subscribing to a private channel, use the address of the private service

Request limit:

The total number of 'subscribe'/'unsubscribe'/'login' requests per connection is limited to 480 times per hour.

Login

Request Example

{
  "op": "login",
  "args": [
    {
      "apiKey": "985d5b66-57ce-40fb-b714-afc0b9787083",
      "passphrase": "123456",
      "timestamp": "1538054050",
      "sign": "7L+zFQ+CEgGu5rzCj4+BdV2/uUHGqddA9pI6ztsRRPs="
    }
  ]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation
login
args Array Yes List of account to login
> apiKey String Yes API Key
> passphrase String Yes API Key password
> timestamp String Yes Unix Epoch time, the unit is seconds
> sign String Yes Signature string

Successful Response Example

{
  "event": "login",
  "code": "0",
  "msg": "",
  "connId": "a4d3ae55"
}

Failure Response Example

{
  "event": "error",
  "code": "60009",
  "msg": "Login failed.",
  "connId": "a4d3ae55"
}

Response parameters

Parameter Type Required Description
event String Yes Operation
login
error
code String No Error code
msg String No Error message
connId String Yes WebSocket connection ID

api_key: Unique identification for invoking API. Requires user to apply one manually.

passphrase: API Key password

timestamp: the Unix Epoch time, the unit is seconds

sign: signature string, the signature algorithm is as follows:

First concatenate timestamp, method, requestPath, strings, then use HMAC SHA256 method to encrypt the concatenated string with SecretKey, and then perform Base64 encoding.

secretKey: The security key generated when the user applies for APIKey, e.g. : 22582BD0CFF14C41EDBF1AB98506286D

Example of timestamp: const timestamp = '' + Date.now() / 1,000

Among sign example: sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(timestamp +'GET'+'/users/self/verify', secretKey))

method: always 'GET'.

requestPath : always '/users/self/verify'

Subscribe

Subscription Instructions

Request format description

{
  "op": "subscribe",
  "args": ["<SubscriptionTopic>"]
}

WebSocket channels are divided into two categories: public and private channels.

Public channels -- No authentication is required, include tickers channel, K-Line channel and order book channel, etc.

Private channels -- including account channel and order channel, etc -- require log in.

Users can choose to subscribe to one or more channels, and the total length of multiple channels cannot exceed 64 KB.

Below is an example of subscription parameters. The requirement of subscription parameters for each channel is different. For details please refer to the specification of each channels.

Request Example

{
  "op": "subscribe",
  "args": [
    {
      "channel": "tickers",
      "instId": "LTC-USDT"
    },
    {
      "channel": "candle1m",
      "instId": "LTC-USDT"
    }
  ]
}

Request parameters

Parameter Type Required Description
op String Yes Operation
subscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name
> instType String No Instrument type
SPOT
ANY
> instId String No Instrument ID

Response Example

{
  "event": "subscribe",
  "arg": {
    "channel": "tickers",
    "instId": "LTC-USDT"
  },
  "connId": "a4d3ae55"
}

Return parameters

Parameter Type Required Description
event String Yes Event, subscribe error
arg Object No Subscribed channel
> channel String Yes Channel name
> instType String No Instrument type
SPOT
ANY
> instId String No Instrument ID
code String No Error code
msg String No Error message
connId String Yes WebSocket connection ID

Unsubscribe

Unsubscribe from one or more channels.

Request format description

{
  "op": "unsubscribe",
  "args": ["< SubscriptionTopic>"]
}

Request Example

{
  "op": "unsubscribe",
  "args": [
    {
      "channel": "tickers",
      "instId": "LTC-USDT"
    },
    {
      "channel": "candle1m",
      "instId": "LTC-USDT"
    }
  ]
}

Request parameters

Parameter Type Required Description
op String Yes Operation
unsubscribe
args Array Yes List of channels to unsubscribe from
> channel String Yes Channel name
> instType String No Instrument type
SPOT
ANY
> instId String No Instrument ID

Response Example

{
  "event": "unsubscribe",
  "arg": {
    "channel": "tickers",
    "instId": "LTC-USDT"
  },
  "connId": "a4d3ae55"
}

Response parameters

Parameter Type Required Description
event String Yes Event, unsubscribe error
arg Object No Unsubscribed channel
> channel String Yes Channel name
> instType String No Instrument type
SPOT
ANY
> instId String No Instrument ID
code String No Error code
msg String No Error message

Production Trading Services

The Production Trading URL:

AWS URL:

Demo Trading Services

Currently, the V5 API works for Demo Trading, but some functions are not supported, such as `withdraw','deposit','purchase/redemption', etc.

The Demo Trading URL:

OKX TR account can be used for login on Demo Trading. If you already have an OKX TR account, you can log in directly.

Start API Demo Trading by the following steps:
Login OKX TR —> Trade —> Demo Trading —> Personal Center —> Demo Trading API -> Create Demo Trading V5 API Key —> Start your Demo Trading

Http Header Example

Content-Type: application/json

OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418

OK-ACCESS-SIGN: leaVRETrtaoEQ3yI9qEtI1CZ82ikZ4xSG5Kj8gnl3uw=

OK-ACCESS-PASSPHRASE: 1****6

OK-ACCESS-TIMESTAMP: 2020-03-28T12:21:41.274Z

x-simulated-trading: 1

General Info

The rules for placing orders at the exchange level are as follows:


The rules for trading are as follows:


The rules for the returning data are as follows:


Transaction Timeouts

Orders may not be processed in time due to network delay or busy OKX servers. You can configure the expiry time of the request using expTime if you want the order request to be discarded after a specific time.

If expTime is specified in the requests for Place (multiple) orders or Amend (multiple) orders, the request will not be processed if the current system time of the server is after the expTime.

You should synchronize with our system time. Use Get system time to obtain the current system time.

REST API

Set the following parameters in the request header

Parameter Type Required Description
expTime String No Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085

The following endpoints are supported:

Request Example

curl -X 'POST' \
  'https://www.okx.com/api/v5/trade/order' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'OK-ACCESS-KEY: *****' \
  -H 'OK-ACCESS-SIGN: *****'' \
  -H 'OK-ACCESS-TIMESTAMP: *****'' \
  -H 'OK-ACCESS-PASSPHRASE: *****'' \
  -H 'expTime: 1597026383085' \   // request effective deadline
  -d '{
  "instId": "BTC-USDT",
  "tdMode": "cash",
  "side": "buy",
  "ordType": "limit",
  "px": "1000",
  "sz": "0.01"
}'

WebSocket

The following parameters are set in the request

Parameter Type Required Description
expTime String No Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085

The following endpoints are supported:

Request Example

{
    "id": "1512",
    "op": "order",
    "expTime":"1597026383085",  // request effective deadline
    "args": [{
        "side": "buy",
        "instId": "BTC-USDT",
        "tdMode": "isolated",
        "ordType": "market",
        "sz": "100"
    }]
}

Rate Limits

Our REST and WebSocket APIs use rate limits to protect our APIs against malicious usage so our trading platform can operate reliably and fairly.
When a request is rejected by our system due to rate limits, the system returns error code 50011 (Rate limit reached. Please refer to API documentation and throttle requests accordingly).
The rate limit is different for each endpoint. You can find the limit for each endpoint from the endpoint details. Rate limit definitions are detailed below:

For Trading-related APIs (place order, cancel order, and amend order) the following conditions apply:

Best practices

If you require a higher request rate than our rate limit, you can set up different sub-accounts to batch request rate limits. We recommend this method for throttling or spacing out requests in order to maximize each accounts' rate limit and avoid disconnections or rejections.

Trading Account

The API endpoints of Account require authentication.

REST API

Get balance

Retrieve a list of assets (with non-zero balance), remaining balance, and available amount in the trading account.

Rate Limit: 10 requests per 2 seconds

Rate limit rule: UserID

HTTP Requests

GET /api/v5/account/balance

Request Example

# Get the balance of all assets in the account
GET /api/v5/account/balance

# Get the balance of BTC and ETH assets in the account
GET /api/v5/account/balance?ccy=BTC,ETH

import okx.Account as Account

# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"

flag = "1"  # Production trading:0 , demo trading:1

accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)

# Get account balance
result = accountAPI.get_account_balance()
print(result)

Request Parameters

Parameters Types Required Description
ccy String No Single currency or multiple currencies (no more than 20) separated with comma, e.g. BTC or BTC,ETH.

Response Example

{
    "code": "0",
    "data": [
        {
            "adjEq": "55415.624719833286",
            "borrowFroz": "0",
            "details": [
                {
                    "availBal": "4834.317093622894",
                    "availEq": "4834.3170936228935",
                    "borrowFroz": "0",
                    "cashBal": "4850.435693622894",
                    "ccy": "USDT",
                    "crossLiab": "0",
                    "disEq": "4991.542013297616",
                    "eq": "4992.890093622894",
                    "eqUsd": "4991.542013297616",
                    "fixedBal": "0",
                    "frozenBal": "158.573",
                    "imr": "",
                    "interest": "0",
                    "isoEq": "0",
                    "isoLiab": "0",
                    "isoUpl": "0",
                    "liab": "0",
                    "maxLoan": "0",
                    "mgnRatio": "",
                    "mmr": "",
                    "notionalLever": "",
                    "ordFrozen": "0",
                    "spotInUseAmt": "",
                    "spotIsoBal": "0",
                    "stgyEq": "150",
                    "twap": "0",
                    "uTime": "1705449605015",
                    "upl": "-7.545600000000006",
                    "uplLiab": "0"
                }
            ],
            "imr": "8.57068529",
            "isoEq": "0",
            "mgnRatio": "143682.59776662575",
            "mmr": "0.3428274116",
            "notionalUsd": "85.7068529",
            "ordFroz": "0",
            "totalEq": "55837.43556134779",
            "uTime": "1705474164160",
            "upl": "-7.543562688000006"
        }
    ],
    "msg": ""
}

Response Parameters

Parameters Types Description
uTime String Update time of account information, millisecond format of Unix timestamp, e.g. 1597026383085
totalEq String The total amount of equity in USD
isoEq String Isolated margin equity in USD
Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
adjEq String Adjusted / Effective equity in USD
The net fiat value of the assets in the account that can provide margins for spot, expiry futures, perpetual futures and options under the cross-margin mode.
In multi-ccy or PM mode, the asset and margin requirement will all be converted to USD value to process the order check or liquidation.
Due to the volatility of each currency market, our platform calculates the actual USD value of each currency based on discount rates to balance market risks.
Applicable to Multi-currency margin and Portfolio margin
ordFroz String Cross margin frozen for pending orders in USD
Only applicable to Multi-currency margin
imr String Initial margin requirement in USD
The sum of initial margins of all open positions and pending orders under cross-margin mode in USD.
Applicable to Multi-currency margin/Portfolio margin
mmr String Maintenance margin requirement in USD
The sum of maintenance margins of all open positions and pending orders under cross-margin mode in USD.
Applicable to Multi-currency margin/Portfolio margin
borrowFroz String Potential borrowing IMR of the account in USD
Only applicable to Multi-currency margin/Portfolio margin. It is "" for other margin modes.
mgnRatio String Margin ratio in USD
Applicable to Multi-currency margin/Portfolio margin
notionalUsd String Notional value of positions in USD
Applicable to Multi-currency margin/Portfolio margin
upl String Cross-margin info of unrealized profit and loss at the account level in USD
Applicable to Multi-currency margin/Portfolio margin
details Array Detailed asset information in all currencies
> ccy String Currency
> eq String Equity of currency
> cashBal String Cash balance
> uTime String Update time of currency balance information, Unix timestamp format in milliseconds, e.g. 1597026383085
> isoEq String Isolated margin equity of currency
Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
> availEq String Available equity of currency
The balance that can be used on margin or futures/swap trading.
Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
> disEq String Discount equity of currency in USD.
> fixedBal String Frozen balance for Dip Sniper and Peak Sniper
> availBal String Available balance of currency
The balance that can be withdrawn or transferred or used on spot trading.
> frozenBal String Frozen balance of currency
> ordFrozen String Margin frozen for open orders
Applicable to Simple/Single-currency margin/Multi-currency margin
> liab String Liabilities of currency
It is a positive value, e.g. 21625.64
Applicable to Multi-currency margin/Portfolio margin
> upl String The sum of the unrealized profit & loss of all margin and derivatives positions of currency.
Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
> uplLiab String Liabilities due to Unrealized loss of currency
Applicable to Multi-currency margin/Portfolio margin
> crossLiab String Cross liabilities of currency
Applicable to Multi-currency margin/Portfolio margin
> isoLiab String Isolated liabilities of currency
Applicable to Multi-currency margin/Portfolio margin
> mgnRatio String Margin ratio of currency
The index for measuring the risk of a certain asset in the account.
Applicable to Single-currency margin
> interest String Accrued interest of currency
It is a positive value, e.g. 9.01
Applicable to Multi-currency margin/Portfolio margin
> twap String Risk indicator of auto liability repayment
Divided into multiple levels from 0 to 5, the larger the number, the more likely the auto repayment will be triggered.
Applicable to Multi-currency margin/Portfolio margin
> maxLoan String Max loan of currency
Applicable to cross of Multi-currency margin/Portfolio margin
> eqUsd String Equity in USD of currency
> borrowFroz String Potential borrowing IMR of currency in USD
Applicable to Multi-currency margin/Portfolio margin. It is "" for other margin modes.
> notionalLever String Leverage of currency
Applicable to Single-currency margin
> stgyEq String Strategy equity
> isoUpl String Isolated unrealized profit and loss of currency
Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
> spotInUseAmt String Spot in use amount
Applicable to Portfolio margin
> spotIsoBal String Spot isolated balance
Applicable to copy trading
> imr String Initial margin requirement at the currency level
Applicable to Single-currency margin
> mmr String Maintenance margin requirement at the currency level
Applicable to Single-currency margin

Distribution of applicable fields under each account level are as follows:

Parameters Simple Single-currency margin Multi-currency margin
uTime Yes Yes Yes
totalEq Yes Yes Yes
isoEq Yes Yes
adjEq Yes
ordFroz Yes
imr Yes
mmr Yes
mgnRatio Yes
notionalUsd Yes
upl Yes
details Yes
> ccy Yes Yes Yes
> eq Yes Yes Yes
> cashBal Yes Yes Yes
> uTime Yes Yes Yes
> isoEq Yes Yes
> availEq Yes Yes
> disEq Yes Yes Yes
> availBal Yes Yes Yes
> frozenBal Yes Yes Yes
> ordFrozen Yes Yes Yes
> liab Yes
> upl Yes Yes
> uplLiab Yes
> crossLiab Yes
> isoLiab Yes
> mgnRatio Yes
> interest Yes
> twap Yes
> maxLoan Yes
> eqUsd Yes Yes Yes
> notionalLever Yes
> stgyEq Yes Yes Yes
> isoUpl Yes Yes
> imr Yes
> mmr Yes

Get bills details (last 7 days)

Retrieve the bills of the account. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with the most recent first. This endpoint can retrieve data from the last 7 days.

Rate Limit: 5 requests per second

Rate limit rule: UserID

HTTP Request

GET /api/v5/account/bills

Request Example

GET /api/v5/account/bills

GET /api/v5/account/bills?instType=SPOT

import okx.Account as Account

# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"

flag = "1"  # Production trading:0 , demo trading:1

accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)

# Get bills details (last 7 days)
result = accountAPI.get_account_bills()
print(result)

Request Parameters

Parameter Type Required Description
instType String No Instrument type
SPOT
ccy String No Bill currency
type String No Bill type
1: Transfer
2: Trade
6: Margin transfer
subType String No Bill subtype
1: Buy
2: Sell
11: Transfer in
12: Transfer out
236: Easy convert in
237: Easy convert out
after String No Pagination of data to return records earlier than the requested bill ID.
before String No Pagination of data to return records newer than the requested bill ID.
begin String No Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
end String No Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
limit String No Number of results per request. The maximum is 100. The default is 100.

Response Example

{
    "code": "0",
    "msg": "",
    "data": [{
        "bal": "8694.2179403378290202",
        "balChg": "0.0219338232210000",
        "billId": "623950854533513219",
        "ccy": "USDT",
        "clOrdId": "",
        "execType": "T",
        "fee": "-0.000021955779",
        "fillFwdPx": "",
        "fillIdxPx": "27104.1",
        "fillMarkPx": "",
        "fillMarkVol": "",
        "fillPxUsd": "",
        "fillPxVol": "",
        "fillTime": "1695033476166",
        "from": "",
        "instId": "BTC-USDT",
        "instType": "SPOT",
        "interest": "0",
        "mgnMode": "isolated",
        "notes": "",
        "ordId": "623950854525124608",
        "pnl": "0",
        "posBal": "0",
        "posBalChg": "0",
        "px": "27105.9",
        "subType": "1",
        "sz": "0.021955779",
        "tag": "",
        "to": "",
        "tradeId": "586760148",
        "ts": "1695033476167",
        "type": "2"
    }]
} 

Response Parameters

Parameter Type Description
instType String Instrument type
billId String Bill ID
type String Bill type
subType String Bill subtype
ts String The time when the balance complete update, Unix timestamp format in milliseconds, e.g.1597026383085
balChg String Change in balance amount at the account level
posBalChg String Change in balance amount at the position level
bal String Balance at the account level
posBal String Balance at the position level
sz String Quantity
px String Price which related to subType
  • Trade filled price for
  • 1: Buy 2: Sell
    ccy String Account balance currency
    pnl String Profit and loss
    fee String Fee
    Negative number represents the user transaction fee charged by the platform.
    Positive number represents rebate.
    mgnMode String Margin mode
    isolated cross
    When bills are not generated by position changes, the field returns ""
    instId String Instrument ID, e.g. BTC-USDT
    ordId String Order ID
    Return order ID when the type is 2\5\9
    Return "" when there is no order
    execType String Liquidity taker or maker, T: taker M: maker
    from String The remitting account
    6: Funding account
    18: Trading account
    Only applicable to transfer. When bill type is not transfer, the field returns "".
    to String The beneficiary account
    6: Funding account
    18: Trading account
    Only applicable to transfer. When bill type is not transfer, the field returns "".
    notes String Notes
    interest String Interest
    tag String Order tag
    fillTime String Last filled time
    tradeId String Last traded ID
    clOrdId String Client Order ID as assigned by the client
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    fillIdxPx String Index price at the moment of trade execution
    For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT.
    fillMarkPx String Mark price when filled
    Applicable to FUTURES/SWAP/OPTIONS, return "" for other instrument types
    fillPxVol String Implied volatility when filled
    Only applicable to options; return "" for other instrument types
    fillPxUsd String Options price when filled, in the unit of USD
    Only applicable to options; return "" for other instrument types
    fillMarkVol String Mark volatility when filled
    Only applicable to options; return "" for other instrument types
    fillFwdPx String Forward price when filled
    Only applicable to options; return "" for other instrument types

    Get bills details (last 3 months)

    Retrieve the account’s bills. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with most recent first. This endpoint can retrieve data from the last 3 months.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/bills-archive

    Request Example

    GET /api/v5/account/bills-archive
    
    GET /api/v5/account/bills-archive?instType=SPOT
    
    
    import okx.Account as Account
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading:0 , demo trading:1
    
    accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get bills details (last 3 months)
    result = accountAPI.get_account_bills_archive()
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String No Instrument type
    SPOT
    ccy String No Bill currency
    type String No Bill type
    1: Transfer
    2: Trade
    6: Margin transfer
    subType String No Bill subtype
    1: Buy
    2: Sell
    11: Transfer in
    12: Transfer out
    236: Easy convert in
    237: Easy convert out
    after String No Pagination of data to return records earlier than the requested bill ID.
    before String No Pagination of data to return records newer than the requested bill ID.
    begin String No Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
    end String No Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
    limit String No Number of results per request. The maximum is 100. The default is 100.

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "bal": "8694.2179403378290202",
            "balChg": "0.0219338232210000",
            "billId": "623950854533513219",
            "ccy": "USDT",
            "clOrdId": "",
            "execType": "T",
            "fee": "-0.000021955779",
            "fillFwdPx": "",
            "fillIdxPx": "27104.1",
            "fillMarkPx": "",
            "fillMarkVol": "",
            "fillPxUsd": "",
            "fillPxVol": "",
            "fillTime": "1695033476166",
            "from": "",
            "instId": "BTC-USDT",
            "instType": "SPOT",
            "interest": "0",
            "mgnMode": "isolated",
            "notes": "",
            "ordId": "623950854525124608",
            "pnl": "0",
            "posBal": "0",
            "posBalChg": "0",
            "px": "27105.9",
            "subType": "1",
            "sz": "0.021955779",
            "tag": "",
            "to": "",
            "tradeId": "586760148",
            "ts": "1695033476167",
            "type": "2"
        }]
    } 
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    billId String Bill ID
    type String Bill type
    subType String Bill subtype
    ts String The time when the balance complete update, Unix timestamp format in milliseconds, e.g.1597026383085
    balChg String Change in balance amount at the account level
    posBalChg String Change in balance amount at the position level
    bal String Balance at the account level
    posBal String Balance at the position level
    sz String Quantity
    px String Price which related to subType
  • Trade filled price for
  • 1: Buy 2: Sell
    ccy String Account balance currency
    pnl String Profit and loss
    fee String Fee
    Negative number represents the user transaction fee charged by the platform.
    Positive number represents rebate.
    mgnMode String Margin mode
    isolated cross
    When bills are not generated by position changes, the field returns ""
    instId String Instrument ID, e.g. BTC-USDT
    ordId String Order ID
    When bill type is not trade, the field returns ""
    execType String Liquidity taker or maker
    T: taker
    M: maker
    from String The remitting account
    6: Funding account
    18: Trading account
    Only applicable to transfer. When bill type is not transfer, the field returns "".
    to String The beneficiary account
    6: Funding account
    18: Trading account
    Only applicable to transfer. When bill type is not transfer, the field returns "".
    notes String Notes
    interest String Interest
    tag String Order tag
    fillTime String Last filled time
    tradeId String Last traded ID
    clOrdId String Client Order ID as assigned by the client
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    fillIdxPx String Index price at the moment of trade execution
    For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT.
    fillMarkPx String Mark price when filled
    Applicable to FUTURES/SWAP/OPTIONS, return "" for other instrument types
    fillPxVol String Implied volatility when filled
    Only applicable to options; return "" for other instrument types
    fillPxUsd String Options price when filled, in the unit of USD
    Only applicable to options; return "" for other instrument types
    fillMarkVol String Mark volatility when filled
    Only applicable to options; return "" for other instrument types
    fillFwdPx String Forward price when filled
    Only applicable to options; return "" for other instrument types

    Get account configuration

    Retrieve current account configuration.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/config

    Request Example

    GET /api/v5/account/config
    
    
    import okx.Account as Account
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading:0 , demo trading:1
    
    accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
    
    # Retrieve current account configuration
    result = accountAPI.get_account_config()
    print(result)
    

    Request Parameters

    none

    Response Example

    {
        "code": "0",
        "data": [
            {
                "acctLv": "3",
                "autoLoan": true,
                "ctIsoMode": "automatic",
                "greeksType": "PA",
                "level": "Lv1",
                "levelTmp": "",
                "mgnIsoMode": "automatic",
                "posMode": "net_mode",
                "spotOffsetType": "",
                "uid": "44705892343619584",
                "label": "V5 Test",
                "roleType": "0",
                "traderInsts": [],
                "spotRoleType": "0",
                "spotTraderInsts": [],
                "opAuth": "0",
                "kycLv": "3",
                "ip": "120.255.24.182,49.245.196.13",
                "perm": "read_only,withdraw,trade",
                "mainUid": "444810535339712570"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    uid String Account ID of current request.
    mainUid String Main Account ID of current request.
    The current request account is main account if uid = mainUid.
    The current request account is sub-account if uid != mainUid.
    acctLv String Account level
    1: Simple
    2: Single-currency margin
    3: Multi-currency margin
    4: Portfolio margin
    posMode String Position mode
    long_short_mode: long/short, only applicable to FUTURES/SWAP
    net_mode: net
    autoLoan Boolean Whether to borrow coins automatically
    true: borrow coins automatically
    false: not borrow coins automatically
    greeksType String Current display type of Greeks
    PA: Greeks in coins
    BS: Black-Scholes Greeks in dollars
    level String The user level of the current real trading volume on the platform, e.g lv1
    levelTmp String Temporary experience user level of special users, e.g lv3
    ctIsoMode String Contract isolated margin trading settings
    automatic: Auto transfers
    autonomy: Manual transfers
    mgnIsoMode String Margin isolated margin trading settings
    automatic: Auto transfers
    quick_margin: Quick Margin Mode (For new accounts, including subaccounts, some defaults will be automatic, and others will be quick_margin)
    spotOffsetType String Risk offset type
    1: Spot-Derivatives(USDT) to be offsetted
    2: Spot-Derivatives(Coin) to be offsetted
    3: Only derivatives to be offsetted
    Only applicable to Portfolio margin
    roleType String Role type
    0: General user
    1: Leading trader
    2: Copy trader
    traderInsts Array Leading trade instruments, only applicable to Leading trader
    spotRoleType String SPOT copy trading role type.
    0: General user;1: Leading trader;2: Copy trader
    spotTraderInsts String Spot lead trading instruments, only applicable to lead trader
    opAuth String Whether the optional trading was activated
    0: not activate
    1: activated
    kycLv String Main account KYC level
    0: No verification
    1: level 1 completed
    2: level 2 completed
    3: level 3 completed
    If the request originates from a subaccount, kycLv is the KYC level of the main account.
    If the request originates from the main account, kycLv is the KYC level of the current account.
    label String API key note of current request API key. No more than 50 letters (case sensitive) or numbers, which can be pure letters or pure numbers.
    ip String IP addresses that linked with current API key, separate with commas if more than one, e.g. 117.37.203.58,117.37.203.57. It is an empty string "" if there is no IP bonded.
    perm String The permission of the current requesting API Key
    read_only: Read
    trade: Trade
    withdraw: Withdraw

    Get maximum buy/sell amount or open amount

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/max-size

    Request Example

    GET /api/v5/account/max-size?instId=BTC-USDT&tdMode=cash
    
    
    import okx.Account as Account
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading:0 , demo trading:1
    
    accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get maximum buy/sell amount or open amount
    result = accountAPI.get_max_order_size(
        instId="BTC-USDT",
        tdMode="cash"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Single instrument or multiple instruments (no more than 5) separated with comma, e.g. BTC-USDT,ETH-USDT
    tdMode String Yes Trade mode
    cash
    px String No Price
    The parameter will be ignored when multiple instruments are specified.

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "ccy": "BTC",
            "instId": "BTC-USDT",
            "maxBuy": "0.0500695098559788",
            "maxSell": "64.4798671570072269"
      }]
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    ccy String Currency used for margin
    maxBuy String SPOT: The maximum quantity in base currency that you can buy
    maxSell String SPOT: The maximum quantity in quote currency that you can sell

    Get maximum available tradable amount

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/max-avail-size

    Request Example

    # Query maximum available transaction amount for SPOT BTC-USDT
    GET /api/v5/account/max-avail-size?instId=BTC-USDT&tdMode=cash
    
    
    import okx.Account as Account
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading:0 , demo trading:1
    
    accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get maximum available transaction amount for SPOT BTC-USDT
    result = accountAPI.get_max_avail_size(
        instId="BTC-USDT",
        tdMode="cash"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Single instrument or multiple instruments (no more than 5) separated with comma, e.g. BTC-USDT,ETH-USDT
    tdMode String Yes Trade mode
    cash

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
          "instId": "BTC-USDT",
          "availBuy": "100",
          "availSell": "1"
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    availBuy String Amount available to buy
    availSell String Amount available to sell

    Get fee rates

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/trade-fee

    Request Example

    # Query trade fee rate of SPOT BTC-USDT
    GET /api/v5/account/trade-fee?instType=SPOT&instId=BTC-USDT
    
    import okx.Account as Account
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading:0 , demo trading:1
    
    accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get trading fee rates of current account
    result = accountAPI.get_fee_rates(
        instType="SPOT",
        instId="BTC-USDT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String Yes Instrument type
    SPOT
    instId String No Instrument ID, e.g. BTC-USDT
    Applicable to SPOT

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [{
        "category": "1", //Deprecated
        "delivery": "",
        "exercise": "",
        "instType": "SPOT",
        "level": "lv1",
        "maker": "-0.0008",
        "makerU": "",
        "makerUSDC": "",
        "taker": "-0.001",
        "takerU": "",
        "takerUSDC": "",
        "ts": "1608623351857",
        "fiat": []
       }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    level String Fee rate Level
    taker String For SPOT, it is taker fee rate of the USDT trading pairs.
    maker String For SPOT, it is maker fee rate of the USDT trading pairs.
    takerU String Taker fee rate of USDT-margined contracts, only applicable to FUTURES/SWAP
    makerU String Maker fee rate of USDT-margined contracts, only applicable to FUTURES/SWAP
    delivery String Delivery fee rate
    exercise String Fee rate for exercising the option
    instType String Instrument type
    takerUSDC String For SPOT, it is taker fee rate of the USDⓈ&Crypto trading pairs.
    makerUSDC String For SPOT, it is maker fee rate of the USDⓈ&Crypto trading pairs.
    ts String Data return time, Unix timestamp format in milliseconds, e.g. 1597026383085
    category String Currency category. Note: this parameter is already deprecated
    fiat Array Details of fiat fee rate
    > ccy String Fiat currency.
    > taker String Taker fee rate
    > maker String Maker fee rate

    WebSocket

    Account channel

    Retrieve account information. Data will be pushed when triggered by events such as placing order, canceling order, transaction execution, etc. It will also be pushed in regular interval according to subscription granularity.

    The exchange will implement concurrent connection limit in February. Please refer to Restrict number of connections per private WebSocket channel

    Request Example : single

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "account",
          "ccy": "BTC"
        }
      ]
    }
    

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "account",
          "extraParams": "
            {
              \"updateInterval\": \"0\"
            }
          "
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    account
    > ccy String No Currency
    > extraParams String No Additional configuration
    >> updateInterval int No 0: only push due to account events
    The data will be pushed both by events and regularly if this field is omitted or set to other values than 0.
    The following format should be strictly obeyed when using this field.
    "extraParams": "
    {
    \"updateInterval\": \"0\"
    }
    "

    Successful Response Example : single

    {
      "event": "subscribe",
      "arg": {
        "channel": "account",
        "ccy": "BTC"
      },
      "connId": "a4d3ae55"
    }
    

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "account"
      },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"account\", \"ccy\" : \"BTC\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Operation
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    account
    > ccy String No Currency
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
        "arg": {
            "channel": "account",
            "uid": "44*********584"
        },
        "data": [{
            "adjEq": "55444.12216906034",
            "borrowFroz": "0",
            "details": [{
                "availBal": "4734.371190691436",
                "availEq": "4734.371190691435",
                "borrowFroz": "0",
                "cashBal": "4750.426970691436",
                "ccy": "USDT",
                "coinUsdPrice": "0.99927",
                "crossLiab": "0",
                "disEq": "4889.379316336831",
                "eq": "4892.951170691435",
                "eqUsd": "4889.379316336831",
                "fixedBal": "0",
                "frozenBal": "158.57998",
                "imr": "",
                "interest": "0",
                "isoEq": "0",
                "isoLiab": "0",
                "isoUpl": "0",
                "liab": "0",
                "maxLoan": "0",
                "mgnRatio": "",
                "mmr": "",
                "notionalLever": "",
                "ordFrozen": "0",
                "spotInUseAmt": "",
                "spotIsoBal": "0",
                "stgyEq": "150",
                "twap": "0",
                "uTime": "1705564213903",
                "upl": "-7.475800000000003",
                "uplLiab": "0"
            }],
            "imr": "8.5737166146",
            "isoEq": "0",
            "mgnRatio": "143705.65988369548",
            "mmr": "0.342948664584",
            "notionalUsd": "85.737166146",
            "ordFroz": "0",
            "totalEq": "55868.06403501676",
            "uTime": "1705564223311",
            "upl": "-7.470342666000003"
        }]
    }
    

    Push data parameters

    Parameters Types Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > uid String User Identifier
    data Array Subscribed data
    > uTime String The latest time to get account information, millisecond format of Unix timestamp, e.g. 1597026383085
    > totalEq String The total amount of equity in USD
    > isoEq String Isolated margin equity in USD
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    > adjEq String Adjusted / Effective equity in USD
    The net fiat value of the assets in the account that can provide margins for spot, expiry futures, perpetual futures and options under the cross-margin mode.
    In multi-ccy or PM mode, the asset and margin requirement will all be converted to USD value to process the order check or liquidation.
    Due to the volatility of each currency market, our platform calculates the actual USD value of each currency based on discount rates to balance market risks.
    Applicable to Multi-currency margin/Portfolio margin
    > ordFroz String Margin frozen for pending cross orders in USD
    Only applicable to Multi-currency margin
    > imr String Initial margin requirement in USD
    The sum of initial margins of all open positions and pending orders under cross-margin mode in USD.
    Applicable to Multi-currency margin/Portfolio margin
    > mmr String Maintenance margin requirement in USD
    The sum of maintenance margins of all open positions and pending orders under cross-margin mode in USD.
    Applicable to Multi-currency margin/Portfolio margin
    > borrowFroz String Potential borrowing IMR of the account in USD
    Only applicable to Multi-currency margin/Portfolio margin. It is "" for other margin modes.
    > mgnRatio String Margin ratio in USD.
    Applicable to Multi-currency margin/Portfolio margin
    > notionalUsd String Notional value of positions in USD
    Applicable to Multi-currency margin/Portfolio margin
    > upl String Cross-margin info of unrealized profit and loss at the account level in USD
    Applicable to Multi-currency margin/Portfolio margin
    > details Array Detailed asset information in all currencies
    >> ccy String Currency
    >> eq String Equity of currency
    >> cashBal String Cash Balance
    >> uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    >> isoEq String Isolated margin equity of currency
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    >> availEq String Available equity of currency
    The balance that can be used on margin or futures/swap trading.
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    >> disEq String Discount equity of currency in USD
    >> fixedBal String Frozen balance for Dip Sniper and Peak Sniper
    >> availBal String Available balance of currency
    The balance that can be withdrawn or transferred or used on spot trading.
    >> frozenBal String Frozen balance of currency
    >> ordFrozen String Margin frozen for open orders
    Applicable to Simple/Single-currency margin/Multi-currency margin
    >> liab String Liabilities of currency
    It is a positive value, e.g. 21625.64.
    Applicable to Multi-currency margin/Portfolio margin
    >> upl String The sum of the unrealized profit & loss of all margin and derivatives positions of currency.
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    >> uplLiab String Liabilities due to Unrealized loss of currency
    Applicable to Multi-currency margin/Portfolio margin
    >> crossLiab String Cross Liabilities of currency
    Applicable to Multi-currency margin/Portfolio margin
    >> isoLiab String Isolated Liabilities of currency
    Applicable to Multi-currency margin/Portfolio margin
    >> mgnRatio String Margin ratio of currency
    The index for measuring the risk of a certain asset in the account.
    Applicable to Single-currency margin
    >> interest String Interest of currency
    It is a positive value, e.g."9.01". Applicable to Multi-currency margin/Portfolio margin
    >> twap String System is forced repayment(TWAP) indicator
    Divided into multiple levels from 0 to 5, the larger the number, the more likely the auto repayment will be triggered.
    Applicable to Multi-currency margin/Portfolio margin
    >> maxLoan String Max loan of currency
    Applicable to cross of Multi-currency margin/Portfolio margin
    >> eqUsd String Equity usd of currency
    >> borrowFroz String Potential borrowing IMR of currency in USD
    Only applicable to Multi-currency margin/Portfolio margin. It is "" for other margin modes.
    >> notionalLever String Leverage of currency
    Applicable to Single-currency margin
    >> coinUsdPrice String Price index usd of currency
    >> stgyEq String strategy equity
    >> isoUpl String Isolated unrealized profit and loss of currency
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    >> spotInUseAmt String Spot in use amount
    Applicable to Portfolio margin
    >> imr String Initial margin requirement at the currency level
    Applicable to Single-currency margin
    >> mmr String Maintenance margin requirement at the currency level
    Applicable to Single-currency margin

    Order Book Trading

    Trade

    All Trade API endpoints require authentication.

    POST / Place order

    You can place an order only if you have sufficient funds.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule : UserID + Instrument ID

    HTTP Request

    POST /api/v5/trade/order

    Request Example

     place order for SPOT
     POST /api/v5/trade/order
     body
     {
        "instId":"BTC-USDT",
        "tdMode":"cash",
        "clOrdId":"b15",
        "side":"buy",
        "ordType":"limit",
        "px":"2.15",
        "sz":"2"
    }
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Simple mode, limit order
    result = tradeAPI.place_order(
        instId="BTC-USDT",
        tdMode="cash",
        clOrdId="b15",
        side="buy",
        ordType="limit",
        px="2.15",
        sz="2"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    tdMode String Yes Trade mode
    cash
    clOrdId String No Client Order ID as assigned by the client
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    tag String No Order tag
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
    side String Yes Order side
    buy
    sell
    ordType String Yes Order type
    market: Market order
    limit: Limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    sz String Yes Quantity to buy or sell
    px String Conditional Order price. Only applicable to limit,post_only,fok,iocorder.
    tgtCcy String No Whether the target currency uses the quote or base currency.
    base_ccy: Base currency
    quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    banAmend Boolean No Whether to disallow the system from amending the size of the SPOT Market Order.
    Valid options: true or false. The default value is false.
    If true, system will not amend and reject the market order if user does not have sufficient funds.
    Only applicable to SPOT Market Orders
    stpId String No Self trade prevention ID. Orders from the same master account with the same ID will be prevented from self trade.
    Numerical integers defined by user in the range of 1<= x<= 999999999
    stpMode String No Self trade prevention mode. It is available only when stpId is filled.
    Default to cancel maker
    cancel_maker,cancel_taker, cancel_both
    Cancel both does not support FOK.
    attachAlgoOrds Array of object No TP/SL information attached when placing order
    > attachAlgoClOrdId String No Client-supplied Algo ID when placing order attaching TP/SL
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > tpTriggerPx String Conditional Take-profit trigger price
    If you fill in this parameter, you should fill in the take-profit order price as well.
    > tpOrdPx String Conditional Take-profit order price
    If you fill in this parameter, you should fill in the take-profit trigger price as well.
    If the price is -1, take-profit will be executed at the market price.
    > slTriggerPx String Conditional Stop-loss trigger price
    If you fill in this parameter, you should fill in the stop-loss order price.
    > slOrdPx String Conditional Stop-loss order price
    If you fill in this parameter, you should fill in the stop-loss trigger price.
    If the price is -1, stop-loss will be executed at the market price.
    > tpTriggerPxType String No Take-profit trigger price type
    last: last price
    The default is last
    > slTriggerPxType String No Stop-loss trigger price type
    last: last price
    The default is last
    > sz String Conditional Size. Only applicable to TP order of split TPs, and it is required for TP order of split TPs
    > amendPxOnTriggerType String No Whether to enable Cost-price SL. Only applicable to SL order of split TPs. Whether slTriggerPx will move to avgPx when the first TP order is triggered
    0: disable, the default value
    1: Enable

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
          "clOrdId": "oktswap6",
          "ordId": "312269865356374016",
          "tag": "",
          "sCode": "0",
          "sMsg": ""
        }
      ],
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    code String The result code, 0 means success
    msg String The error message, empty if the code is 0
    data Array of objects Array of objects contains the response results
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > tag String Order tag
    > sCode String The code of the event execution result, 0 means success.
    > sMsg String Rejection or success message of event execution.
    inTime String Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    The time is recorded after authentication.
    outTime String Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    POST / Place multiple orders

    Place orders in batches. Maximum 20 orders can be placed per request.
    Request parameters should be passed in the form of an array. Orders will be placed in turn

    Rate Limit: 300 orders per 2 seconds

    Rate limit rule: UserID + Instrument ID

    HTTP Request

    POST /api/v5/trade/batch-orders

    Request Example

    # batch place order for SPOT
    POST /api/v5/trade/batch-orders
    body
    [
        {
            "instId":"BTC-USDT",
            "tdMode":"cash",
            "clOrdId":"b15",
            "side":"buy",
            "ordType":"limit",
            "px":"2.15",
            "sz":"2"
        },
        {
            "instId":"BTC-USDT",
            "tdMode":"cash",
            "clOrdId":"b16",
            "side":"buy",
            "ordType":"limit",
            "px":"2.15",
            "sz":"2"
        }
    ]
    
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Place multiple orders 
    place_orders_without_clOrdId = [
        {"instId": "BTC-USDT", "tdMode": "cash", "clOrdId": "b15", "side": "buy", "ordType": "limit", "px": "2.15", "sz": "2"},
        {"instId": "BTC-USDT", "tdMode": "cash", "clOrdId": "b16", "side": "buy", "ordType": "limit", "px": "2.15", "sz": "2"}
    ]
    
    result = tradeAPI.place_multiple_orders(place_orders_without_clOrdId)
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    tdMode String Yes Trade mode
    cash
    clOrdId String No Client Order ID as assigned by the client
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    tag String No Order tag
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
    side String Yes Order side
    buy
    sell
    ordType String Yes Order type
    market: Market order
    limit: Limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    sz String Yes Quantity to buy or sell
    px String Conditional Order price. Only applicable to limit,post_only,fok,iocorder.
    tgtCcy String No Whether the target currency uses the quote or base currency.
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    banAmend Boolean No Whether to disallow the system from amending the size of the SPOT Market Order.
    Valid options: true or false. The default value is false.
    If true, system will not amend and reject the market order if user does not have sufficient funds.
    Only applicable to SPOT Market Orders
    stpId String No Self trade prevention ID. Orders from the same master account with the same ID will be prevented from self trade.
    Numerical integers defined by user in the range of 1<= x<= 999999999
    stpMode String No Self trade prevention mode. It is available only when stpId is filled.
    Default to cancel maker
    cancel_maker,cancel_taker, cancel_both
    Cancel both does not support FOK.
    attachAlgoOrds Array of object No TP/SL information attached when placing order
    > attachAlgoClOrdId String No Client-supplied Algo ID when placing order attaching TP/SL
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > tpTriggerPx String Conditional Take-profit trigger price
    If you fill in this parameter, you should fill in the take-profit order price as well.
    > tpOrdPx String Conditional Take-profit order price
    If you fill in this parameter, you should fill in the take-profit trigger price as well.
    If the price is -1, take-profit will be executed at the market price.
    > slTriggerPx String Conditional Stop-loss trigger price
    If you fill in this parameter, you should fill in the stop-loss order price.
    > slOrdPx String Conditional Stop-loss order price
    If you fill in this parameter, you should fill in the stop-loss trigger price.
    If the price is -1, stop-loss will be executed at the market price.
    > tpTriggerPxType String No Take-profit trigger price type
    last: last price
    The default is last
    > slTriggerPxType String No Stop-loss trigger price type
    last: last price
    The default is last
    > sz String Conditional Size. Only applicable to TP order of split TPs, and it is required for TP order of split TPs
    > amendPxOnTriggerType String No Whether to enable Cost-price SL. Only applicable to SL order of split TPs. Whether slTriggerPx will move to avgPx when the first TP order is triggered
    0: disable, the default value
    1: Enable

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "clOrdId":"oktswap6",
                "ordId":"12345689",
                "tag":"",
                "sCode":"0",
                "sMsg":""
            },
            {
                "clOrdId":"oktswap7",
                "ordId":"12344",
                "tag":"",
                "sCode":"0",
                "sMsg":""
            }
        ],
        "inTime": "1695190491421339",
        "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    code String The result code, 0 means success
    msg String The error message, empty if the code is 0
    data Array of objects Array of objects contains the response results
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > tag String Order tag
    > sCode String The code of the event execution result, 0 means success.
    > sMsg String Rejection or success message of event execution.
    inTime String Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    The time is recorded after authentication.
    outTime String Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    POST / Cancel order

    Cancel an incomplete order.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule: UserID + Instrument ID

    HTTP Request

    POST /api/v5/trade/cancel-order

    Request Example

    POST /api/v5/trade/cancel-order
    body
    {
        "ordId":"590908157585625111",
        "instId":"BTC-USDT"
    }
    
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Cancel order
    result = tradeAPI.cancel_order(instId="BTC-USDT", ordId = "590908157585625111")
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    ordId String Conditional Order ID
    Either ordId or clOrdId is required. If both are passed, ordId will be used.
    clOrdId String Conditional Client Order ID as assigned by the client

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "clOrdId":"oktswap6",
                "ordId":"12345689",
                "sCode":"0",
                "sMsg":""
            }
        ],
        "inTime": "1695190491421339",
        "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    code String The result code, 0 means success
    msg String The error message, empty if the code is 0
    data Array of objects Array of objects contains the response results
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > sCode String The code of the event execution result, 0 means success.
    > sMsg String Rejection message if the request is unsuccessful.
    inTime String Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    The time is recorded after authentication.
    outTime String Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    POST / Cancel multiple orders

    Cancel incomplete orders in batches. Maximum 20 orders can be canceled per request. Request parameters should be passed in the form of an array.

    Rate Limit: 300 orders per 2 seconds

    Rate limit rule: UserID + Instrument ID

    HTTP Request

    POST /api/v5/trade/cancel-batch-orders

    Request Example

    POST /api/v5/trade/cancel-batch-orders
    body
    [
        {
            "instId":"BTC-USDT",
            "ordId":"590908157585625111"
        },
        {
            "instId":"BTC-USDT",
            "ordId":"590908544950571222"
        }
    ]
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Cancel multiple orders by ordId
    cancel_orders_with_orderId = [
        {"instId": "BTC-USDT", "ordId": "590908157585625111"},
        {"instId": "BTC-USDT", "ordId": "590908544950571222"},
    ]
    
    result = tradeAPI.cancel_multiple_orders(cancel_orders_with_orderId)
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    ordId String Conditional Order ID
    Either ordId or clOrdId is required. If both are passed, ordId will be used.
    clOrdId String Conditional Client Order ID as assigned by the client

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "clOrdId":"oktswap6",
                "ordId":"12345689",
                "sCode":"0",
                "sMsg":""
            },
            {
                "clOrdId":"oktswap7",
                "ordId":"12344",
                "sCode":"0",
                "sMsg":""
            }
        ],
        "inTime": "1695190491421339",
        "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    code String The result code, 0 means success
    msg String The error message, empty if the code is 0
    data Array of objects Array of objects contains the response results
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > sCode String The code of the event execution result, 0 means success.
    > sMsg String Rejection message if the request is unsuccessful.
    inTime String Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    The time is recorded after authentication.
    outTime String Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    POST / Amend order

    Amend an incomplete order.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule: UserID + Instrument ID

    HTTP Request

    POST /api/v5/trade/amend-order

    Request Example

    POST /api/v5/trade/amend-order
    body
    {
        "ordId":"590909145319051111",
        "newSz":"2",
        "instId":"BTC-USDT"
    }
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Amend order
    result = tradeAPI.amend_order(
        instId="BTC-USDT",
        ordId="590909145319051111",
        newSz="2"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID
    cxlOnFail Boolean No Whether the order needs to be automatically canceled when the order amendment fails
    Valid options: false or true, the default is false.
    ordId String Conditional Order ID
    Either ordId or clOrdId is required. If both are passed, ordId will be used.
    clOrdId String Conditional Client Order ID as assigned by the client
    reqId String No Client Request ID as assigned by the client for order amendment
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    The response will include the corresponding reqId to help you identify the request if you provide it in the request.
    newSz String Conditional New quantity after amendment. When amending a partially-filled order, the newSz should include the amount that has been filled.
    newPx String Conditional New price after amendment.
    attachAlgoOrds Array of object No TP/SL information attached when placing order
    > attachAlgoId String Conditional The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely.
    > attachAlgoClOrdId String Conditional Client-supplied Algo ID when placing order attaching TP/SL
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > newTpTriggerPx String Conditional Take-profit trigger price.
    Either the take profit trigger price or order price is 0, it means that the take profit is deleted.
    Only applicable to Expiry Futures and Perpetual Futures.
    > newTpOrdPx String Conditional Take-profit order price
    If the price is -1, take-profit will be executed at the market price.
    Only applicable to Expiry Futures and Perpetual Futures.
    > newSlTriggerPx String Conditional Stop-loss trigger price
    Either the stop loss trigger price or order price is 0, it means that the stop loss is deleted.
    Only applicable to Expiry Futures and Perpetual Futures.
    > newSlOrdPx String Conditional Stop-loss order price
    If the price is -1, stop-loss will be executed at the market price.
    Only applicable to Expiry Futures and Perpetual Futures.
    > newTpTriggerPxType String Conditional Take-profit trigger price type
    last: last price
    index: index price
    mark: mark price
    Only applicable to FUTURES/SWAP
    If you want to add the take-profit, this parameter is required
    > newSlTriggerPxType String Conditional Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark price
    Only applicable to FUTURES/SWAP
    If you want to add the stop-loss, this parameter is required
    > sz String Conditional New size. Only applicable to TP order of split TPs, and it is required for TP order of split TPs
    > amendPxOnTriggerType String No Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
             "clOrdId":"",
             "ordId":"12344",
             "reqId":"b12344",
             "sCode":"0",
             "sMsg":""
            }
        ],
        "inTime": "1695190491421339",
        "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    code String The result code, 0 means success
    msg String The error message, empty if the code is 0
    data Array of objects Array of objects contains the response results
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > reqId String Client Request ID as assigned by the client for order amendment.
    > sCode String The code of the event execution result, 0 means success.
    > sMsg String Rejection message if the request is unsuccessful.
    inTime String Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    The time is recorded after authentication.
    outTime String Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    POST / Amend multiple orders

    Amend incomplete orders in batches. Maximum 20 orders can be amended per request. Request parameters should be passed in the form of an array.

    Rate Limit: 300 orders per 2 seconds

    Rate limit rule: UserID + Instrument ID

    The exchange will implement sub-account rate limit in early March. Please refer to Sub-account rate limit and Fill ratio based sub-account rate limit

    HTTP Request

    POST /api/v5/trade/amend-batch-orders

    Request Example

    POST /api/v5/trade/amend-batch-orders
    body
    [
        {
            "ordId":"590909308792049444",
            "newSz":"2",
            "instId":"BTC-USDT"
        },
        {
            "ordId":"590909308792049555",
            "newSz":"2",
            "instId":"BTC-USDT"
        }
    ]
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Amend incomplete orders in batches by ordId
    amend_orders_with_orderId = [
        {"instId": "BTC-USDT", "ordId": "590909308792049444","newSz":"2"},
        {"instId": "BTC-USDT", "ordId": "590909308792049555","newSz":"2"},
    ]
    
    result = tradeAPI.amend_multiple_orders(amend_orders_with_orderId)
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID
    cxlOnFail Boolean No Whether the order needs to be automatically canceled when the order amendment fails
    false true, the default is false.
    ordId String Conditional Order ID
    Either ordId or clOrdIdis required, if both are passed, ordId will be used.
    clOrdId String Conditional Client Order ID as assigned by the client
    reqId String No Client Request ID as assigned by the client for order amendment
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    The response will include the corresponding reqId to help you identify the request if you provide it in the request.
    newSz String Conditional New quantity after amendment. When amending a partially-filled order, the newSz should include the amount that has been filled.
    newPx String Conditional New price after amendment.
    attachAlgoOrds Array of object No TP/SL information attached when placing order
    > attachAlgoId String Conditional The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely.
    > attachAlgoClOrdId String Conditional Client-supplied Algo ID when placing order attaching TP/SL
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > newTpTriggerPx String Conditional Take-profit trigger price.
    Either the take profit trigger price or order price is 0, it means that the take profit is deleted.
    Only applicable to Expiry Futures and Perpetual Futures.
    > newTpOrdPx String Conditional Take-profit order price
    If the price is -1, take-profit will be executed at the market price.
    Only applicable to Expiry Futures and Perpetual Futures.
    > newSlTriggerPx String Conditional Stop-loss trigger price
    Either the stop loss trigger price or order price is 0, it means that the stop loss is deleted.
    Only applicable to Expiry Futures and Perpetual Futures.
    > newSlOrdPx String Conditional Stop-loss order price
    If the price is -1, stop-loss will be executed at the market price.
    Only applicable to Expiry Futures and Perpetual Futures.
    > newTpTriggerPxType String Conditional Take-profit trigger price type
    last: last price
    index: index price
    mark: mark price
    Only applicable to FUTURES/SWAP
    If you want to add the take-profit, this parameter is required
    > newSlTriggerPxType String Conditional Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark price
    Only applicable to FUTURES/SWAP
    If you want to add the stop-loss, this parameter is required
    > sz String Conditional New size. Only applicable to TP order of split TPs, and it is required for TP order of split TPs
    > amendPxOnTriggerType String No Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "clOrdId":"oktswap6",
                "ordId":"12345689",
                "reqId":"b12344",
                "sCode":"0",
                "sMsg":""
            },
            {
                "clOrdId":"oktswap7",
                "ordId":"12344",
                "reqId":"b12344",
                "sCode":"0",
                "sMsg":""
            }
        ],
        "inTime": "1695190491421339",
        "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    code String The result code, 0 means success
    msg String The error message, empty if the code is 0
    data Array of objects Array of objects contains the response results
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > reqId String Client Request ID as assigned by the client for order amendment.
    > sCode String The code of the event execution result, 0 means success.
    > sMsg String Rejection message if the request is unsuccessful.
    inTime String Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    The time is recorded after authentication.
    outTime String Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    GET / Order details

    Retrieve order details.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule: UserID + Instrument ID

    HTTP Request

    GET /api/v5/trade/order

    Request Example

    GET /api/v5/trade/order?ordId=680800019749904384&instId=BTC-USDT
    
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Retrieve order details by ordId
    result = tradeAPI.get_order(
        instId="BTC-USDT",
        ordId="680800019749904384"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    Only applicable to live instruments
    ordId String Conditional Order ID
    Either ordId or clOrdId is required, if both are passed, ordId will be used
    clOrdId String Conditional Client Order ID as assigned by the client
    If the clOrdId is associated with multiple orders, only the latest one will be returned.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "accFillSz": "0.00192834",
                "algoClOrdId": "",
                "algoId": "",
                "attachAlgoClOrdId": "",
                "attachAlgoOrds": [],
                "avgPx": "51858",
                "cTime": "1708587373361",
                "cancelSource": "",
                "cancelSourceReason": "",
                "category": "normal",
                "ccy": "",
                "clOrdId": "",
                "fee": "-0.00000192834",
                "feeCcy": "BTC",
                "fillPx": "51858",
                "fillSz": "0.00192834",
                "fillTime": "1708587373361",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "isTpLimit": "false",
                "lever": "",
                "linkedAlgoOrd": {
                    "algoId": ""
                },
                "ordId": "680800019749904384",
                "ordType": "market",
                "pnl": "0",
                "posSide": "net",
                "px": "",
                "pxType": "",
                "pxUsd": "",
                "pxVol": "",
                "quickMgnType": "",
                "rebate": "0",
                "rebateCcy": "USDT",
                "reduceOnly": "false",
                "side": "buy",
                "slOrdPx": "",
                "slTriggerPx": "",
                "slTriggerPxType": "",
                "source": "",
                "state": "filled",
                "stpId": "",
                "stpMode": "",
                "sz": "100",
                "tag": "",
                "tdMode": "cash",
                "tgtCcy": "quote_ccy",
                "tpOrdPx": "",
                "tpTriggerPx": "",
                "tpTriggerPxType": "",
                "tradeId": "744876980",
                "uTime": "1708587373362"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    SPOT
    instId String Instrument ID
    tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    ccy String Margin currency
    Only applicable to cross MARGIN orders in Single-currency margin.
    ordId String Order ID
    clOrdId String Client Order ID as assigned by the client
    tag String Order tag
    px String Price
    For options, use coin as unit (e.g. BTC, ETH)
    pxUsd String Options price in USDOnly applicable to options; return "" for other instrument types
    pxVol String Implied volatility of the options orderOnly applicable to options; return "" for other instrument types
    pxType String Price type of options
    px: Place an order based on price, in the unit of coin (the unit for the request parameter px is BTC or ETH)
    pxVol: Place an order based on pxVol
    pxUsd: Place an order based on pxUsd, in the unit of USD (the unit for the request parameter px is USD)
    sz String Quantity to buy or sell
    pnl String Profit and loss, Applicable to orders which have a trade and aim to close position. It always is 0 in other conditions
    ordType String Order type
    market: Market order
    limit: Limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    optimal_limit_ioc: Market order with immediate-or-cancel order
    mmp: Market Maker Protection (only applicable to Option in Portfolio Margin mode)
    mmp_and_post_only: Market Maker Protection and Post-only order(only applicable to Option in Portfolio Margin mode)
    op_fok: Simple options (fok)
    side String Order side
    posSide String Position side
    tdMode String Trade mode
    accFillSz String Accumulated fill quantity
    The unit is base_ccy for SPOT and MARGIN, e.g. BTC-USDT, the unit is BTC; For market orders, the unit both is base_ccy when the tgtCcy is base_ccy or quote_ccy;
    The unit is contract for FUTURES/SWAP/OPTION
    fillPx String Last filled price. If none is filled, it will return "".
    tradeId String Last traded ID
    fillSz String Last filled quantity
    The unit is base_ccy for SPOT and MARGIN, e.g. BTC-USDT, the unit is BTC; For market orders, the unit both is base_ccy when the tgtCcy is base_ccy or quote_ccy;
    The unit is contract for FUTURES/SWAP/OPTION
    fillTime String Last filled time
    avgPx String Average filled price. If none is filled, it will return "".
    state String State
    canceled
    live
    partially_filled
    filled
    mmp_canceled
    stpId String Self trade prevention ID
    Return "" if self trade prevention is not applicable
    stpMode String Self trade prevention mode
    Return "" if self trade prevention is not applicable
    lever String Leverage, from 0.01 to 125.
    Only applicable to MARGIN/FUTURES/SWAP
    attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL.
    tpTriggerPx String Take-profit trigger price.
    tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    tpOrdPx String Take-profit order price.
    slTriggerPx String Stop-loss trigger price.
    slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    slOrdPx String Stop-loss order price.
    attachAlgoOrds Array of object TP/SL information attached when placing order
    > attachAlgoId String The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely.
    > attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > tpTriggerPx String Take-profit trigger price.
    > tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    > tpOrdPx String Take-profit order price.
    > slTriggerPx String Stop-loss trigger price.
    > slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    > slOrdPx String Stop-loss order price.
    > sz String Size. Only applicable to TP order of split TPs
    > amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    feeCcy String Fee currency
    fee String Fee and rebate
    For spot and margin, it is accumulated fee charged by the platform. It is always negative, e.g. -0.01.
    For Expiry Futures, Perpetual Futures and Options, it is accumulated fee and rebate
    rebateCcy String Rebate currency
    source String Order source
    6: The normal order triggered by the trigger order
    7:The normal order triggered by the TP/SL order
    13: The normal order triggered by the algo order
    24:The normal order triggered by the trailing stop order
    rebate String Rebate amount, only applicable to spot and margin, the reward of placing orders from the platform (rebate) given to user who has reached the specified trading level. If there is no rebate, this field is "".
    category String Category
    normal
    twap
    adl
    full_liquidation
    partial_liquidation
    delivery
    ddh: Delta dynamic hedge
    reduceOnly String Whether the order can only reduce the position size. Valid options: true or false.
    cancelSource String Code of the cancellation source.
    cancelSourceReason String Reason for the cancellation.
    quickMgnType String Quick Margin type, Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    algoClOrdId String Client-supplied Algo ID. There will be a value when algo order attaching algoClOrdId is triggered, or it will be "".
    algoId String Algo ID. There will be a value when algo order is triggered, or it will be "".
    uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    GET / Order List

    Retrieve all incomplete orders under the current account.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/orders-pending

    Request Example

    GET /api/v5/trade/orders-pending?ordType=post_only,fok,ioc&instType=SPOT
    
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Retrieve all incomplete orders
    result = tradeAPI.get_order_list(
        instType="SPOT",
        ordType="post_only,fok,ioc"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String No Instrument type
    SPOT
    instId String No Instrument ID, e.g. BTC-USDT
    ordType String No Order type
    market: Market order
    limit: Limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    state String No State
    live
    partially_filled
    after String No Pagination of data to return records earlier than the requested ordId
    before String No Pagination of data to return records newer than the requested ordId
    limit String No Number of results per request. The maximum is 100. The default is 100

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [
            {
                "accFillSz": "0",
                "avgPx": "",
                "cTime": "1618235248028",
                "category": "normal",
                "ccy": "",
                "clOrdId": "",
                "fee": "0",
                "feeCcy": "BTC",
                "fillPx": "",
                "fillSz": "0",
                "fillTime": "",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "lever": "5.6",
                "ordId": "301835739059335168",
                "ordType": "limit",
                "pnl": "0",
                "posSide": "net",
                "px": "59200",
                "pxUsd":"",
                "pxVol":"",
                "pxType":"",
                "rebate": "0",
                "rebateCcy": "USDT",
                "side": "buy",
                "attachAlgoClOrdId": "",
                "slOrdPx": "",
                "slTriggerPx": "",
                "slTriggerPxType": "last",
                "attachAlgoOrds": [],
                "state": "live",
                "stpId": "",
                "stpMode": "",
                "sz": "1",
                "tag": "",
                "tgtCcy": "",
                "tdMode": "cross",
                "source":"",
                "tpOrdPx": "",
                "tpTriggerPx": "",
                "tpTriggerPxType": "last",
                "tradeId": "",
                "reduceOnly": "false",
                "quickMgnType": "",
                "algoClOrdId": "",
                "algoId": "",
                "uTime": "1618235248028"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    ccy String Margin currency
    Only applicable to cross MARGIN orders in Single-currency margin.
    ordId String Order ID
    clOrdId String Client Order ID as assigned by the client
    tag String Order tag
    px String Price
    For options, use coin as unit (e.g. BTC, ETH)
    pxUsd String Options price in USDOnly applicable to options; return "" for other instrument types
    pxVol String Implied volatility of the options orderOnly applicable to options; return "" for other instrument types
    pxType String Price type of options
    px: Place an order based on price, in the unit of coin (the unit for the request parameter px is BTC or ETH)
    pxVol: Place an order based on pxVol
    pxUsd: Place an order based on pxUsd, in the unit of USD (the unit for the request parameter px is USD)
    sz String Quantity to buy or sell
    pnl String Profit and loss, Applicable to orders which have a trade and aim to close position. It always is 0 in other conditions
    ordType String Order type
    market: Market order
    limit: Limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    optimal_limit_ioc: Market order with immediate-or-cancel order
    mmp: Market Maker Protection (only applicable to Option in Portfolio Margin mode)
    mmp_and_post_only: Market Maker Protection and Post-only order(only applicable to Option in Portfolio Margin mode)
    op_fok: Simple options (fok)
    side String Order side
    posSide String Position side
    tdMode String Trade mode
    accFillSz String Accumulated fill quantity
    fillPx String Last filled price
    tradeId String Last trade ID
    fillSz String Last filled quantity
    fillTime String Last filled time
    avgPx String Average filled price. If none is filled, it will return "".
    state String State
    live
    partially_filled
    lever String Leverage, from 0.01 to 125.
    Only applicable to MARGIN/FUTURES/SWAP
    attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL.
    tpTriggerPx String Take-profit trigger price.
    tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    tpOrdPx String Take-profit order price.
    slTriggerPx String Stop-loss trigger price.
    slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    slOrdPx String Stop-loss order price.
    attachAlgoOrds Array of object TP/SL information attached when placing order
    > attachAlgoId String The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely.
    > attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > tpTriggerPx String Take-profit trigger price.
    > tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    > tpOrdPx String Take-profit order price.
    > slTriggerPx String Stop-loss trigger price.
    > slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    > slOrdPx String Stop-loss order price.
    > sz String Size. Only applicable to TP order of split TPs
    > amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    stpId String Self trade prevention ID
    Return "" if self trade prevention is not applicable
    stpMode String Self trade prevention mode
    Return "" if self trade prevention is not applicable
    feeCcy String Fee currency
    fee String Fee and rebate
    For spot and margin, it is accumulated fee charged by the platform. It is always negative, e.g. -0.01.
    For Expiry Futures, Perpetual Futures and Options, it is accumulated fee and rebate
    rebateCcy String Rebate currency
    source String Order source
    6: The normal order triggered by the trigger order
    7:The normal order triggered by the TP/SL order
    13: The normal order triggered by the algo order
    24:The normal order triggered by the trailing stop order
    rebate String Rebate amount, only applicable to spot and margin, the reward of placing orders from the platform (rebate) given to user who has reached the specified trading level. If there is no rebate, this field is "".
    category String Category
    normal
    reduceOnly String Whether the order can only reduce the position size. Valid options: true or false.
    quickMgnType String Quick Margin type, Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    algoClOrdId String Client-supplied Algo ID. There will be a value when algo order attaching algoClOrdId is triggered, or it will be "".
    algoId String Algo ID. There will be a value when algo order is triggered, or it will be "".
    uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    GET / Order history (last 7 days)

    Get completed orders which are placed in the last 7 days, including those placed 7 days ago but completed in the last 7 days.

    The incomplete orders that have been canceled are only reserved for 2 hours.

    Rate Limit: 40 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/orders-history

    Request Example

    GET /api/v5/trade/orders-history?ordType=post_only,fok,ioc&instType=SPOT
    
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get completed SPOT orders which are placed in the last 7 days
    # The incomplete orders that have been canceled are only reserved for 2 hours
    result = tradeAPI.get_orders_history(
        instType="SPOT",
        ordType="post_only,fok,ioc"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String yes Instrument type
    SPOT
    instId String No Instrument ID, e.g. BTC-USDT
    ordType String No Order type
    market: market order
    limit: limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    state String No State
    canceled
    filled
    mmp_canceled: Order canceled automatically due to Market Maker Protection
    after String No Pagination of data to return records earlier than the requested ordId
    before String No Pagination of data to return records newer than the requested ordId
    begin String No Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
    end String No Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
    limit String No Number of results per request. The maximum is 100. The default is 100

    Response Example

    {
        "code": "0",
        "data": [
            {
                "accFillSz": "0.00192834",
                "algoClOrdId": "",
                "algoId": "",
                "attachAlgoClOrdId": "",
                "attachAlgoOrds": [],
                "avgPx": "51858",
                "cTime": "1708587373361",
                "cancelSource": "",
                "cancelSourceReason": "",
                "category": "normal",
                "ccy": "",
                "clOrdId": "",
                "fee": "-0.00000192834",
                "feeCcy": "BTC",
                "fillPx": "51858",
                "fillSz": "0.00192834",
                "fillTime": "1708587373361",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "isTpLimit": "false",
                "lever": "",
                "ordId": "680800019749904384",
                "ordType": "market",
                "pnl": "0",
                "posSide": "",
                "px": "",
                "pxType": "",
                "pxUsd": "",
                "pxVol": "",
                "quickMgnType": "",
                "rebate": "0",
                "rebateCcy": "USDT",
                "reduceOnly": "false",
                "side": "buy",
                "slOrdPx": "",
                "slTriggerPx": "",
                "slTriggerPxType": "",
                "source": "",
                "state": "filled",
                "stpId": "",
                "stpMode": "",
                "sz": "100",
                "tag": "",
                "tdMode": "cash",
                "tgtCcy": "quote_ccy",
                "tpOrdPx": "",
                "tpTriggerPx": "",
                "tpTriggerPxType": "",
                "tradeId": "744876980",
                "uTime": "1708587373362"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    ccy String Margin currency
    Only applicable to cross MARGIN orders in Single-currency margin.
    ordId String Order ID
    clOrdId String Client Order ID as assigned by the client
    tag String Order tag
    px String Price
    For options, use coin as unit (e.g. BTC, ETH)
    pxUsd String Options price in USDOnly applicable to options; return "" for other instrument types
    pxVol String Implied volatility of the options orderOnly applicable to options; return "" for other instrument types
    pxType String Price type of options
    px: Place an order based on price, in the unit of coin (the unit for the request parameter px is BTC or ETH)
    pxVol: Place an order based on pxVol
    pxUsd: Place an order based on pxUsd, in the unit of USD (the unit for the request parameter px is USD)
    sz String Quantity to buy or sell
    ordType String Order type
    market: market order
    limit: limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    optimal_limit_ioc: Market order with immediate-or-cancel order
    mmp: Market Maker Protection (only applicable to Option in Portfolio Margin mode)
    mmp_and_post_only: Market Maker Protection and Post-only order(only applicable to Option in Portfolio Margin mode)
    op_fok: Simple options (fok)
    side String Order side
    posSide String Position side
    tdMode String Trade mode
    accFillSz String Accumulated fill quantity
    fillPx String Last filled price. If none is filled, it will return "".
    tradeId String Last trade ID
    fillSz String Last filled quantity
    fillTime String Last filled time
    avgPx String Average filled price. If none is filled, it will return "".
    state String State
    canceled
    filled
    mmp_canceled
    lever String Leverage, from 0.01 to 125.
    Only applicable to MARGIN/FUTURES/SWAP
    attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL.
    tpTriggerPx String Take-profit trigger price.
    tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    tpOrdPx String Take-profit order price.
    slTriggerPx String Stop-loss trigger price.
    slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    slOrdPx String Stop-loss order price.
    attachAlgoOrds Array of object TP/SL information attached when placing order
    > attachAlgoId String The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely.
    > attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > tpTriggerPx String Take-profit trigger price.
    > tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    > tpOrdPx String Take-profit order price.
    > slTriggerPx String Stop-loss trigger price.
    > slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    > slOrdPx String Stop-loss order price.
    > sz String Size. Only applicable to TP order of split TPs
    > amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    stpId String Self trade prevention ID
    Return "" if self trade prevention is not applicable
    stpMode String Self trade prevention mode
    Return "" if self trade prevention is not applicable
    feeCcy String Fee currency
    fee String Fee and rebate
    For spot and margin, it is accumulated fee charged by the platform. It is always negative, e.g. -0.01.
    For Expiry Futures, Perpetual Futures and Options, it is accumulated fee and rebate
    rebateCcy String Rebate currency
    source String Order source
    6: The normal order triggered by the trigger order
    7:The normal order triggered by the TP/SL order
    13: The normal order triggered by the algo order
    24:The normal order triggered by the trailing stop order
    rebate String Rebate amount, only applicable to spot and margin, the reward of placing orders from the platform (rebate) given to user who has reached the specified trading level. If there is no rebate, this field is "".
    pnl String Profit and loss, Applicable to orders which have a trade and aim to close position. It always is 0 in other conditions
    category String Category
    normal
    twap
    adl
    full_liquidation
    partial_liquidation
    delivery
    ddh: Delta dynamic hedge
    reduceOnly String Whether the order can only reduce the position size. Valid options: true or false.
    cancelSource String Code of the cancellation source.
    cancelSourceReason String Reason for the cancellation.
    algoClOrdId String Client-supplied Algo ID. There will be a value when algo order attaching algoClOrdId is triggered, or it will be "".
    algoId String Algo ID. There will be a value when algo order is triggered, or it will be "".
    uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    Get order history (last 3 months)

    Retrieve the completed order data of the last 3 months, and the incomplete orders that have been canceled are only reserved for 2 hours.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/orders-history-archive

    Request Example

    GET /api/v5/trade/orders-history-archive?ordType=post_only,fok,ioc&instType=SPOT
    
    

    Request Parameters

    Parameter Type Required Description
    instType String yes Instrument type
    SPOT
    instId String No Instrument ID, e.g. BTC-USDT
    ordType String No Order type
    market: market order
    limit: limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    state String No State
    canceled
    filled
    category String No Category
    twap
    after String No Pagination of data to return records earlier than the requested ordId
    before String No Pagination of data to return records newer than the requested ordId
    limit String No Number of results per request. The maximum is 100; The default is 100

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
          "instType": "SPOT",
          "instId": "BTC-USDT",
          "ccy": "",
          "ordId": "312269865356374016",
          "clOrdId": "b1",
          "tag": "",
          "px": "999",
          "sz": "3",
          "ordType": "limit",
          "side": "buy",
          "posSide": "",
          "tdMode": "cash",
          "accFillSz": "0",
          "fillPx": "0",
          "tradeId": "0",
          "fillSz": "0",
          "fillTime": "0",
          "state": "filled",
          "avgPx": "0",
          "lever": "20",
          "tpTriggerPx": "",
          "tpTriggerPxType": "",
          "tpOrdPx": "",
          "slTriggerPx": "",
          "slTriggerPxType": "",
          "slOrdPx": "",
          "feeCcy": "",
          "fee": "",
          "rebateCcy": "",
          "rebate": "",
          "tgtCcy":"",
          "pnl": "",
          "category": "",
          "uTime": "1597026383085",
          "cTime": "1597026383085"
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    ccy String Margin currency
    ordId String Order ID
    clOrdId String Client Order ID as assigned by the client
    tag String Order tag
    px String Price
    sz String Quantity to buy or sell
    ordType String Order type
    market: market order
    limit: limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    side String Order side
    posSide String Position side
    tdMode String Trade mode
    accFillSz String Accumulated fill quantity
    fillPx String Last filled price. If none is filled, it will return 0.
    tradeId String Last trade ID
    fillSz String Last filled quantity
    fillTime String Last filled time
    avgPx String Average filled price. If none is filled, it will return "".
    state String State
    canceled
    filled
    lever String Leverage, from 0.01 to 125
    tpTriggerPx String Take-profit trigger price.
    tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    tpOrdPx String Take-profit order price.
    slTriggerPx String Stop-loss trigger price.
    slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    slOrdPx String Stop-loss order price.
    feeCcy String Fee currency
    fee String Fee
    rebateCcy String Rebate currency
    rebate String Rebate amount, the reward of placing orders from the platform (rebate) given to user who has reached the specified trading level. If there is no rebate, this field is "".
    pnl String Profit and loss
    category String Category
    normal
    uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    GET / Transaction details (last 3 days)

    Retrieve recently-filled transaction details in the last 3 day.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/fills

    Request Example

    GET /api/v5/trade/fills
    
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Retrieve recently-filled transaction details
    result = tradeAPI.get_fills()
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String No Instrument type
    SPOT
    instId String No Instrument ID, e.g. BTC-USDT
    ordId String No Order ID
    after String No Pagination of data to return records earlier than the requested billId
    before String No Pagination of data to return records newer than the requested billId
    begin String No Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
    end String No Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
    limit String No Number of results per request. The maximum is 100; The default is 100

    Response Example

    {
        "code": "0",
        "data": [
            {
                "side": "buy",
                "fillSz": "0.00192834",
                "fillPx": "51858",
                "fillPxVol": "",
                "fillFwdPx": "",
                "fee": "-0.00000192834",
                "fillPnl": "0",
                "ordId": "680800019749904384",
                "feeRate": "-0.001",
                "instType": "SPOT",
                "fillPxUsd": "",
                "instId": "BTC-USDT",
                "clOrdId": "",
                "posSide": "net",
                "billId": "680800019754098688",
                "fillMarkVol": "",
                "tag": "",
                "fillTime": "1708587373361",
                "execType": "T",
                "fillIdxPx": "",
                "tradeId": "744876980",
                "fillMarkPx": "",
                "feeCcy": "BTC",
                "ts": "1708587373362"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    tradeId String Last trade ID
    ordId String Order ID
    clOrdId String Client Order ID as assigned by the client
    billId String Bill ID
    tag String Order tag
    fillPx String Last filled price
    fillSz String Last filled quantity
    fillIdxPx String Index price at the moment of trade execution
    For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT.
    fillPnl String Last filled profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions
    fillPxVol String Implied volatility when filled
    Only applicable to options; return "" for other instrument types
    fillPxUsd String Options price when filled, in the unit of USD
    Only applicable to options; return "" for other instrument types
    fillMarkVol String Mark volatility when filled
    Only applicable to options; return "" for other instrument types
    fillFwdPx String Forward price when filled
    Only applicable to options; return "" for other instrument types
    fillMarkPx String Mark price when filled
    Applicable to FUTURES, SWAP, OPTION
    side String Order side, buy sell
    posSide String Position side
    long short
    it returns net innet mode.
    execType String Liquidity taker or maker, T: taker M: maker
    Not applicable to system orders such as ADL and liquidation
    feeCcy String Trading fee or rebate currency
    fee String The amount of trading fee or rebate. The trading fee deduction is negative, such as '-0.01'; the rebate is positive, such as '0.01'.
    ts String Data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085.
    fillTime String Trade time which is the same as fillTime for the order channel.

    GET / Transaction details (last 3 months)

    Retrieve recently-filled transaction details in the last 3 months.

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/fills-history

    Request Example

    GET /api/v5/trade/fills-history
    
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Retrieve SPOT transaction details in the last 3 months.
    result = tradeAPI.get_fills_history(
        instType="SPOT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String YES Instrument type
    SPOT
    instId String No Instrument ID, e.g. BTC-USDT
    ordId String No Order ID
    after String No Pagination of data to return records earlier than the requested billId
    before String No Pagination of data to return records newer than the requested billId
    begin String No Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
    end String No Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
    limit String No Number of results per request. The maximum is 100; The default is 100

    Response Example

    {
        "code": "0",
        "data": [
            {
                "side": "buy",
                "fillSz": "0.00192834",
                "fillPx": "51858",
                "fillPxVol": "",
                "fillFwdPx": "",
                "fee": "-0.00000192834",
                "fillPnl": "0",
                "ordId": "680800019749904384",
                "feeRate": "-0.001",
                "instType": "SPOT",
                "fillPxUsd": "",
                "instId": "BTC-USDT",
                "clOrdId": "",
                "posSide": "net",
                "billId": "680800019754098688",
                "fillMarkVol": "",
                "tag": "",
                "fillTime": "1708587373361",
                "execType": "T",
                "fillIdxPx": "",
                "tradeId": "744876980",
                "fillMarkPx": "",
                "feeCcy": "BTC",
                "ts": "1708587373362"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    tradeId String Last trade ID
    ordId String Order ID
    clOrdId String Client Order ID as assigned by the client
    billId String Bill ID
    tag String Order tag
    fillPx String Last filled price
    fillSz String Last filled quantity
    fillIdxPx String Index price at the moment of trade execution
    For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT.
    fillPnl String Last filled profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions
    fillPxVol String Implied volatility when filled
    Only applicable to options; return "" for other instrument types
    fillPxUsd String Options price when filled, in the unit of USD
    Only applicable to options; return "" for other instrument types
    fillMarkVol String Mark volatility when filled
    Only applicable to options; return "" for other instrument types
    fillFwdPx String Forward price when filled
    Only applicable to options; return "" for other instrument types
    fillMarkPx String Mark price when filled
    Applicable to FUTURES, SWAP, OPTION
    side String Order side
    buy
    sell
    posSide String Position side
    long
    short
    it returns net innet mode.
    execType String Liquidity taker or maker
    T: taker
    M: maker
    Not applicable to system orders such as ADL and liquidation
    feeCcy String Trading fee or rebate currency
    fee String The amount of trading fee or rebate. The trading fee deduction is negative, such as '-0.01'; the rebate is positive, such as '0.01'.
    ts String Data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085.
    fillTime String Trade time which is the same as fillTime for the order channel.

    POST / Transaction details (in the past 2 years)

    Apply for recently-filled transaction details in the past 2 years except for last 3 months.

    Rate Limit: 10 requests per day

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/trade/fills-archive

    Request Example

    POST /api/v5/trade/fills-archive
    body
    {
        "year":"2023",
        "quarter":"Q1"
    }
    

    Request Parameters

    Parameter Type Required Description
    year String Yes 4 digits year
    quarter String Yes Quarter, valid value is Q1, Q2, Q3, Q4

    Response Example

    {
        "code": "0",
        "data": [
            {
                "ts": "1646892328000"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ts String Download link generation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    GET / Transaction details (in the past 2 years)

    Retrieve recently-filled transaction details in the past 2 years except for last 3 months.

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/fills-archive

    Request Example

    GET /api/v5/trade/fills-archive?year=2023&quarter=Q4
    
    

    Request Parameters

    Parameter Type Required Description
    year String Yes 4 digits year
    quarter String Yes Quarter, valid value is Q1, Q2, Q3, Q4

    Response Example

    {
        "code": "0",
        "data": [
            {
                "fileHref": "http://xxx",
                "state": "finished",
                "ts": "1646892328000"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    fileHref String Download file link
    ts String Download link generation time, Unix timestamp format in milliseconds, e.g. 1597026383085
    state String Download link status
    "finished" "ongoing"

    Field descriptions in the decompressed CSV file

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    tradeId String Last trade ID
    ordId String Order ID
    clOrdId String Client Order ID as assigned by the client
    billId String Bill ID
    tag String Order tag
    fillPx String Last filled price
    fillSz String Last filled quantity
    fillIdxPx String Index price at the moment of trade execution
    For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT.
    fillPnl String Last filled profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions
    fillPxVol String Implied volatility when filled
    Only applicable to options; return "" for other instrument types
    fillPxUsd String Options price when filled, in the unit of USD
    Only applicable to options; return "" for other instrument types
    fillMarkVol String Mark volatility when filled
    Only applicable to options; return "" for other instrument types
    fillFwdPx String Forward price when filled
    Only applicable to options; return "" for other instrument types
    fillMarkPx String Mark price when filled
    Applicable to FUTURES, SWAP, OPTION
    side String Order side, buy sell
    posSide String Position side
    long short
    it returns net innet mode.
    execType String Liquidity taker or maker, T: taker M: maker
    Not applicable to system orders such as ADL and liquidation
    feeCcy String Trading fee or rebate currency
    fee String The amount of trading fee or rebate. The trading fee deduction is negative, such as '-0.01'; the rebate is positive, such as '0.01'.
    ts String Data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085.
    fillTime String Trade time which is the same as fillTime for the order channel.

    GET / Easy convert currency list

    Get list of small convertibles and mainstream currencies. Only applicable to the crypto balance less than $10.

    Rate Limit: 1 request per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/easy-convert-currency-list

    Request Example

    GET /api/v5/trade/easy-convert-currency-list
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get list of small convertibles and mainstream currencies
    result = tradeAPI.get_easy_convert_currency_list()
    print(result)
    

    Request Parameters

    None

    Response Example

    {
        "code": "0",
        "data": [
            {
                "fromData": [
                    {
                        "fromAmt": "6.580712708344864",
                        "fromCcy": "ADA"
                    },
                    {
                        "fromAmt": "2.9970000013055097",
                        "fromCcy": "USDC"
                    }
                ],
                "toCcy": [
                    "USDT",
                    "BTC",
                    "ETH",
                    "OKB"
                ]
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    fromData Array Currently owned and convertible small currency list
    > fromCcy String Type of small payment currency convert from, e.g. BTC
    > fromAmt String Amount of small payment currency convert from
    toCcy Array Type of mainstream currency convert to, e.g. USDT

    POST / Place easy convert

    Convert small currencies to mainstream currencies. Only applicable to the crypto balance less than $10.

    Rate Limit: 1 request per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/trade/easy-convert

    Request Example

    POST /api/v5/trade/easy-convert
    body
    {
        "fromCcy": ["ADA","USDC"], //Seperated by commas
        "toCcy": "OKB" 
    }
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Convert small currencies to mainstream currencies
    result = tradeAPI.easy_convert(
        fromCcy=["ADA", "USDC"],
        toCcy="OKB"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    fromCcy Array Yes Type of small payment currency convert from
    Maximum 5 currencies can be selected in one order. If there are multiple currencies, separate them with commas.
    toCcy String Yes Type of mainstream currency convert to
    Only one receiving currency type can be selected in one order and cannot be the same as the small payment currencies.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "fillFromSz": "6.5807127",
                "fillToSz": "0.17171580105126",
                "fromCcy": "ADA",
                "status": "running",
                "toCcy": "OKB",
                "uTime": "1661419684687"
            },
            {
                "fillFromSz": "2.997",
                "fillToSz": "0.1683755161661844",
                "fromCcy": "USDC",
                "status": "running",
                "toCcy": "OKB",
                "uTime": "1661419684687"
            }
        ],
        "msg": ""
    }
    
    

    Response Parameters

    Parameter Type Description
    status String Current status of easy convert
    running: Running
    filled: Filled
    failed: Failed
    fromCcy String Type of small payment currency convert from
    toCcy String Type of mainstream currency convert to
    fillFromSz String Filled amount of small payment currency convert from
    fillToSz String Filled amount of mainstream currency convert to
    uTime String Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085

    GET / Easy convert history

    Get the history and status of easy convert trades.

    Rate Limit: 1 request per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/easy-convert-history

    Request Example

    GET /api/v5/trade/easy-convert-history
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get the history of easy convert trades
    result = tradeAPI.get_easy_convert_history()
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    after String No Pagination of data to return records earlier than the requested time, Unix timestamp format in milliseconds, e.g. 1597026383085
    before String No Pagination of data to return records newer than the requested time, Unix timestamp format in milliseconds, e.g. 1597026383085
    limit String No Number of results per request. The maximum is 100. The default is 100.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "fillFromSz": "0.1761712511667539",
                "fillToSz": "6.7342205900000000",
                "fromCcy": "OKB",
                "status": "filled",
                "toCcy": "ADA",
                "uTime": "1661313307979"
            },
            {
                "fillFromSz": "0.1722106121112177",
                "fillToSz": "2.9971018300000000",
                "fromCcy": "OKB",
                "status": "filled",
                "toCcy": "USDC",
                "uTime": "1661313307979"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    fromCcy String Type of small payment currency convert from
    fromSz String Amount of small payment currency convert from
    toCcy String Type of mainstream currency convert to
    toSz String Amount of mainstream currency convert to
    status String Current status of easy convert
    running: Running
    filled: Filled
    failed: Failed
    uTime String Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085

    POST / Cancel All After

    Cancel all pending orders after the countdown timeout. Applicable to all trading symbols through order book (except Spread trading)

    Rate Limit: 1 request per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/trade/cancel-all-after

    Request Example

    POST /api/v5/trade/cancel-all-after
    {
       "timeOut":"60"
    }
    

    Request Parameters

    Parameter Type Required Description
    timeOut String Yes The countdown for order cancellation, with second as the unit.
    Range of value can be 0, [10, 120].
    Setting timeOut to 0 disables Cancel All After.

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "triggerTime":"1587971460",
                "ts":"1587971400"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    triggerTime String The time the cancellation is triggered.
    triggerTime=0 means Cancel All After is disabled.
    ts String The time the request is sent.

    GET / Account rate limit

    Get account rate limit related information.

    Only new order requests and amendment order requests will be counted towards this limit. For batch order requests consisting of multiple orders, each order will be counted individually.

    For details, please refer to Fill ratio based sub-account rate limit

    Rate Limit: 1 request per second

    Rate limit rule: UserID

    HTTP Requests

    GET /api/v5/trade/account-rate-limit

    Request Example

    # Get the account rate limit
    GET /api/v5/trade/account-rate-limit
    
    

    Request Parameters

    None

    Response Example

    {
       "code":"0",
       "data":[
          {
             "accRateLimit":"2000",
             "fillRatio":"0.1234",
             "mainFillRatio":"0.1234",
             "nextAccRateLimit":"2000",
             "ts":"123456789000"
          }
       ],
       "msg":""
    }
    
    

    Response Parameters

    Parameter Type Description
    fillRatio String Sub account fill ratio during the monitoring period
    Applicable for users with trading fee level >= VIP 5 and return "" for others
    For accounts with no trading volume during the monitoring period, return "0"
    mainFillRatio String Master account aggregated fill ratio during the monitoring period
    Applicable for users with trading fee level >= VIP 5 and return "" for others
    For accounts with no trading volume during the monitoring period, return "0"
    accRateLimit String Current sub-account rate limit per two seconds
    nextAccRateLimit String Expected sub-account rate limit (per two seconds) in the next period
    Applicable for users with trading fee level >= VIP 5 and return "" for others
    ts String Data update time
    For users with trading fee level >= VIP 5, the data will be generated at 08:00 am (UTC)
    For users with trading fee level < VIP 5, return the current timestamp

    WS / Order channel

    Retrieve order information. Data will not be pushed when first subscribed. Data will only be pushed when there are order updates.

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "orders",
          "instType": "ANY"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    orders
    > instType String Yes Instrument type
    ANY
    > instId String No Instrument ID

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "orders",
        "instType": "ANY"
      },
      "connId": "a4d3ae55"
    }
    

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "orders",
        "instType": "ANY"
      },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"orders\", \"instType\" : \"FUTURES\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    > instType String Yes Instrument type
    ANY
    > instId String No Instrument ID
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
        "arg": {
            "channel": "orders",
            "instType": "ANY",
            "uid": "614488474791936"
        },
        "data": [
            {
                "accFillSz": "0.001",
                "algoClOrdId": "",
                "algoId": "",
                "amendResult": "",
                "amendSource": "",
                "avgPx": "31527.1",
                "cancelSource": "",
                "category": "normal",
                "ccy": "",
                "clOrdId": "",
                "code": "0",
                "cTime": "1654084334977",
                "execType": "M",
                "fee": "-0.02522168",
                "feeCcy": "USDT",
                "fillFee": "-0.02522168",
                "fillFeeCcy": "USDT",
                "fillNotionalUsd": "31.50818374",
                "fillPx": "31527.1",
                "fillSz": "0.001",
                "fillPnl": "0.01",
                "fillTime": "1654084353263",
                "fillPxVol": "",
                "fillPxUsd": "",
                "fillMarkVol": "",
                "fillFwdPx": "",
                "fillMarkPx": "",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "lever": "0",
                "msg": "",
                "notionalUsd": "31.50818374",
                "ordId": "452197707845865472",
                "ordType": "limit",
                "pnl": "0",
                "posSide": "",
                "px": "31527.1",
                "pxUsd":"",
                "pxVol":"",
                "pxType":"",
                "quickMgnType": "",
                "rebate": "0",
                "rebateCcy": "BTC",
                "reduceOnly": "false",
                "reqId": "",
                "side": "sell",
                "attachAlgoClOrdId": "",
                "slOrdPx": "",
                "slTriggerPx": "",
                "slTriggerPxType": "last",
                "source": "",
                "state": "filled",
                "stpId": "",
                "stpMode": "",
                "sz": "0.001",
                "tag": "",
                "tdMode": "cash",
                "tgtCcy": "",
                "tpOrdPx": "",
                "tpTriggerPx": "",
                "tpTriggerPxType": "last",
                "attachAlgoOrds": [],
                "tradeId": "242589207",
                "lastPx": "38892.2",
                "uTime": "1654084353264"
            }
        ]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > uid String User Identifier
    > instType String Instrument type
    > instFamily String Instrument family
    > instId String Instrument ID
    data Array Subscribed data
    > instType String Instrument type
    > instId String Instrument ID
    > tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market orders.
    Default is quote_ccy for buy, base_ccy for sell
    > ccy String Margin currency
    Only applicable to cross MARGIN orders in Single-currency margin.
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > tag String Order tag
    > px String Price
    For options, use coin as unit (e.g. BTC, ETH)
    > pxUsd String Options price in USDOnly applicable to options; return "" for other instrument types
    > pxVol String Implied volatility of the options orderOnly applicable to options; return "" for other instrument types
    > pxType String Price type of options
    px: Place an order based on price, in the unit of coin (the unit for the request parameter px is BTC or ETH)
    pxVol: Place an order based on pxVol
    pxUsd: Place an order based on pxUsd, in the unit of USD (the unit for the request parameter px is USD)
    > sz String The original order quantity, SPOT/MARGIN, in the unit of currency; FUTURES/SWAP/OPTION, in the unit of contract
    > notionalUsd String Estimated national value in USD of order
    > ordType String Order type
    market: market order
    limit: limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    optimal_limit_ioc: Market order with immediate-or-cancel order (applicable only to Expiry Futures and Perpetual Futures)
    mmp: Market Maker Protection (only applicable to Option in Portfolio Margin mode)
    mmp_and_post_only: Market Maker Protection and Post-only order(only applicable to Option in Portfolio Margin mode).
    op_fok: Simple options (fok)
    > side String Order side, buy sell
    > posSide String Position side
    net
    long or short Only applicable to FUTURES/SWAP
    > tdMode String Trade mode, cross: cross isolated: isolated cash: cash
    > fillPx String Last filled price
    > tradeId String Last trade ID
    > fillSz String Last filled quantity
    The unit is base_ccy for SPOT and MARGIN, e.g. BTC-USDT, the unit is BTC; For market orders, the unit both is base_ccy when the tgtCcy is base_ccy or quote_ccy;
    The unit is contract for FUTURES/SWAP/OPTION
    > fillPnl String Last filled profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions
    > fillTime String Last filled time
    > fillFee String last filled fee amount or rebate amount:
    Negative number represents the user transaction fee charged by the platform;
    Positive number represents rebate
    > fillFeeCcy String last filled fee currency or rebate currency.
    It is fee currency when fillFee is less than 0; It is rebate currency when fillFee>=0.
    > fillPxVol String Implied volatility when filled
    Only applicable to options; return "" for other instrument types
    > fillPxUsd String Options price when filled, in the unit of USD
    Only applicable to options; return "" for other instrument types
    > fillMarkVol String Mark volatility when filled
    Only applicable to options; return "" for other instrument types
    > fillFwdPx String Forward price when filled
    Only applicable to options; return "" for other instrument types
    > fillMarkPx String Mark price when filled
    Applicable to FUTURES, SWAP, OPTION
    > execType String Liquidity taker or maker of the last filled, T: taker M: maker
    > accFillSz String Accumulated fill quantity
    The unit is base_ccy for SPOT and MARGIN, e.g. BTC-USDT, the unit is BTC; For market orders, the unit both is base_ccy when the tgtCcy is base_ccy or quote_ccy;
    The unit is contract for FUTURES/SWAP/OPTION
    > fillNotionalUsd String Filled notional value in USD of order
    > avgPx String Average filled price. If none is filled, it will return 0.
    > state String Order state
    canceled
    live
    partially_filled
    filled
    mmp_canceled
    > lever String Leverage, from 0.01 to 125.
    Only applicable to MARGIN/FUTURES/SWAP
    > attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL.
    > tpTriggerPx String Take-profit trigger price, it
    > tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    > tpOrdPx String Take-profit order price, it
    > slTriggerPx String Stop-loss trigger price, it
    > slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    > slOrdPx String Stop-loss order price, it
    > attachAlgoOrds Array of object TP/SL information attached when placing order
    >> attachAlgoId String The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely.
    >> attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    >> tpTriggerPx String Take-profit trigger price.
    >> tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    >> tpOrdPx String Take-profit order price.
    >> slTriggerPx String Stop-loss trigger price.
    >> slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    >> slOrdPx String Stop-loss order price.
    >> sz String Size. Only applicable to TP order of split TPs
    >> amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    > stpId String Self trade prevention ID
    Return "" if self trade prevention is not applicable
    > stpMode String Self trade prevention mode
    Return "" if self trade prevention is not applicable
    > feeCcy String Fee currency
    SPOT/MARGIN: If you buy, you will receive BTC; if you sell, you will receive USDT
    FUTURES/SWAP/OPTION What is charged is the margin
    > fee String Fee and rebate
    For spot and margin, it is accumulated fee charged by the platform. It is always negative, e.g. -0.01.
    For Expiry Futures, Perpetual Futures and Options, it is accumulated fee and rebate
    > rebateCcy String Rebate currency, if there is no rebate, this field is "".
    > rebate String Rebate accumulated amount, only applicable to spot and margin, the reward of placing orders from the platform (rebate) given to user who has reached the specified trading level. If there is no rebate, this field is "".
    > pnl String Profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions.
    For liquidation under cross margin mode, it will include liquidation penalties.
    > source String Order source
    6: The normal order triggered by the trigger order
    7:The normal order triggered by the TP/SL order
    13: The normal order triggered by the algo order
    24:The normal order triggered by the trailing stop order
    > cancelSource String Source of the order cancellation.
    Valid values and the corresponding meanings are:
    0: Order canceled by system
    1: Order canceled by user
    2: Order canceled: Pre reduce-only order canceled, due to insufficient margin in user position
    3: Order canceled: Risk cancellation was triggered. Pending order was canceled due to insufficient margin ratio and forced-liquidation risk.
    4: Order canceled: Borrowings of crypto reached hard cap, order was canceled by system.
    6: Order canceled: ADL order cancellation was triggered. Pending order was canceled due to a low margin ratio and forced-liquidation risk.
    7: Order canceled: Futures contract delivery.
    9: Order canceled: Insufficient balance after funding fees deducted.
    13: Order canceled: FOK order was canceled due to incompletely filled.
    14: Order canceled: IOC order was partially canceled due to incompletely filled.
    15: Order canceled: The order price is beyond the limit
    17: Order canceled: Close order was canceled, due to the position was already closed at market price.
    20: Cancel all after triggered
    21: Order canceled: The TP/SL order was canceled because the position had been closed
    22, 23: Order canceled: Reduce-only orders only allow reducing your current position. System has already canceled this order.
    27: Order canceled: Price limit verification failed because the price difference between counterparties exceeds 5%
    31: The post-only order will take liquidity in taker orders
    32: Self trade prevention
    33: The order exceeds the maximum number of order matches per taker order
    > amendSource String Source of the order amendation.
    1: Order amended by user
    2: Order amended by user, but the order quantity is overriden by system due to reduce-only
    3: New order placed by user, but the order quantity is overriden by system due to reduce-only
    4: Order amended by system due to other pending orders
    5: Order modification due to changes in options px, pxVol, or pxUsd as a result of following variations. For example, when iv = 60, usd and px are anchored at iv = 60, the changes in usd or px lead to modification.
    > category String Category
    normal
    twap
    adl
    full_liquidation
    partial_liquidation
    delivery
    ddh: Delta dynamic hedge
    > uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    > cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
    > reqId String Client Request ID as assigned by the client for order amendment. "" will be returned if there is no order amendment.
    > amendResult String The result of amending the order
    -1: failure
    0: success
    1: Automatic cancel (amendment request returned success but amendment subsequently failed then automatically canceled by the system)
    2: Automatic amendation successfully, only applicable to pxVol and pxUsd orders of Option.
    When amending the order through API and cxlOnFail is set to true in the order amendment request but the amendment is rejected, "" is returned.
    When amending the order through API, the order amendment acknowledgement returns success and the amendment subsequently failed, -1 will be returned if cxlOnFail is set to false, 1 will be returned if cxlOnFail is set to true.
    When amending the order through Web/APP and the amendment failed, -1 will be returned.
    > reduceOnly String Whether the order can only reduce the position size. Valid options: true or false.
    > quickMgnType String Quick Margin type, Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    > algoClOrdId String Client-supplied Algo ID. There will be a value when algo order attaching algoClOrdId is triggered, or it will be "".
    > algoId String Algo ID. There will be a value when algo order is triggered, or it will be "".
    > lastPx String Last price
    > code String Error Code, the default is 0
    > msg String Error Message, The default is ""

    WS / Place order

    You can place an order only if you have sufficient funds.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule: UserID + Instrument ID

    Request Example

    {
      "id": "1512",
      "op": "order",
      "args": [
        {
          "side": "buy",
          "instId": "BTC-USDT",
          "tdMode": "cash",
          "ordType": "market",
          "sz": "100"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    id String Yes Unique identifier of the message
    Provided by client. It will be returned in response message for identifying the corresponding request.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    op String Yes Operation
    order
    args Array Yes Request parameters
    > instId String Yes Instrument ID, e.g. BTC-USDT
    > tdMode String Yes Trade mode
    cash
    > clOrdId String No Client Order ID as assigned by the client
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    > tag String No Order tag
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
    > side String Yes Order side
    buy
    sell
    > ordType String Yes Order type
    market: market order
    limit: limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    > sz String Yes Quantity to buy or sell.
    > px String Conditional Order price. Only applicable to limit,post_only,fok,ioc,mmp,mmp_and_post_only order.
    > tgtCcy String No Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    > banAmend Boolean No Whether to disallow the system from amending the size of the SPOT Market Order.
    Valid options: true or false. The default value is false.
    If true, system will not amend and reject the market order if user does not have sufficient funds.
    Only applicable to SPOT Market Orders
    > stpId String No Self trade prevention ID. Orders from the same master account with the same ID will be prevented from self trade.
    Numerical integers defined by user in the range of 1<= x<= 999999999
    > stpMode String No Self trade prevention mode. It is available only when stpId is filled.
    Default to cancel maker
    cancel_maker,cancel_taker, cancel_both
    Cancel both does not support FOK.
    expTime String No Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085

    Successful Response Example

    {
      "id": "1512",
      "op": "order",
      "data": [
        {
          "clOrdId": "",
          "ordId": "12345689",
          "tag": "",
          "sCode": "0",
          "sMsg": ""
        }
      ],
      "code": "0",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Failure Response Example

    {
      "id": "1512",
      "op": "order",
      "data": [
        {
          "clOrdId": "",
          "ordId": "",
          "tag": "",
          "sCode": "5XXXX",
          "sMsg": "not exist"
        }
      ],
      "code": "1",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When Format Error

    {
      "id": "1512",
      "op": "order",
      "data": [],
      "code": "60013",
      "msg": "Invalid args",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    id String Unique identifier of the message
    op String Operation
    code String Error Code
    msg String Error message
    data Array Data
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > tag String Order tag
    > sCode String Order status code, 0 means success
    > sMsg String Rejection or success message of event execution.
    inTime String Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    outTime String Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    WS / Place multiple orders

    Place orders in a batch. Maximum 20 orders can be placed per request

    Rate Limit: 300 orders per 2 seconds

    Rate limit rule: UserID + Instrument ID

    Request Example

    {
      "id": "1513",
      "op": "batch-orders",
      "args": [
        {
          "side": "buy",
          "instId": "BTC-USDT",
          "tdMode": "cash",
          "ordType": "market",
          "sz": "100"
        },
        {
          "side": "buy",
          "instId": "LTC-USDT",
          "tdMode": "cash",
          "ordType": "market",
          "sz": "1"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    id String Yes Unique identifier of the message
    Provided by client. It will be returned in response message for identifying the corresponding request.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    op String Yes Operation
    batch-orders
    args Array Yes Request Parameters
    > instId String Yes Instrument ID, e.g. BTC-USDT
    > tdMode String Yes Trade mode
    cash
    > clOrdId String No Client Order ID as assigned by the client
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    > tag String No Order tag
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
    > side String Yes Order side
    buy
    sell
    > ordType String Yes Order type
    market: market order
    limit: limit order
    post_only: Post-only order
    fok: Fill-or-kill order
    ioc: Immediate-or-cancel order
    > sz String Yes Quantity to buy or sell.
    > px String Conditional Order price. Only applicable to limit,post_only,fok,ioc,mmp,mmp_and_post_only order.
    > tgtCcy String No Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    > banAmend Boolean No Whether to disallow the system from amending the size of the SPOT Market Order.
    Valid options: true or false. The default value is false.
    If true, system will not amend and reject the market order if user does not have sufficient funds.
    Only applicable to SPOT Market Orders
    > stpId String No Self trade prevention ID. Orders from the same master account with the same ID will be prevented from self trade.
    Numerical integers defined by user in the range of 1<= x<= 999999999
    > stpMode String No Self trade prevention mode. It is available only when stpId is filled.
    Default to cancel maker
    cancel_maker,cancel_taker, cancel_both
    Cancel both does not support FOK.
    expTime String No Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085

    Response Example When All Succeed

    {
      "id": "1513",
      "op": "batch-orders",
      "data": [
        {
          "clOrdId": "",
          "ordId": "12345689",
          "tag": "",
          "sCode": "0",
          "sMsg": ""
        },
        {
          "clOrdId": "",
          "ordId": "12344",
          "tag": "",
          "sCode": "0",
          "sMsg": ""
        }
      ],
      "code": "0",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When Partially Successful

    {
      "id": "1513",
      "op": "batch-orders",
      "data": [
        {
          "clOrdId": "",
          "ordId": "12345689",
          "tag": "",
          "sCode": "0",
          "sMsg": ""
        },
        {
          "clOrdId": "",
          "ordId": "",
          "tag": "",
          "sCode": "5XXXX",
          "sMsg": "Insufficient margin"
        }
      ],
      "code": "2",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When All Failed

    {
      "id": "1513",
      "op": "batch-orders",
      "data": [
        {
          "clOrdId": "oktswap6",
          "ordId": "",
          "tag": "",
          "sCode": "5XXXX",
          "sMsg": "Insufficient margin"
        },
        {
          "clOrdId": "oktswap7",
          "ordId": "",
          "tag": "",
          "sCode": "5XXXX",
          "sMsg": "Insufficient margin"
        }
      ],
      "code": "1",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When Format Error

    {
      "id": "1513",
      "op": "batch-orders",
      "data": [],
      "code": "60013",
      "msg": "Invalid args",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    id String Unique identifier of the message
    op String Operation
    code String Error Code
    msg String Error message
    data Array Data
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > tag String Order tag
    > sCode String Order status code, 0 means success
    > sMsg String Rejection or success message of event execution.
    inTime String Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    outTime String Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    WS / Cancel order

    Cancel an incomplete order

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule: UserID + Instrument ID

    Request Example

    {
      "id": "1514",
      "op": "cancel-order",
      "args": [
        {
          "instId": "BTC-USDT",
          "ordId": "2510789768709120"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    id String Yes Unique identifier of the message
    Provided by client. It will be returned in response message for identifying the corresponding request.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    op String Yes Operation
    cancel-order
    args Array Yes Request Parameters
    > instId String Yes Instrument ID
    > ordId String Conditional Order ID
    Either ordId or clOrdId is required, if both are passed, ordId will be used
    > clOrdId String Conditional Client Order ID as assigned by the client
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

    Successful Response Example

    {
      "id": "1514",
      "op": "cancel-order",
      "data": [
        {
          "clOrdId": "",
          "ordId": "2510789768709120",
          "sCode": "0",
          "sMsg": ""
        }
      ],
      "code": "0",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Failure Response Example

    {
      "id": "1514",
      "op": "cancel-order",
      "data": [
        {
          "clOrdId": "",
          "ordId": "2510789768709120",
          "sCode": "5XXXX",
          "sMsg": "Order not exist"
        }
      ],
      "code": "1",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When Format Error

    {
      "id": "1514",
      "op": "cancel-order",
      "data": [],
      "code": "60013",
      "msg": "Invalid args",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    id String Unique identifier of the message
    op String Operation
    code String Error Code
    msg String Error message
    data Array Data
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > sCode String Order status code, 0 means success
    > sMsg String Order status message
    inTime String Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    outTime String Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    WS / Cancel multiple orders

    Cancel incomplete orders in batches. Maximum 20 orders can be canceled per request.

    Rate Limit: 300 orders per 2 seconds

    Rate limit rule: UserID + Instrument ID

    Request Example

    {
      "id": "1515",
      "op": "batch-cancel-orders",
      "args": [
        {
          "instId": "BTC-USDT",
          "ordId": "2517748157541376"
        },
        {
          "instId": "LTC-USDT",
          "ordId": "2517748155771904"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    id String Yes Unique identifier of the message
    Provided by client. It will be returned in response message for identifying the corresponding request.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    op String Yes Operation
    batch-cancel-orders
    args Array Yes Request Parameters
    > instId String Yes Instrument ID
    > ordId String Conditional Order ID
    Either ordId or clOrdId is required, if both are passed, ordId will be used
    > clOrdId String Conditional Client Order ID as assigned by the client
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

    Response Example When All Succeed

    {
      "id": "1515",
      "op": "batch-cancel-orders",
      "data": [
        {
          "clOrdId": "oktswap6",
          "ordId": "2517748157541376",
          "sCode": "0",
          "sMsg": ""
        },
        {
          "clOrdId": "oktswap7",
          "ordId": "2517748155771904",
          "sCode": "0",
          "sMsg": ""
        }
      ],
      "code": "0",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When partially successfully

    {
      "id": "1515",
      "op": "batch-cancel-orders",
      "data": [
        {
          "clOrdId": "oktswap6",
          "ordId": "2517748157541376",
          "sCode": "0",
          "sMsg": ""
        },
        {
          "clOrdId": "oktswap7",
          "ordId": "2517748155771904",
          "sCode": "5XXXX",
          "sMsg": "order not exist"
        }
      ],
      "code": "2",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When All Failed

    {
      "id": "1515",
      "op": "batch-cancel-orders",
      "data": [
        {
          "clOrdId": "oktswap6",
          "ordId": "2517748157541376",
          "sCode": "5XXXX",
          "sMsg": "order not exist"
        },
        {
          "clOrdId": "oktswap7",
          "ordId": "2517748155771904",
          "sCode": "5XXXX",
          "sMsg": "order not exist"
        }
      ],
      "code": "1",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When Format Error

    {
      "id": "1515",
      "op": "batch-cancel-orders",
      "data": [],
      "code": "60013",
      "msg": "Invalid args",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    id String Unique identifier of the message
    op String Operation
    code String Error Code
    msg String Error message
    data Array Data
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > sCode String Order status code, 0 means success
    > sMsg String Order status message
    inTime String Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    outTime String Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    WS / Amend order

    Amend an incomplete order.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule: UserID + Instrument ID

    Request Example

    {
      "id": "1512",
      "op": "amend-order",
      "args": [
        {
          "instId": "BTC-USDT",
          "ordId": "2510789768709120",
          "newSz": "2"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    id String Yes Unique identifier of the message
    Provided by client. It will be returned in response message for identifying the corresponding request.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    op String Yes Operation
    amend-order
    args Array Yes Request Parameters
    > instId String Yes Instrument ID
    > cxlOnFail Boolean No Whether the order needs to be automatically canceled when the order amendment fails
    Valid options: false or true, the default is false.
    > ordId String Conditional Order ID
    Either ordId or clOrdId is required, if both are passed, ordId will be used.
    > clOrdId String Conditional Client Order ID as assigned by the client
    > reqId String No Client Request ID as assigned by the client for order amendment
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    > newSz String Conditional New quantity after amendment. Either newSz or newPx is required. When amending a partially-filled order, the newSz should include the amount that has been filled.
    > newPx String Conditional New price after amendment.
    expTime String No Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085

    Successful Response Example

    {
      "id": "1512",
      "op": "amend-order",
      "data": [
        {
          "clOrdId": "",
          "ordId": "2510789768709120",
          "reqId": "b12344",
          "sCode": "0",
          "sMsg": ""
        }
      ],
      "code": "0",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Failure Response Example

    {
      "id": "1512",
      "op": "amend-order",
      "data": [
        {
          "clOrdId": "",
          "ordId": "2510789768709120",
          "reqId": "b12344",
          "sCode": "5XXXX",
          "sMsg": "order not exist"
        }
      ],
      "code": "1",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When Format Error

    {
      "id": "1512",
      "op": "amend-order",
      "data": [],
      "code": "60013",
      "msg": "Invalid args",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    id String Unique identifier of the message
    op String Operation
    code String Error Code
    msg String Error message
    data Array Data
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > reqId String Client Request ID as assigned by the client for order amendment
    > sCode String Order status code, 0 means success
    > sMsg String Order status message
    inTime String Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    outTime String Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    WS / Amend multiple orders

    Amend incomplete orders in batches. Maximum 20 orders can be amended per request.

    Rate Limit: 300 orders per 2 seconds

    Rate limit rule: UserID + Instrument ID

    Request Example

    {
      "id": "1513",
      "op": "batch-amend-orders",
      "args": [
        {
          "instId": "BTC-USDT",
          "ordId": "12345689",
          "newSz": "2"
        },
        {
          "instId": "BTC-USDT",
          "ordId": "12344",
          "newSz": "2"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    id String Yes Unique identifier of the message
    Provided by client. It will be returned in response message for identifying the corresponding request.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    op String Yes Operation
    batch-amend-orders
    args Array Yes Request Parameters
    > instId String Yes Instrument ID
    > cxlOnFail Boolean No Whether the order needs to be automatically canceled when the order amendment fails
    Valid options: false or true, the default is false.
    > ordId String Conditional Order ID
    Either ordId or clOrdId is required, if both are passed, ordId will be used.
    > clOrdId String Conditional Client Order ID as assigned by the client
    > reqId String No Client Request ID as assigned by the client for order amendment
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    > newSz String Conditional New quantity after amendment. Either newSz or newPx is required. When amending a partially-filled order, the newSz should include the amount that has been filled.
    > newPx String Conditional New price after amendment.
    expTime String No Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085

    Response Example When All Succeed

    {
      "id": "1513",
      "op": "batch-amend-orders",
      "data": [
        {
          "clOrdId": "oktswap6",
          "ordId": "12345689",
          "reqId": "b12344",
          "sCode": "0",
          "sMsg": ""
        },
        {
          "clOrdId": "oktswap7",
          "ordId": "12344",
          "reqId": "b12344",
          "sCode": "0",
          "sMsg": ""
        }
      ],
      "code": "0",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When All Failed

    {
      "id": "1513",
      "op": "batch-amend-orders",
      "data": [
        {
          "clOrdId": "",
          "ordId": "12345689",
          "reqId": "b12344",
          "sCode": "5XXXX",
          "sMsg": "order not exist"
        },
        {
          "clOrdId": "oktswap7",
          "ordId": "",
          "reqId": "b12344",
          "sCode": "5XXXX",
          "sMsg": "order not exist"
        }
      ],
      "code": "1",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When Partially Successful

    {
      "id": "1513",
      "op": "batch-amend-orders",
      "data": [
        {
          "clOrdId": "",
          "ordId": "12345689",
          "reqId": "b12344",
          "sCode": "0",
          "sMsg": ""
        },
        {
          "clOrdId": "oktswap7",
          "ordId": "",
          "reqId": "b12344",
          "sCode": "5XXXX",
          "sMsg": "order not exist"
        }
      ],
      "code": "2",
      "msg": "",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Example When Format Error

    {
      "id": "1513",
      "op": "batch-amend-orders",
      "data": [],
      "code": "60013",
      "msg": "Invalid args",
      "inTime": "1695190491421339",
      "outTime": "1695190491423240"
    }
    

    Response Parameters

    Parameter Type Description
    id String Unique identifier of the message
    op String Operation
    code String Error Code
    msg String Error message
    data Array Data
    > ordId String Order ID
    > clOrdId String Client Order ID as assigned by the client
    > reqId String Client Request ID as assigned by the client for order amendment
    If the user provides reqId in the request, the corresponding reqId will be returned
    > sCode String Order status code, 0 means success
    > sMsg String Order status message
    inTime String Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123
    outTime String Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123

    Algo Trading

    POST / Place algo order

    The algo order includes trigger order, oco order, conditional order and trailing order.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID + Instrument ID

    HTTP Request

    POST /api/v5/trade/order-algo

    Request Example

    # Place Take Profit / Stop Loss Order
    POST /api/v5/trade/order-algo
    body
    {
        "instId":"BTC-USDT",
        "tdMode":"cash",
        "side":"buy",
        "ordType":"conditional",
        "sz":"2",
        "tpTriggerPx":"15",
        "tpOrdPx":"18"
    }
    
    # Place Trigger Order
    POST /api/v5/trade/order-algo
    body
    {
        "instId": "BTC-USDT",
        "tdMode": "cash",
        "side": "buy",
        "ordType": "trigger",
        "sz": "10",
        "triggerPx": "100",
        "orderPx": "-1"
    }
    
    # Place Trailing Stop Order
    POST /api/v5/trade/order-algo
    body
    {
        "instId": "BTC-USDT",
        "tdMode": "cash",
        "side": "buy",
        "ordType": "move_order_stop",
        "sz": "10",
        "callbackRatio": "0.05"
    }
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # One-way stop order
    result = tradeAPI.place_algo_order(
        instId="BTC-USDT",
        tdMode="cash",
        side="buy",
        ordType="conditional",
        sz="2",
        tpTriggerPx="15",
        tpOrdPx="18"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    tdMode String Yes Trade mode
    cash
    side String Yes Order side
    buy
    sell
    ordType String Yes Order type
    conditional: One-way stop order
    oco: One-cancels-the-other order
    trigger: Trigger order
    move_order_stop: Trailing order
    sz String Yes Quantity to buy or sell
    tag String No Order tag
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
    tgtCcy String No Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT traded with Market buy conditional order
    Default is quote_ccy for buy, base_ccy for sell
    algoClOrdId String No Client-supplied Algo ID
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

    Take Profit / Stop Loss Order

    learn more about Take Profit / Stop Loss Order

    Parameter Type Required Description
    tpTriggerPx String No Take-profit trigger price
    If you fill in this parameter, you should fill in the take-profit order price as well.
    tpTriggerPxType String No Take-profit trigger price type
    last: last price
    The default is last
    tpOrdPx String No Take-profit order price
    If you fill in this parameter, you should fill in the take-profit trigger price as well.
    If the price is -1, take-profit will be executed at the market price.
    slTriggerPx String No Stop-loss trigger price
    If you fill in this parameter, you should fill in the stop-loss order price.
    slTriggerPxType String No Stop-loss trigger price type
    last: last price
    The default is last
    slOrdPx String No Stop-loss order price
    If you fill in this parameter, you should fill in the stop-loss trigger price.
    If the price is -1, stop-loss will be executed at the market price.

    Trigger Order

    learn more about Trigger Order

    Parameter Type Required Description
    triggerPx String Yes Trigger price
    orderPx String Yes Order Price
    If the price is -1, the order will be executed at the market price.
    triggerPxType String No Trigger price type
    last: last price
    The default is last

    Trailing Stop Order

    learn more about Trailing Stop Order

    Parameter Type Required Description
    callbackRatio String Conditional Callback price ratio, e.g. 0.01 represents 1%
    Either callbackRatio or callbackSpread is allowed to be passed.
    callbackSpread String Conditional Callback price variance
    activePx String No Active price
    The system will only start tracking the market and calculating your trigger price after the activation price is reached. If you don’t set a price, your order will be activated as soon as it’s placed.

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
          "algoId": "12345689",
          "clOrdId": "",
          "algoClOrdId": "",
          "sCode": "0",
          "sMsg": ""
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    algoId String Algo ID
    clOrdId String Client Order ID as assigned by the client(Deprecated)
    algoClOrdId String Client-supplied Algo ID
    sCode String The code of the event execution result, 0 means success.
    sMsg String Rejection message if the request is unsuccessful.

    POST / Cancel algo order

    Cancel unfilled algo orders (not including Trailing Stop order). A maximum of 10 orders can be canceled per request. Request parameters should be passed in the form of an array.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID + instrumentID

    HTTP Request

    POST /api/v5/trade/cancel-algos

    Request Example

    POST /api/v5/trade/cancel-algos
    body
    [
        {
            "algoId":"198273485",
            "instId":"BTC-USDT"
        },
        {
            "algoId":"198273485",
            "instId":"BTC-USDT"
        }
    ]
    

    Request Parameters

    Parameter Type Required Description
    algoId String Yes Algo ID
    instId String Yes Instrument ID, e.g. BTC-USDT

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "algoId":"1234",
                "sCode":"0",
                "sMsg":""
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    algoId String Order ID
    sCode String The code of the event execution result, 0 means success.
    sMsg String Rejection message if the request is unsuccessful.

    POST / Cancel advance algo order

    Cancel unfilled algo orders (including Trailing Stop order). A maximum of 10 orders can be canceled per request. Request parameters should be passed in the form of an array.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID + Instrument ID

    HTTP Request

    POST /api/v5/trade/cancel-advance-algos

    Request Example

    POST /api/v5/trade/cancel-advance-algos
    body
    [
        {
            "algoId":"590920768125665111",
            "instId":"BTC-USDT"
        },
        {
            "algoId":"590920799650058222",
            "instId":"BTC-USDT"
        }
    ]
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Cancel unfilled algo orders (including Iceberg order, TWAP order, Trailing Stop order)
    algo_orders_advance = [
        {"instId": "BTC-USDT", "algoId": "590920768125665111"},
        {"instId": "BTC-USDT", "algoId": "590920799650058222"}
    ]
    
    result = tradeAPI.cancel_advance_algos(algo_orders_advance)
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    algoId String Yes Algo ID
    instId String Yes Instrument ID, e.g. BTC-USDT

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "algoId":"1234",
                "sCode":"0",
                "sMsg":""
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    algoId String Order ID
    sCode String The code of the event execution result, 0 means success.
    sMsg String Rejection message if the request is unsuccessful.

    GET / Algo order details

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/order-algo

    Request Example

    GET /api/v5/trade/order-algo?algoId=681187161907138560
    

    Request Parameters

    Parameter Type Required Description
    algoId String Conditional Algo ID
    Either algoId or algoClOrdId is required.If both are passed, algoId will be used.
    algoClOrdId String Conditional Client-supplied Algo ID
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "activePx": "",
                "actualPx": "",
                "actualSide": "",
                "actualSz": "",
                "algoClOrdId": "",
                "algoId": "681187161907138560",
                "amendPxOnTriggerType": "",
                "attachAlgoOrds": [],
                "cTime": "1708679675244",
                "callbackRatio": "0.05",
                "callbackSpread": "",
                "ccy": "",
                "clOrdId": "",
                "closeFraction": "",
                "failCode": "",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "last": "50962.7",
                "lever": "",
                "linkedOrd": {
                    "ordId": ""
                },
                "moveTriggerPx": "53423.160",
                "ordId": "",
                "ordIdList": [],
                "ordPx": "",
                "ordType": "move_order_stop",
                "posSide": "net",
                "pxLimit": "",
                "pxSpread": "",
                "pxVar": "",
                "quickMgnType": "",
                "reduceOnly": "false",
                "side": "buy",
                "slOrdPx": "",
                "slTriggerPx": "",
                "slTriggerPxType": "",
                "state": "live",
                "sz": "10",
                "szLimit": "",
                "tag": "",
                "tdMode": "cash",
                "tgtCcy": "",
                "timeInterval": "",
                "tpOrdPx": "",
                "tpTriggerPx": "",
                "tpTriggerPxType": "",
                "triggerPx": "",
                "triggerPxType": "",
                "triggerTime": ""
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    ccy String Margin currency
    Only applicable to cross MARGIN orders in Single-currency margin.
    ordId String Latest order ID
    ordIdList String Order ID list. There will be multiple order IDs when there is TP/SL splitting order.
    algoId String Algo ID
    clOrdId String Client Order ID as assigned by the client
    sz String Quantity to buy or sell
    closeFraction String Fraction of position to be closed when the algo order is triggered
    ordType String Order type
    side String Order side
    posSide String Position side
    tdMode String Trade mode
    tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    state String State
    live
    pause
    partially_effective
    effective
    canceled
    order_failed
    partially_failed
    lever String Leverage, from 0.01 to 125.
    Only applicable to MARGIN/FUTURES/SWAP
    tpTriggerPx String Take-profit trigger price.
    tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    tpOrdPx String Take-profit order price.
    slTriggerPx String Stop-loss trigger price.
    slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    slOrdPx String Stop-loss order price.
    triggerPx String trigger price.
    triggerPxType String trigger price type.
    last: last price
    index: index price
    mark: mark price
    ordPx String Order price
    actualSz String Actual order quantity
    actualPx String Actual order price
    tag String Order tag
    actualSide String Actual trigger side, tp: take profit sl: stop loss
    triggerTime String Trigger time, Unix timestamp format in milliseconds, e.g. 1597026383085
    pxVar String Price ratio
    Only applicable to iceberg order or twap order
    pxSpread String Price variance
    Only applicable to iceberg order or twap order
    szLimit String Average amount
    Only applicable to iceberg order or twap order
    pxLimit String Price Limit
    Only applicable to iceberg order or twap order
    timeInterval String Time interval
    Only applicable to twap order
    callbackRatio String Callback price ratio
    Only applicable to move_order_stop order
    callbackSpread String Callback price variance
    Only applicable to move_order_stop order
    activePx String Active price
    Only applicable to move_order_stop order
    moveTriggerPx String Trigger price
    Only applicable to move_order_stop order
    reduceOnly String Whether the order can only reduce the position size. Valid options: true or false.
    quickMgnType String Quick Margin type, Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    last String Last filled price while placing
    failCode String It represents that the reason that algo order fails to trigger. It is "" when the state is effective/canceled. There will be value when the state is order_failed, e.g. 51008;
    Only applicable to Stop Order, Trailing Stop Order, Trigger order.
    algoClOrdId String Client-supplied Algo ID
    amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    attachAlgoOrds Array of object Attached SL/TP orders info
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    > attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > tpTriggerPx String Take-profit trigger price
    If you fill in this parameter, you should fill in the take-profit order price as well.
    > tpTriggerPxType String Take-profit trigger price type
    last: last price
    index: index price
    mark: mark price
    The default is last
    > tpOrdPx String Take-profit order price
    If you fill in this parameter, you should fill in the take-profit trigger price as well.
    If the price is -1, take-profit will be executed at the market price.
    > slTriggerPx String Stop-loss trigger price
    If you fill in this parameter, you should fill in the stop-loss order price.
    > slTriggerPxType String Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark price
    The default is last
    > slOrdPx String Stop-loss order price
    If you fill in this parameter, you should fill in the stop-loss trigger price.
    If the price is -1, stop-loss will be executed at the market price.
    cTime String Creation time Unix timestamp format in milliseconds, e.g. 1597026383085

    GET / Algo order list

    Retrieve a list of untriggered Algo orders under the current account.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/orders-algo-pending

    Request Example

    GET /api/v5/trade/orders-algo-pending?ordType=conditional
    
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Retrieve a list of untriggered one-way stop orders
    result = tradeAPI.order_algos_list(
        ordType="conditional"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ordType String Yes Order type
    conditional: One-way stop order
    oco: One-cancels-the-other order
    trigger: Trigger order
    move_order_stop: Trailing order
    algoId String No Algo ID
    algoClOrdId String No Client-supplied Algo ID
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    instType String No Instrument type
    SPOT
    instId String No Instrument ID, e.g. BTC-USDT
    after String No Pagination of data to return records earlier than the requested algoId.
    before String No Pagination of data to return records newer than the requested algoId.
    limit String No Number of results per request. The maximum is 100. The default is 100

    Response Example

    {
        "code": "0",
        "data": [
            {
                "activePx": "",
                "actualPx": "",
                "actualSide": "buy",
                "actualSz": "0",
                "algoClOrdId": "",
                "algoId": "681096944655273984",
                "amendPxOnTriggerType": "",
                "attachAlgoOrds": [],
                "cTime": "1708658165774",
                "callbackRatio": "",
                "callbackSpread": "",
                "ccy": "",
                "clOrdId": "",
                "closeFraction": "",
                "failCode": "",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "last": "51014.6",
                "lever": "",
                "moveTriggerPx": "",
                "ordId": "",
                "ordIdList": [],
                "ordPx": "-1",
                "ordType": "trigger",
                "posSide": "net",
                "pxLimit": "",
                "pxSpread": "",
                "pxVar": "",
                "quickMgnType": "",
                "reduceOnly": "false",
                "side": "buy",
                "slOrdPx": "",
                "slTriggerPx": "",
                "slTriggerPxType": "",
                "state": "live",
                "sz": "10",
                "szLimit": "",
                "tag": "",
                "tdMode": "cash",
                "tgtCcy": "",
                "timeInterval": "",
                "tpOrdPx": "",
                "tpTriggerPx": "",
                "tpTriggerPxType": "",
                "triggerPx": "100",
                "triggerPxType": "last",
                "triggerTime": "0"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    ccy String Margin currency
    Only applicable to cross MARGIN orders in Single-currency margin.
    ordId String Latest order ID
    ordIdList String Order ID list. There will be multiple order IDs when there is TP/SL splitting order.
    algoId String Algo ID
    clOrdId String Client Order ID as assigned by the client
    sz String Quantity to buy or sell
    closeFraction String Fraction of position to be closed when the algo order is triggered
    ordType String Order type
    side String Order side
    posSide String Position side
    tdMode String Trade mode
    tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT traded with Market order
    state String State,live pause
    lever String Leverage, from 0.01 to 125.
    Only applicable to MARGIN/FUTURES/SWAP
    tpTriggerPx String Take-profit trigger price
    tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    tpOrdPx String Take-profit order price
    slTriggerPx String Stop-loss trigger price
    slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    slOrdPx String Stop-loss order price
    triggerPx String Trigger price
    triggerPxType String Trigger price type
    last: last price
    index: index price
    mark: mark price
    ordPx String Order price
    actualSz String Actual order quantity
    tag String Order tag
    actualPx String Actual order price
    actualSide String Actual trigger side
    tp: take profit sl: stop loss
    triggerTime String Trigger time, Unix timestamp format in milliseconds, e.g. 1597026383085
    pxVar String Price ratio
    Only applicable to iceberg order or twap order
    pxSpread String Price variance
    Only applicable to iceberg order or twap order
    szLimit String Average amount
    Only applicable to iceberg order or twap order
    pxLimit String Price Limit
    Only applicable to iceberg order or twap order
    timeInterval String Time interval
    Only applicable to twap order
    callbackRatio String Callback price ratio
    Only applicable to move_order_stop order
    callbackSpread String Callback price variance
    Only applicable to move_order_stop order
    activePx String Active price
    Only applicable to move_order_stop order
    moveTriggerPx String Trigger price
    Only applicable to move_order_stop order
    reduceOnly String Whether the order can only reduce the position size. Valid options: true or false.
    quickMgnType String Quick Margin type, Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    last String Last filled price while placing
    failCode String It represents that the reason that algo order fails to trigger. There will be value when the state is order_failed, e.g. 51008;
    For this endpoint, it always is "".
    algoClOrdId String Client-supplied Algo ID
    amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    attachAlgoOrds Array of object Attached SL/TP orders info
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    > attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > tpTriggerPx String Take-profit trigger price
    If you fill in this parameter, you should fill in the take-profit order price as well.
    > tpTriggerPxType String Take-profit trigger price type
    last: last price
    index: index price
    mark: mark price
    The default is last
    > tpOrdPx String Take-profit order price
    If you fill in this parameter, you should fill in the take-profit trigger price as well.
    If the price is -1, take-profit will be executed at the market price.
    > slTriggerPx String Stop-loss trigger price
    If you fill in this parameter, you should fill in the stop-loss order price.
    > slTriggerPxType String Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark price
    The default is last
    > slOrdPx String Stop-loss order price
    If you fill in this parameter, you should fill in the stop-loss trigger price.
    If the price is -1, stop-loss will be executed at the market price.
    cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    GET / Algo order history

    Retrieve a list of all algo orders under the current account in the last 3 months.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/trade/orders-algo-history

    Request Example

    GET /api/v5/trade/orders-algo-history?algoId=681096944655273984&ordType=trigger
    
    import okx.Trade as Trade
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
    
    # Retrieve a list of all one-way stop algo orders
    result = tradeAPI.order_algos_history(
        state="effective",
        ordType="conditional"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ordType String Yes Order type
    conditional: One-way stop order
    oco: One-cancels-the-other order
    trigger: Trigger order
    move_order_stop: Trailing order
    state String Conditional State
    effective
    canceled
    order_failed
    Either state or algoId is required
    algoId String Conditional Algo ID
    Either state or algoId is required.
    instType String No Instrument type
    SPOT
    instId String No Instrument ID, e.g. BTC-USDT
    after String No Pagination of data to return records earlier than the requested algoId
    before String No Pagination of data to return records new than the requested algoId
    limit String No Number of results per request. The maximum is 100. The default is 100

    Response Example

    {
        "code": "0",
        "data": [
            {
                "activePx": "",
                "actualPx": "",
                "actualSide": "buy",
                "actualSz": "0",
                "algoClOrdId": "",
                "algoId": "681096944655273984",
                "amendPxOnTriggerType": "",
                "attachAlgoOrds": [],
                "cTime": "1708658165774",
                "callbackRatio": "",
                "callbackSpread": "",
                "ccy": "",
                "clOrdId": "",
                "closeFraction": "",
                "failCode": "",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "last": "51014.6",
                "lever": "",
                "moveTriggerPx": "",
                "ordId": "",
                "ordIdList": [],
                "ordPx": "-1",
                "ordType": "trigger",
                "posSide": "net",
                "pxLimit": "",
                "pxSpread": "",
                "pxVar": "",
                "quickMgnType": "",
                "reduceOnly": "false",
                "side": "buy",
                "slOrdPx": "",
                "slTriggerPx": "",
                "slTriggerPxType": "",
                "state": "canceled",
                "sz": "10",
                "szLimit": "",
                "tag": "",
                "tdMode": "cash",
                "tgtCcy": "",
                "timeInterval": "",
                "tpOrdPx": "",
                "tpTriggerPx": "",
                "tpTriggerPxType": "",
                "triggerPx": "100",
                "triggerPxType": "last",
                "triggerTime": ""
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    ccy String Margin currency
    Only applicable to cross MARGIN orders in Single-currency margin.
    ordId String Latest order ID
    ordIdList String Order ID list. There will be multiple order IDs when there is TP/SL splitting order.
    algoId String Algo ID
    clOrdId String Client Order ID as assigned by the client
    sz String Quantity to buy or sell
    closeFraction String Fraction of position to be closed when the algo order is triggered
    ordType String Order type
    side String Order side
    posSide String Position side
    tdMode String Trade mode
    tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    state String State
    effective
    canceled
    order_failed
    partially_failed
    lever String Leverage, from 0.01 to 125.
    Only applicable to MARGIN/FUTURES/SWAP
    tpTriggerPx String Take-profit trigger price.
    tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    tpOrdPx String Take-profit order price.
    slTriggerPx String Stop-loss trigger price.
    slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    slOrdPx String Stop-loss order price.
    triggerPx String trigger price.
    triggerPxType String trigger price type.
    last: last price
    index: index price
    mark: mark price
    ordPx String Order price
    actualSz String Actual order quantity
    actualPx String Actual order price
    tag String Order tag
    actualSide String Actual trigger side, tp: take profit sl: stop loss
    triggerTime String Trigger time, Unix timestamp format in milliseconds, e.g. 1597026383085
    pxVar String Price ratio
    Only applicable to iceberg order or twap order
    pxSpread String Price variance
    Only applicable to iceberg order or twap order
    szLimit String Average amount
    Only applicable to iceberg order or twap order
    pxLimit String Price Limit
    Only applicable to iceberg order or twap order
    timeInterval String Time interval
    Only applicable to twap order
    callbackRatio String Callback price ratio
    Only applicable to move_order_stop order
    callbackSpread String Callback price variance
    Only applicable to move_order_stop order
    activePx String Active price
    Only applicable to move_order_stop order
    moveTriggerPx String Trigger price
    Only applicable to move_order_stop order
    reduceOnly String Whether the order can only reduce the position size. Valid options: true or false.
    quickMgnType String Quick Margin type, Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    last String Last filled price while placing
    failCode String It represents that the reason that algo order fails to trigger. It is "" when the state is effective/canceled. There will be value when the state is order_failed, e.g. 51008;
    Only applicable to Stop Order, Trailing Stop Order, Trigger order.
    algoClOrdId String Client Algo Order ID as assigned by the client.
    amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    attachAlgoOrds Array of object Attached SL/TP orders info
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    > attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    > tpTriggerPx String Take-profit trigger price
    If you fill in this parameter, you should fill in the take-profit order price as well.
    > tpTriggerPxType String Take-profit trigger price type
    last: last price
    index: index price
    mark: mark price
    The default is last
    > tpOrdPx String Take-profit order price
    If you fill in this parameter, you should fill in the take-profit trigger price as well.
    If the price is -1, take-profit will be executed at the market price.
    > slTriggerPx String Stop-loss trigger price
    If you fill in this parameter, you should fill in the stop-loss order price.
    > slTriggerPxType String Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark price
    The default is last
    > slOrdPx String Stop-loss order price
    If you fill in this parameter, you should fill in the stop-loss trigger price.
    If the price is -1, stop-loss will be executed at the market price.
    cTime String Creation time Unix timestamp format in milliseconds, e.g. 1597026383085

    WS / Algo orders channel

    Retrieve algo orders (includes trigger order, oco order, conditional order). Data will not be pushed when first subscribed. Data will only be pushed when there are order updates.

    Request Example : single

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "orders-algo",
          "instType": "ANY"
        }
      ]
    }
    

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "orders-algo",
          "instType": "ANY"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    orders-algo
    > instType String Yes Instrument type
    ANY
    > instId String No Instrument ID

    Successful Response Example : single

    {
      "event": "subscribe",
      "arg": {
        "channel": "orders-algo",
        "instType": "ANY"
      },
      "connId": "a4d3ae55"
    }
    

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "orders-algo",
        "instType": "ANY"
      },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"orders-algo\", \"instType\" : \"FUTURES\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    > instType String Yes Instrument type
    ANY
    > instId String No Instrument ID
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example: single

    {
        "arg": {
            "channel": "orders-algo",
            "uid": "77982378738415879",
            "instType": "ANY"
        },
        "data": [{
            "actualPx": "0",
            "actualSide": "",
            "actualSz": "0",
            "algoClOrdId": "",
            "algoId": "581878926302093312",
            "attachAlgoOrds": [],
            "amendResult": "",
            "cTime": "1685002746818",
            "ccy": "",
            "clOrdId": "",
            "closeFraction": "",
            "failCode": "",
            "instId": "BTC-USDC",
            "instType": "SPOT",
            "last": "26174.8",
            "lever": "0",
            "notionalUsd": "11.0",
            "ordId": "",
            "ordIdList": [],
            "ordPx": "",
            "ordType": "conditional",
            "posSide": "",
            "quickMgnType": "",
            "reduceOnly": "false",
            "reqId": "",
            "side": "buy",
            "slOrdPx": "",
            "slTriggerPx": "",
            "slTriggerPxType": "",
            "state": "live",
            "sz": "11",
            "tag": "",
            "tdMode": "cross",
            "tgtCcy": "quote_ccy",
            "tpOrdPx": "-1",
            "tpTriggerPx": "1",
            "tpTriggerPxType": "last",
            "triggerPx": "",
            "triggerTime": "",
            "amendPxOnTriggerType": "0"
        }]
    }
    

    Response parameters when data is pushed.

    Parameter Type Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > uid String User Identifier
    > instType String Instrument type
    > instFamily String Instrument family
    > instId String Instrument ID
    data Array Subscribed data
    > instType String Instrument type
    > instId String Instrument ID
    > ccy String Margin currency
    Only applicable to cross MARGIN orders in Single-currency margin.
    > ordId String Latest order ID, the order ID associated with the algo order.
    > ordIdList String Order ID list. There will be multiple order IDs when there is TP/SL splitting order.
    > algoId String Algo ID
    > clOrdId String Client Order ID as assigned by the client
    > sz String Quantity to buy or sell.
    SPOT/MARGIN: in the unit of currency. FUTURES/SWAP/OPTION: in the unit of contract.
    > ordType String Order type
    conditional: One-way stop order
    oco: One-cancels-the-other order
    trigger: Trigger order
    > side String Order side
    buy
    sell
    > posSide String Position side
    net
    long or short
    Only applicable to FUTURES/SWAP
    > tdMode String Trade mode
    cross: cross
    isolated: isolated
    cash: cash
    > tgtCcy String Order quantity unit setting for sz
    base_ccy: Base currency ,quote_ccy: Quote currency
    Only applicable to SPOT Market Orders
    Default is quote_ccy for buy, base_ccy for sell
    > lever String Leverage, from 0.01 to 125.
    Only applicable to MARGIN/FUTURES/SWAP
    > state String Order status
    live: to be effective
    effective: effective
    canceled: canceled
    order_failed: order failed
    partially_failed: partially failed
    > tpTriggerPx String Take-profit trigger price.
    > tpTriggerPxType String Take-profit trigger price type
    last: last price
    index: index price
    mark: mark price
    > tpOrdPx String Take-profit order price.
    > slTriggerPx String Stop-loss trigger price.
    > slTriggerPxType String Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark price
    > slOrdPx String Stop-loss order price.
    > triggerPx String Trigger price
    > triggerPxType String Trigger price type.
    last: last price
    index: index price
    mark: mark price
    > ordPx String Order price
    > last String Last filled price while placing
    > actualSz String Actual order quantity
    > actualPx String Actual order price
    > notionalUsd String Estimated national value in USD of order
    > tag String Order tag
    > actualSide String Actual trigger side
    > triggerTime String Trigger time, Unix timestamp format in milliseconds, e.g. 1597026383085
    > reduceOnly String Whether the order can only reduce the position size. Valid options: true or false.
    > failCode String It represents that the reason that algo order fails to trigger. It is "" when the state is effective/canceled. There will be value when the state is order_failed, e.g. 51008;
    Only applicable to Stop Order, Trailing Stop Order, Trigger order.
    > algoClOrdId String Client Algo Order ID as assigned by the client.
    > cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
    > reqId String Client Request ID as assigned by the client for order amendment. "" will be returned if there is no order amendment.
    > amendResult String The result of amending the order
    -1: failure
    0: success
    > amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    > attachAlgoOrds Array of object Attached SL/TP orders info
    Applicable to Single-currency margin/Multi-currency margin/Portfolio margin
    >> attachAlgoClOrdId String Client-supplied Algo ID when placing order attaching TP/SL.
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely.
    >> tpTriggerPx String Take-profit trigger price
    If you fill in this parameter, you should fill in the take-profit order price as well.
    >> tpTriggerPxType String Take-profit trigger price type
    last: last price
    index: index price
    mark: mark price
    The default is last
    >> tpOrdPx String Take-profit order price
    If you fill in this parameter, you should fill in the take-profit trigger price as well.
    If the price is -1, take-profit will be executed at the market price.
    >> slTriggerPx String Stop-loss trigger price
    If you fill in this parameter, you should fill in the stop-loss order price.
    >> slTriggerPxType String Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark price
    The default is last
    >> slOrdPx String Stop-loss order price
    If you fill in this parameter, you should fill in the stop-loss trigger price.
    If the price is -1, stop-loss will be executed at the market price.

    Market Data

    The API endpoints of Market Data do not require authentication.

    GET / Tickers

    Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/tickers

    Request Example

    GET /api/v5/market/tickers?instType=SPOT
    
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours
    result = marketDataAPI.get_tickers(
        instType="SPOT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String Yes Instrument type
    SPOT

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "instType": "SPOT",
                "instId": "BTC-USDT",
                "last": "51230",
                "lastSz": "0.18531491",
                "askPx": "51229.4",
                "askSz": "2.1683067",
                "bidPx": "51229.3",
                "bidSz": "0.28249897",
                "open24h": "51635.7",
                "high24h": "52080",
                "low24h": "50936",
                "volCcy24h": "539658490.410419122",
                "vol24h": "10476.2229261",
                "ts": "1708669508505",
                "sodUtc0": "51290.1",
                "sodUtc8": "51602.4"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    last String Last traded price
    lastSz String Last traded size
    askPx String Best ask price
    askSz String Best ask size
    bidPx String Best bid price
    bidSz String Best bid size
    open24h String Open price in the past 24 hours
    high24h String Highest price in the past 24 hours
    low24h String Lowest price in the past 24 hours
    volCcy24h String 24h trading volume
    If it is SPOT, the value is the quantity in quote currency.
    vol24h String 24h trading volume
    If it is SPOT, the value is the quantity in base currency.
    sodUtc0 String Open price in the UTC 0
    sodUtc8 String Open price in the UTC 8
    ts String Ticker data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    GET / Ticker

    Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/ticker

    Request Example

    GET /api/v5/market/ticker?instId=BTC-USDT
    
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours
    result = marketDataAPI.get_ticker(
        instId="BTC-USDT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [
            {
                "instType": "SPOT",
                "instId": "BTC-USDT",
                "last": "51240",
                "lastSz": "0.49011124",
                "askPx": "51240",
                "askSz": "0.64278176",
                "bidPx": "51239.9",
                "bidSz": "1.68139044",
                "open24h": "51695.6",
                "high24h": "52080",
                "low24h": "50936",
                "volCcy24h": "539533972.680195094",
                "vol24h": "10474.12353007",
                "ts": "1708669925904",
                "sodUtc0": "51290.1",
                "sodUtc8": "51602.4"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID
    last String Last traded price
    lastSz String Last traded size
    askPx String Best ask price
    askSz String Best ask size
    bidPx String Best bid price
    bidSz String Best bid size
    open24h String Open price in the past 24 hours
    high24h String Highest price in the past 24 hours
    low24h String Lowest price in the past 24 hours
    volCcy24h String 24h trading volume
    If it is SPOT, the value is the quantity in quote currency.
    vol24h String 24h trading volume
    If it is SPOT, the value is the quantity in base currency.
    sodUtc0 String Open price in the UTC 0
    sodUtc8 String Open price in the UTC 8
    ts String Ticker data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085.

    GET / Order book

    Retrieve order book of the instrument.

    Rate Limit: 40 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/books

    Request Example

    GET /api/v5/market/books?instId=BTC-USDT
    
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve order book of the instrument
    result = marketDataAPI.get_orderbook(
        instId="BTC-USDT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    sz String No Order book depth per side. Maximum 400, e.g. 400 bids + 400 asks
    Default returns to 1 depth data

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [
            {
                "asks": [
                    [
                        "41006.8",
                        "0.60038921",
                        "0",
                        "1"
                    ]
                ],
                "bids": [
                    [
                        "41006.3",
                        "0.30178218",
                        "0",
                        "2"
                    ]
                ],
                "ts": "1629966436396"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    asks Array Order book on sell side
    bids Array Order book on buy side
    ts String Order book generation time

    GET / Candlesticks

    Retrieve the candlestick charts. This endpoint can retrieve the latest 1,440 data entries. Charts are returned in groups based on the requested bar.

    Rate Limit: 40 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/candles

    Request Example

    GET /api/v5/market/candles?instId=BTC-USDT
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve the candlestick charts
    result = marketDataAPI.get_candlesticks(
        instId="BTC-USDT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    bar String No Bar size, the default is 1m
    e.g. [1m/3m/5m/15m/30m/1H/2H/4H]
    Hong Kong time opening price k-line: [6H/12H/1D/2D/3D/1W/1M/3M]
    UTC time opening price k-line: [/6Hutc/12Hutc/1Dutc/2Dutc/3Dutc/1Wutc/1Mutc/3Mutc]
    after String No Pagination of data to return records earlier than the requested ts
    before String No Pagination of data to return records newer than the requested ts. The latest data will be returned when using before individually
    limit String No Number of results per request. The maximum is 300. The default is 100.

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
         [
            "1597026383085",
            "3.721",
            "3.743",
            "3.677",
            "3.708",
            "8422410",
            "22698348.04828491",
            "12698348.04828491",
            "0"
        ],
        [
            "1597026383085",
            "3.731",
            "3.799",
            "3.494",
            "3.72",
            "24912403",
            "67632347.24399722",
            "37632347.24399722",
            "1"
        ]
        ]
    }
    

    Response Parameters

    Parameter Type Description
    ts String Opening time of the candlestick, Unix timestamp format in milliseconds, e.g. 1597026383085
    o String Open price
    h String highest price
    l String Lowest price
    c String Close price
    vol String Trading volume
    If it is SPOT, the value is the quantity in base currency.
    volCcy String Trading volume
    If it is SPOT, the value is the quantity in quote currency.
    volCcyQuote String Trading volume, the value is the quantity in quote currency
    e.g. The unit is USDT for BTC-USDT
    confirm String The state of candlesticks.
    0: K line is uncompleted
    1: K line is completed

    GET / Candlesticks history

    Retrieve history candlestick charts from recent years(It is last 3 months supported for 1s candlestick).

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/history-candles

    Request Example

    GET /api/v5/market/history-candles?instId=BTC-USDT
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve history candlestick charts from recent years
    result = marketDataAPI.get_history_candlesticks(
        instId="BTC-USDT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    after String No Pagination of data to return records earlier than the requested ts
    before String No Pagination of data to return records newer than the requested ts. The latest data will be returned when using before individually
    bar String No Bar size, the default is 1m
    e.g. [1s/1m/3m/5m/15m/30m/1H/2H/4H]
    Hong Kong time opening price k-line: [6H/12H/1D/2D/3D/1W/1M/3M]
    UTC time opening price k-line: [6Hutc/12Hutc/1Dutc/2Dutc/3Dutc/1Wutc/1Mutc/3Mutc]
    limit String No Number of results per request. The maximum is 100. The default is 100.

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
         [
            "1597026383085",
            "3.721",
            "3.743",
            "3.677",
            "3.708",
            "8422410",
            "22698348.04828491",
            "12698348.04828491",
            "1"
        ],
        [
            "1597026383085",
            "3.731",
            "3.799",
            "3.494",
            "3.72",
            "24912403",
            "67632347.24399722",
            "37632347.24399722",
            "1"
        ]
        ]
    }
    

    Response Parameters

    Parameter Type Description
    ts String Opening time of the candlestick, Unix timestamp format in milliseconds, e.g. 1597026383085
    o String Open price
    h String Highest price
    l String Lowest price
    c String Close price
    vol String Trading volume
    If it is SPOT, the value is the quantity in base currency.
    volCcy String Trading volume
    If it is SPOT, the value is the quantity in quote currency.
    volCcyQuote String Trading volume, the value is the quantity in quote currency
    e.g. The unit is USDT for BTC-USDT
    confirm String The state of candlesticks.
    0: K line is uncompleted
    1: K line is completed

    GET / Trades

    Retrieve the recent transactions of an instrument.

    Rate Limit: 100 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/trades

    Request Example

    GET /api/v5/market/trades?instId=BTC-USDT
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve the recent transactions of an instrument
    result = marketDataAPI.get_trades(
        instId="BTC-USDT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    limit String No Number of results per request. The maximum is 500; The default is 100

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [
            {
                "instId": "BTC-USDT",
                "side": "sell",
                "sz": "0.00001",
                "px": "29963.2",
                "tradeId": "242720720",
                "ts": "1654161646974"
            },
            {
                "instId": "BTC-USDT",
                "side": "sell",
                "sz": "0.00001",
                "px": "29964.1",
                "tradeId": "242720719",
                "ts": "1654161641568"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    tradeId String Trade ID
    px String Trade price
    sz String Trade quantity
    For spot trading, the unit is base currency
    side String Trade side
    buy
    sell
    ts String Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085.

    GET / Trades history

    Retrieve the recent transactions of an instrument from the last 3 months with pagination.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/history-trades

    Request Example

    GET /api/v5/market/history-trades?instId=BTC-USDT
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve the recent transactions of an instrument from the last 3 months with pagination
    result = marketDataAPI.get_history_trades(
        instId="BTC-USD-SWAP"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    type String No Pagination Type
    1: tradeId 2: timestamp
    The default is 1
    after String No Pagination of data to return records earlier than the requested tradeId or ts.
    before String No Pagination of data to return records newer than the requested tradeId.
    Do not support timestamp for pagination. The latest data will be returned when using before individually
    limit String No Number of results per request. The maximum and default both are 100

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [
            {
                "instId": "BTC-USDT",
                "side": "sell",
                "sz": "0.00001",
                "px": "29963.2",
                "tradeId": "242720720",
                "ts": "1654161646974"
            },
            {
                "instId": "BTC-USDT",
                "side": "sell",
                "sz": "0.00001",
                "px": "29964.1",
                "tradeId": "242720719",
                "ts": "1654161641568"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    tradeId String Trade ID
    px String Trade price
    sz String Trade quantity
    side String Trade side
    buy
    sell
    ts String Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085.

    GET / 24H total volume

    The 24-hour trading volume is calculated on a rolling basis.

    Rate Limit: 2 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/platform-24-volume

    Request Example

    GET /api/v5/market/platform-24-volume
    
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve 24 total volume
    result = marketDataAPI.get_volume()
    print(result)
    

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
         {
             "volCny": "230900886396766",
             "volUsd": "34462818865189",
             "ts": "1657856040389"
         }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    volUsd String 24-hour total trading volume from the order book trading in "USD"
    volCny String 24-hour total trading volume from the order book trading in "CNY"
    ts String Data return time, Unix timestamp format in milliseconds, e.g. 1597026383085

    WS / Tickers channel

    Retrieve the last traded price, bid price, ask price and 24-hour trading volume of instruments.
    The fastest rate is 1 update/100ms. There will be no update if the event is not triggered. The events which can trigger update: trade, the change on best ask/bid.

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "tickers",
          "instId": "BTC-USDT"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    tickers
    > instId String Yes Instrument ID

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "tickers",
        "instId": "BTC-USDT"
      },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"tickers\", \"instId\" : \"LTC-USD-200327\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    > instId String Yes Instrument ID
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
      "arg": {
        "channel": "tickers",
        "instId": "BTC-USDT"
      },
      "data": [
        {
          "instType": "SPOT",
          "instId": "BTC-USDT",
          "last": "9999.99",
          "lastSz": "0.1",
          "askPx": "9999.99",
          "askSz": "11",
          "bidPx": "8888.88",
          "bidSz": "5",
          "open24h": "9000",
          "high24h": "10000",
          "low24h": "8888.88",
          "volCcy24h": "2222",
          "vol24h": "2222",
          "sodUtc0": "2222",
          "sodUtc8": "2222",
          "ts": "1597026383085"
        }
      ]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > instId String Instrument ID
    data Array Subscribed data
    > instType String Instrument type
    > instId String Instrument ID
    > last String Last traded price
    > lastSz String Last traded size
    > askPx String Best ask price
    > askSz String Best ask size
    > bidPx String Best bid price
    > bidSz String Best bid size
    > open24h String Open price in the past 24 hours
    > high24h String Highest price in the past 24 hours
    > low24h String Lowest price in the past 24 hours
    > volCcy24h String 24h trading volume
    If it is SPOT, the value is the quantity in quote currency.
    > vol24h String 24h trading volume
    If it is SPOT, the value is the quantity in base currency.
    > sodUtc0 String Open price in the UTC 0
    > sodUtc8 String Open price in the UTC 8
    > ts String Ticker data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    WS / Candlesticks channel

    Retrieve the candlesticks data of an instrument. the push frequency is the fastest interval 1 second push the data.

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "candle1D",
          "instId": "BTC-USDT"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    channel String Yes Channel name
    candle3M candle1M
    candle1W
    candle1D candle2D candle3D candle5D
    candle12H candle6H candle4H candle2H candle1H
    candle30m candle15m candle5m candle3m candle1m candle1s
    candle3Mutc candle1Mutc candle1Wutc candle1Dutc candle2Dutc candle3Dutc candle5Dutc candle12Hutc candle6Hutc
    instId String Yes Instrument ID

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "candle1D",
        "instId": "BTC-USDT"
      },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"candle1D\", \"instId\" : \"BTC-USD-191227\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    channel String yes channel name
    instId String Yes Instrument ID
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
      "arg": {
        "channel": "candle1D",
        "instId": "BTC-USDT"
      },
      "data": [
        [
          "1597026383085",
          "8533.02",
          "8553.74",
          "8527.17",
          "8548.26",
          "45247",
          "529.5858061",
          "5529.5858061",
          "0"
        ]
      ]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > instId String Instrument ID
    data Array Subscribed data
    > ts String Opening time of the candlestick, Unix timestamp format in milliseconds, e.g. 1597026383085
    > o String Open price
    > h String highest price
    > l String Lowest price
    > c String Close price
    > vol String Trading volume
    If it is SPOT, the value is the quantity in base currency.
    > volCcy String Trading volume
    If it is SPOT, the value is the quantity in quote currency.
    > volCcyQuote String Trading volume, the value is the quantity in quote currency
    e.g. The unit is USDT for BTC-USDT
    > confirm String The state of candlesticks
    0: K line is uncompleted
    1: K line is completed

    WS / Trades channel

    Retrieve the recent trades data. Data will be pushed whenever there is a trade. Every update may aggregate multiple trades.

    The message is sent only once per taker order, per filled price. The count field is used to represent the number of aggregated matches.

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "trades",
          "instId": "BTC-USDT"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    trades
    > instId String Yes Instrument ID

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
          "channel": "trades",
          "instId": "BTC-USDT"
      },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"trades\"\"instId\" : \"BTC-USD-191227\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    > instId String Yes Instrument ID
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
      "arg": {
        "channel": "trades",
        "instId": "BTC-USDT"
      },
      "data": [
        {
          "instId": "BTC-USDT",
          "tradeId": "130639474",
          "px": "42219.9",
          "sz": "0.12060306",
          "side": "buy",
          "ts": "1630048897897",
          "count": "3"
        }
      ]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > instId String Instrument ID
    data Array Subscribed data
    > instId String Instrument ID, e.g. BTC-USDT
    > tradeId String The last trade ID in the trades aggregation
    > px String Trade price
    > sz String Trade size
    > side String Trade direction
    buy
    sell
    > ts String Filled time, Unix timestamp format in milliseconds, e.g. 1597026383085
    > count String The count of trades aggregated

    WS / All trades channel

    Retrieve the recent trades data. Data will be pushed whenever there is a trade. Every update contain only one trade.

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "trades-all",
          "instId": "BTC-USDT"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    trades-all
    > instId String Yes Instrument ID

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
          "channel": "trades-all",
          "instId": "BTC-USDT"
        },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"trades-all\"\"instId\" : \"BTC-USD-191227\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    > instId String Yes Instrument ID
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
      "arg": {
        "channel": "trades-all",
        "instId": "BTC-USDT"
      },
      "data": [
        {
          "instId": "BTC-USDT",
          "tradeId": "130639474",
          "px": "42219.9",
          "sz": "0.12060306",
          "side": "buy",
          "ts": "1630048897897"
        }
      ]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > instId String Instrument ID
    data Array Subscribed data
    > instId String Instrument ID, e.g. BTC-USDT
    > tradeId String Trade ID
    > px String Trade price
    > sz String Trade size
    > side String Trade direction
    buy
    sell
    > ts String Filled time, Unix timestamp format in milliseconds, e.g. 1597026383085

    WS / Order book channel

    Retrieve order book data.

    Use books for 400 depth levels, books5 for 5 depth levels, bbo-tbt tick-by-tick 1 depth level, books50-l2-tbt tick-by-tick 50 depth levels, and books-l2-tbt for tick-by-tick 400 depth levels.

    Identity verification refers to Login

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "books",
          "instId": "BTC-USDT"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    books books5 books50-l2-tbt books-l2-tbt
    > instId String Yes Instrument ID

    Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "books",
        "instId": "BTC-USDT"
      },
      "connId": "a4d3ae55"
    }
    

    Failure example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"books\"\"instId\" : \"BTC-USD-191227\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    > instId String Yes Instrument ID
    msg String No Error message
    code String No Error code
    connId String Yes WebSocket connection ID

    Push Data Example: Full Snapshot

    {
      "arg": {
        "channel": "books",
        "instId": "BTC-USDT"
      },
      "action": "snapshot",
      "data": [
        {
          "asks": [
            ["8476.98", "415", "0", "13"],
            ["8477", "7", "0", "2"],
            ["8477.34", "85", "0", "1"],
            ["8477.56", "1", "0", "1"],
            ["8505.84", "8", "0", "1"],
            ["8506.37", "85", "0", "1"],
            ["8506.49", "2", "0", "1"],
            ["8506.96", "100", "0", "2"]
          ],
          "bids": [
            ["8476.97", "256", "0", "12"],
            ["8475.55", "101", "0", "1"],
            ["8475.54", "100", "0", "1"],
            ["8475.3", "1", "0", "1"],
            ["8447.32", "6", "0", "1"],
            ["8447.02", "246", "0", "1"],
            ["8446.83", "24", "0", "1"],
            ["8446", "95", "0", "3"]
          ],
          "ts": "1597026383085",
          "checksum": -855196043,
          "prevSeqId": -1,
          "seqId": 123456
        }
      ]
    }
    

    Push Data Example: Incremental Data

    {
      "arg": {
        "channel": "books",
        "instId": "BTC-USDT"
      },
      "action": "update",
      "data": [
        {
          "asks": [
            ["8476.98", "415", "0", "13"],
            ["8477", "7", "0", "2"],
            ["8477.34", "85", "0", "1"],
            ["8477.56", "1", "0", "1"],
            ["8505.84", "8", "0", "1"],
            ["8506.37", "85", "0", "1"],
            ["8506.49", "2", "0", "1"],
            ["8506.96", "100", "0", "2"]
          ],
          "bids": [
            ["8476.97", "256", "0", "12"],
            ["8475.55", "101", "0", "1"],
            ["8475.54", "100", "0", "1"],
            ["8475.3", "1", "0", "1"],
            ["8447.32", "6", "0", "1"],
            ["8447.02", "246", "0", "1"],
            ["8446.83", "24", "0", "1"],
            ["8446", "95", "0", "3"]
          ],
          "ts": "1597026383085",
          "checksum": -855196043,
          "prevSeqId": 123456,
          "seqId": 123457
        }
      ]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > instId String Instrument ID
    action String Push data action, incremental data or full snapshot.
    snapshot: full
    update: incremental
    data Array Subscribed data
    > asks Array Order book on sell side
    > bids Array Order book on buy side
    > ts String Order book generation time, Unix timestamp format in milliseconds, e.g. 1597026383085
    > checksum Integer Checksum, implementation details below
    > prevSeqId Integer Sequence ID of the last sent message. Only applicable to books, books-l2-tbt, books50-l2-tbt
    > seqId Integer Sequence ID of the current message, implementation details below

    Sequence ID

    seqId is the sequence ID of the market data published. The set of sequence ID received by users is the same if users are connecting to the same channel through multiple websocket connections. Each instId has an unique set of sequence ID. Users can use prevSeqId and seqId to build the message sequencing for incremental order book updates. Generally the value of seqId is larger than prevSeqId. The prevSeqId in the new message matches with seqId of the previous message. The smallest possible sequence ID value is 0, except in snapshot messages where the prevSeqId is always -1.

    Exceptions:
    1. If there are no updates to the depth for an extended period, OKX will send a message with 'asks': [], 'bids': [] to inform users that the connection is still active. seqId is the same as the last sent message and prevSeqId equals to seqId. 2. The sequence number may be reset due to maintenance, and in this case, users will receive an incremental message with seqId smaller than prevSeqId. However, subsequent messages will follow the regular sequencing rule.

    Example
    1. Snapshot message: prevSeqId = -1, seqId = 10
    2. Incremental message 1 (normal update): prevSeqId = 10, seqId = 15
    3. Incremental message 2 (no update): prevSeqId = 15, seqId = 15
    4. Incremental message 3 (sequence reset): prevSeqId = 15, seqId = 3
    5. Incremental message 4 (normal update): prevSeqId = 3, seqId = 5

    Checksum

    This mechanism can assist users in checking the accuracy of depth data.

    Merging incremental data into full data

    After subscribing to the incremental load push (such as books 400 levels) of Order Book Channel, users first receive the initial full load of market depth. After the incremental load is subsequently received, update the local full load.

    1. If there is the same price, compare the size. If the size is 0, delete this depth data. If the size changes, replace the original data.
    2. If there is no same price, sort by price (bid in descending order, ask in ascending order), and insert the depth information into the full load.
    Calculate Checksum

    Use the first 25 bids and asks in the full load to form a string (where a colon connects the price and size in an ask or a bid), and then calculate the CRC32 value (32-bit signed integer).

    Calculate Checksum

    1. More than 25 levels of bid and ask
    A full load of market depth (only 2 levels of data are shown here, while 25 levels of data should actually be intercepted):
    
    {
        "bids": [
            ["3366.1", "7", "0", "3"],
            ["3366", "6", "3", "4"]
        ],
        "asks": [
            ["3366.8", "9", "10", "3"],
            ["3368", "8", "3", "4"]
        ]
    }
    
    Check string:
    "3366.1:7:3366.8:9:3366:6:3368:8"
    
    2. Less than 25 levels of bid or ask
    A full load of market depth:
    
    {
        "bids": [
            ["3366.1", "7", "0", "3"]
        ],
        "asks": [
            ["3366.8", "9", "10", "3"],
            ["3368", "8", "3", "4"],
            ["3372", "8", "3", "4"]
        ]
    }
    
    Check string:
    "3366.1:7:3366.8:9:3368:8:3372:8"
    
    1. When the bid and ask depth data exceeds 25 levels, each of them will intercept 25 levels of data, and the string to be checked is queued in a way that the bid and ask depth data are alternately arranged.
      Such as: bid[price:size]:ask[price:size]:bid[price:size]:ask[price:size]...
    2. When the bid or ask depth data is less than 25 levels, the missing depth data will be ignored.
      Such as: bid[price:size]:ask[price:size]:asks[price:size]:asks[price:size]...

    Push Data Example of bbo-tbt channel

    {
      "arg": {
        "channel": "bbo-tbt",
        "instId": "BCH-USDT-SWAP"
      },
      "data": [
        {
          "asks": [
            [
              "111.06","55154","0","2"
            ]
          ],
          "bids": [
            [
              "111.05","57745","0","2"
            ]
          ],
          "ts": "1670324386802",
          "seqId": 363996337
        }
      ]
    }
    

    Push Data Example of books5 channel

    {
      "arg": {
        "channel": "books5",
        "instId": "BCH-USDT-SWAP"
      },
      "data": [
        {
          "asks": [
            ["111.06","55154","0","2"],
            ["111.07","53276","0","2"],
            ["111.08","72435","0","2"],
            ["111.09","70312","0","2"],
            ["111.1","67272","0","2"]],
          "bids": [
            ["111.05","57745","0","2"],
            ["111.04","57109","0","2"],
            ["111.03","69563","0","2"],
            ["111.02","71248","0","2"],
            ["111.01","65090","0","2"]],
          "instId": "BCH-USDT-SWAP",
          "ts": "1670324386802",
          "seqId": 363996337
        }
      ]
    }
    

    Public Data

    The API endpoints of Public Data do not require authentication.

    REST API

    Get instruments

    Retrieve a list of instruments with open contracts.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: IP + instrumentType

    HTTP Request

    GET /api/v5/public/instruments

    Request Example

    GET /api/v5/public/instruments?instType=SPOT
    
    import okx.PublicData as PublicData
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    publicDataAPI = PublicData.PublicAPI(flag=flag)
    
    # Retrieve a list of instruments with open contracts
    result = publicDataAPI.get_instruments(
        instType="SPOT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String Yes Instrument type
    SPOT
    instId String No Instrument ID

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
          {
                "alias": "",
                "baseCcy": "BTC",
                "category": "1",
                "ctMult": "",
                "ctType": "",
                "ctVal": "",
                "ctValCcy": "",
                "expTime": "",
                "instFamily": "",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "lever": "10",
                "listTime": "1606468572000",
                "lotSz": "0.00000001",
                "maxIcebergSz": "9999999999.0000000000000000",
                "maxLmtAmt": "1000000",
                "maxLmtSz": "9999999999",
                "maxMktAmt": "1000000",
                "maxMktSz": "",
                "maxStopSz": "",
                "maxTriggerSz": "9999999999.0000000000000000",
                "maxTwapSz": "9999999999.0000000000000000",
                "minSz": "0.00001",
                "optType": "",
                "quoteCcy": "USDT",
                "settleCcy": "",
                "state": "live",
                "stk": "",
                "tickSz": "0.1",
                "uly": ""
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    instType String Instrument type
    instId String Instrument ID, e.g. BTC-USDT
    uly String Underlying, e.g. BTC-USD
    Only applicable to FUTURES/SWAP/OPTION
    instFamily String Instrument family, e.g. BTC-USD
    Only applicable to FUTURES/SWAP/OPTION
    category String Currency category. Note: this parameter is already deprecated
    baseCcy String Base currency, e.g. BTC inBTC-USDT
    Only applicable to SPOT/MARGIN
    quoteCcy String Quote currency, e.g. USDT in BTC-USDT
    Only applicable to SPOT/MARGIN
    settleCcy String Settlement and margin currency, e.g. BTC
    Only applicable to FUTURES/SWAP/OPTION
    ctVal String Contract value
    Only applicable to FUTURES/SWAP/OPTION
    ctMult String Contract multiplier
    Only applicable to FUTURES/SWAP/OPTION
    ctValCcy String Contract value currency
    Only applicable to FUTURES/SWAP/OPTION
    optType String Option type, C: Call P: put
    Only applicable to OPTION
    stk String Strike price
    Only applicable to OPTION
    listTime String Listing time, Unix timestamp format in milliseconds, e.g. 1597026383085
    expTime String Expiry time
    Applicable to SPOT/MARGIN/FUTURES/SWAP/OPTION. For FUTURES/OPTION, it is natural delivery/exercise time. It is the instrument offline time when there is SPOT/MARGIN/FUTURES/SWAP/ manual offline. Update once change.
    lever String Max Leverage,
    Not applicable to SPOT, OPTION
    tickSz String Tick size, e.g. 0.0001
    For Option, it is minimum tickSz among tick band, please use "Get option tick bands" if you want get option tickBands.
    lotSz String Lot size
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    minSz String Minimum order size
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    ctType String Contract type
    linear: linear contract
    inverse: inverse contract
    Only applicable to FUTURES/SWAP
    alias String Alias
    this_week
    next_week
    this_month
    next_month
    quarter
    next_quarter
    Only applicable to FUTURES
    Not recommended for use, users are encouraged to rely on the expTime field to determine the delivery time of the contract
    state String Instrument status
    live
    suspend
    preopen. e.g. There will be preopen before the Futures and Options new contracts state is live.
    test: Test pairs, can't be traded
    maxLmtSz String The maximum order quantity of a single limit order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    maxMktSz String The maximum order quantity of a single market order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in USDT.
    maxLmtAmt String Max USD amount for a single limit order
    maxMktAmt String Max USD amount for a single market order
    Only applicable to SPOT/MARGIN
    maxTwapSz String The maximum order quantity of a single TWAP order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    maxIcebergSz String The maximum order quantity of a single iceBerg order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    maxTriggerSz String The maximum order quantity of a single trigger order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    maxStopSz String The maximum order quantity of a single stop market order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in USDT.

    Get system time

    Retrieve API server time.

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/public/time

    Request Example

    GET /api/v5/public/time
    
    import okx.PublicData as PublicData
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    publicDataAPI = PublicData.PublicAPI(flag=flag)
    
    # Retrieve API server time
    result = publicDataAPI.get_system_time()
    print(result)
    

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
        {
            "ts":"1597026383085"
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    ts String System time, Unix timestamp format in milliseconds, e.g. 1597026383085

    Get oracle

    Get the crypto price of signing using Open Oracle smart contract.

    Rate Limit: 1 request per 5 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/open-oracle

    Request Example

    GET /api/v5/market/open-oracle
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Get the crypto price of signing using Open Oracle smart contract
    result = marketDataAPI.get_oracle()
    print(result)
    

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "messages":[
                    "0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000616d3b1400000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000e70528b800000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034254430000000000000000000000000000000000000000000000000000000000"
                ],
                "prices":{
                    "BTC":"62014"
                },
                "signatures":[
                    "0xf18330e59eaf42373c2c40f1f9e24113ba21d4ed734dd3ed3bc1d12290fa74ba5623fca1113c5d245a1202dc065e333615b90f810f12132ce4a1ecacb8c6b24a000000000000000000000000000000000000000000000000000000000000001b"
                ],
                "timestamp":"1634548500"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    messages String ABI-encoded values [kind, timestamp, key, value], where kind equals 'prices', timestamp is the time when price was obtained, key is the asset ticker (e.g. btc) and value is the asset price.
    prices String Readable asset prices
    signatures String Ethereum-compatible ECDSA signatures for each message
    timestamp String Time of latest datapoint, Unix timestamp, e.g. 1597026387

    Get exchange rate

    This interface provides the average exchange rate data for 2 weeks

    Rate Limit: 1 request per 2 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/market/exchange-rate

    Request Example

    GET /api/v5/market/exchange-rate
    
    import okx.MarketData as MarketData
    
    flag = "0"  # Production trading:0 , demo trading:1
    
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    
    # Retrieve average exchange rate data for 2 weeks
    result = marketDataAPI.get_exchange_rate()
    print(result)
    

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [
            {
                "usdCny": "7.162"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    usdCny String Exchange rate

    Get economic calendar data

    Get the macro-economic calendar data within 3 months. Historical data from 3 months ago is only available to users with trading fee tier VIP1 and above.

    Rate Limit: 1 request per 5 seconds

    Rate limit rule: IP

    HTTP Request

    GET /api/v5/public/economic-calendar

    Request Example

    GET /api/v5/public/economic-calendar
    

    Request Parameters

    Parameter Type Required Description
    region string No Country, region or entity
    afghanistan, albania, algeria, andorra, angola, antigua_and_barbuda, argentina, armenia, aruba, australia, austria, azerbaijan, bahamas, bahrain, bangladesh, barbados, belarus, belgium, belize, benin, bermuda, bhutan, bolivia, bosnia_and_herzegovina, botswana, brazil, brunei, bulgaria, burkina_faso, burundi, cambodia, cameroon, canada, cape_verde, cayman_islands, central_african_republic, chad, chile, china, colombia, comoros, congo, costa_rica, croatia, cuba, cyprus, czech_republic, denmark, djibouti, dominica, dominican_republic, east_timor, ecuador, egypt, el_salvador, equatorial_guinea, eritrea, estonia, ethiopia, euro_area, european_union, faroe_islands, fiji, finland, france, g20, g7, gabon, gambia, georgia, germany, ghana, greece, greenland, grenada, guatemala, guinea, guinea_bissau, guyana, hungary, haiti, honduras, hong_kong, hungary, imf, indonesia, iceland, india, indonesia, iran, iraq, ireland, isle_of_man, israel, italy, ivory_coast, jamaica, japan, jordan, kazakhstan, kenya, kiribati, kosovo, kuwait, kyrgyzstan, laos, latvia, lebanon, lesotho, liberia, libya, liechtenstein, lithuania, luxembourg, macau, macedonia, madagascar, malawi, malaysia, maldives, mali, malta, mauritania, mauritius, mexico, micronesia, moldova, monaco, mongolia, montenegro, morocco, mozambique, myanmar, namibia, nepal, netherlands, new_caledonia, new_zealand, nicaragua, niger, nigeria, north_korea, northern_mariana_islands, norway, opec, oman, pakistan, palau, palestine, panama, papua_new_guinea, paraguay, peru, philippines, poland, portugal, puerto_rico, qatar, russia, republic_of_the_congo, romania, russia, rwanda, slovakia, samoa, san_marino, sao_tome_and_principe, saudi_arabia, senegal, serbia, seychelles, sierra_leone, singapore, slovakia, slovenia, solomon_islands, somalia, south_africa, south_korea, south_sudan, spain, sri_lanka, st_kitts_and_nevis, st_lucia, sudan, suriname, swaziland, sweden, switzerland, syria, taiwan, tajikistan, tanzania, thailand, togo, tonga, trinidad_and_tobago, tunisia, turkey, turkmenistan, uganda, ukraine, united_arab_emirates, united_kingdom, united_states, uruguay, uzbekistan, vanuatu, venezuela, vietnam, world, yemen, zambia, zimbabwe
    importance string No Level of importance
    1: low
    2: medium
    3: high
    before String No Pagination of data to return records newer than the requested ts based on the date parameter. Unix timestamp format in milliseconds.
    after String No Pagination of data to return records earlier than the requested ts based on the date parameter. Unix timestamp format in milliseconds. The default is the timestamp of the request moment.
    limit String No Number of results per request. The maximum is 100. The default is 100.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "actual": "7.8%",
                "calendarId": "330631",
                "category": "Harmonised Inflation Rate YoY",
                "ccy": "",
                "date": "1700121600000",
                "dateSpan": "0",
                "event": "Harmonised Inflation Rate YoY",
                "forecast": "7.8%",
                "importance": "1",
                "prevInitial": "",
                "previous": "9%",
                "refDate": "1698710400000",
                "region": "Slovakia",
                "uTime": "1700121605007",
                "unit": "%"
            }
        ],
        "msg": ""
    }
    
    

    Response Parameters

    Parameter Type Description
    calendarId string Calendar ID
    date string Estimated release time of the value of actual field, millisecond format of Unix timestamp, e.g. 1597026383085
    region string Country, region or entity
    category string Category name
    event string Event name
    refDate string Date for which the datapoint refers to
    actual string The actual value of this event
    previous string Latest actual value of the previous period
    The value will be revised if revision is applicable
    forecast string Average forecast among a representative group of economists
    dateSpan string 0: The time of the event is known
    1: we only know the date of the event, the exact time of the event is unknown.
    importance string Level of importance
    1: low
    2: medium
    3: high
    uTime string Update time of this record, millisecond format of Unix timestamp, e.g. 1597026383085
    prevInitial string The initial value of the previous period
    Only applicable when revision happens
    ccy string Currency of the data
    unit string Unit of the data

    WebSocket

    Instruments channel

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "instruments",
          "instType": "SPOT"
        }
      ]
    }
    

    Request Parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    instruments
    > instType String Yes Instrument type
    SPOT

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "instruments",
        "instType": "SPOT"
      },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"instruments\", \"instType\" : \"FUTURES\"}]}",
      "connId": "a4d3ae55"
    }
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    > instType String Yes Instrument type
    SPOT
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
      "arg": {
        "channel": "instruments",
        "instType": "SPOT"
      },
      "data": [
        {
            "alias": "",
            "baseCcy": "BTC",
            "category": "1",
            "ctMult": "",
            "ctType": "",
            "ctVal": "",
            "ctValCcy": "",
            "expTime": "",
            "instFamily": "",
            "instId": "BTC-USDT",
            "instType": "SPOT",
            "lever": "10",
            "listTime": "1606468572000",
            "lotSz": "0.00000001",
            "maxIcebergSz": "9999999999.0000000000000000",
            "maxLmtAmt": "1000000",
            "maxLmtSz": "9999999999",
            "maxMktAmt": "1000000",
            "maxMktSz": "",
            "maxStopSz": "",
            "maxTriggerSz": "9999999999.0000000000000000",
            "maxTwapSz": "9999999999.0000000000000000",
            "minSz": "0.00001",
            "optType": "",
            "quoteCcy": "USDT",
            "settleCcy": "",
            "state": "live",
            "stk": "",
            "tickSz": "0.1",
            "uly": ""
        }
      ]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Subscribed channel
    > channel String Channel name
    > instType String Instrument type
    data Array Subscribed data
    > instType String Instrument type
    > instId String Instrument ID, e.g. BTC-UST
    > uly String Underlying, e.g. BTC-USD
    Only applicable to FUTURES/SWAP/OPTION
    > instFamily String Instrument family, e.g. BTC-USD
    Only applicable to FUTURES/SWAP/OPTION
    > category String Currency category. Note: this parameter is already deprecated
    > baseCcy String Base currency, e.g. BTC in BTC-USDT
    Only applicable to SPOT/MARGIN
    > quoteCcy String Quote currency, e.g. USDT in BTC-USDT
    Only applicable to SPOT/MARGIN
    > settleCcy String Settlement and margin currency, e.g. BTC
    Only applicable to FUTURES/SWAP/OPTION
    > ctVal String Contract value
    > ctMult String Contract multiplier
    > ctValCcy String Contract value currency
    > optType String Option type
    C: Call
    P: Put
    Only applicable to OPTION
    > stk String Strike price
    Only applicable to OPTION
    > listTime String Listing time
    Only applicable to FUTURES/SWAP/OPTION
    > expTime String Expiry time
    Applicable to SPOT/MARGIN/FUTURES/SWAP/OPTION. For FUTURES/OPTION, it is the delivery/exercise time. It can also be the delisting time of the trading instrument. Update once change.
    > lever String Max Leverage
    Not applicable to SPOT/OPTION, used to distinguish between MARGIN and SPOT.
    > tickSz String Tick size, e.g. 0.0001
    For Option, it is minimum tickSz among tick band.
    > lotSz String Lot size
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency
    > minSz String Minimum order size
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency
    > ctType String Contract type
    linear: linear contract
    inverse: inverse contract
    Only applicable to FUTURES/SWAP
    > alias String Alias
    this_week
    next_week
    this_month
    next_month
    quarter
    next_quarter
    Only applicable to FUTURES
    Not recommended for use, users are encouraged to rely on the expTime field to determine the delivery time of the contract
    > state String Instrument status
    live
    suspend
    expired
    preopen. e.g. There will be preopen before the Futures and Options new contracts state is live.
    test: Test pairs, can't be traded
    > maxLmtSz String The maximum order quantity of a single limit order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    > maxMktSz String The maximum order quantity of a single market order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in USDT.
    > maxTwapSz String The maximum order quantity of a single TWAP order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    > maxIcebergSz String The maximum order quantity of a single iceBerg order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    > maxTriggerSz String The maximum order quantity of a single trigger order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in base currency.
    > maxStopSz String The maximum order quantity of a single stop market order.
    If it is a derivatives contract, the value is the number of contracts.
    If it is SPOT/MARGIN, the value is the quantity in USDT.

    Economic calendar channel

    Retrieve the most up-to-date economic calendar data. This endpoint is only applicable to VIP 1 and above users in the trading fee tier.

    Request Example

    {
        "op": "subscribe",
        "args": [
          {
              "channel": "economic-calendar"
          }
        ]
    }
    
    

    Request parameters

    Parameter Type Required Description
    op String Yes Operation
    subscribe
    unsubscribe
    args Array Yes List of subscribed channels
    > channel String Yes Channel name
    economic-calendar

    Successful Response Example

    {
        "event": "subscribe",
        "arg": {
            "channel": "economic-calendar"
        }
    }
    
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"mark-price\", \"instId\" : \"LTC-USD-190628\"}]}"
    }
    
    

    Response parameters

    Parameter Type Required Description
    event String Yes Event
    subscribe
    unsubscribe
    error
    arg Object No Subscribed channel
    > channel String Yes Channel name
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
        "arg": {
            "channel": "economic-calendar"
        },
        "data": [
            {
                "calendarId": "319275",
                "date": "1597026383085",
                "region": "United States",
                "category": "Manufacturing PMI",
                "event": "S&P Global Manufacturing PMI Final",
                "refDate": "1597026383085",
                "actual": "49.2",
                "previous": "47.3",
                "forecast": "49.3",
                "importance": "2",
                "prevInitial": "",
                "ccy": "",
                "unit": "",
                "ts": "1698648096590"
            }
        ]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    data Array Subscribed data
    > event string Event name
    > region string Country, region or entity
    > category string Category name
    > actual string The actual value of this event
    > previous string Latest actual value of the previous period
    The value will be revised if revision is applicable
    > forecast string Average forecast among a representative group of economists
    > prevInitial string The initial value of the previous period
    Only applicable when revision happens
    > date string Estimated release time of the value of actual field, millisecond format of Unix timestamp, e.g. 1597026383085
    > refDate string Date for which the datapoint refers to
    > calendarId string Calendar ID
    > unit string Unit of the data
    > ccy string Currency of the data
    > importance string Level of importance
    1: low
    2: medium
    3: high
    > ts string The time of the latest update

    Funding Account

    The API endpoints of Funding Account require authentication.

    REST API

    Get currencies

    Retrieve a list of all currencies available which are related to the current account's KYC entity.

    Rate Limit: 6 requests per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/currencies

    Request Example

    GET /api/v5/asset/currencies
    
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get currencies
    result = fundingAPI.get_currencies()
    print(result)
    

    Request Parameters

    Parameters Types Required Description
    ccy String No Single currency or multiple currencies (no more than 20) separated with comma, e.g. BTC or BTC,ETH.

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
            "canDep": true,
            "canInternal": true,
            "canWd": true,
            "ccy": "BTC",
            "chain": "BTC-Bitcoin",
            "depQuotaFixed": "",
            "depQuoteDailyLayer2": "",
            "logoLink": "https://static.coinall.ltd/cdn/oksupport/asset/currency/icon/btc.png",
            "mainNet": true,
            "maxFee": "0.0004",
            "maxFeeForCtAddr": "0.0004",
            "maxWd": "500",
            "minDep": "0.00005",
            "minDepArrivalConfirm": "1",
            "minFee": "0.0002",
            "minFeeForCtAddr": "0.0002",
            "minWd": "0.001",
            "minWdUnlockConfirm": "3",
            "name": "Bitcoin",
            "needTag": false,
            "usedDepQuotaFixed": "",
            "usedWdQuota": "0",
            "wdQuota": "200",
            "wdTickSz": "8"
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Currency, e.g. BTC
    name String Name of currency. There is no related name when it is not shown.
    logoLink String The logo link of currency
    chain String Chain name, e.g. USDT-ERC20, USDT-TRC20
    canDep Boolean The availability to deposit from chain
    false: not available
    true: available
    canWd Boolean The availability to withdraw to chain
    false: not available
    true: available
    canInternal Boolean The availability to internal transfer
    false: not available
    true: available
    minDep String The minimum deposit amount of currency in a single transaction
    minWd String The minimum on-chain withdrawal amount of currency in a single transaction
    maxWd String The maximum amount of currency on-chain withdrawal in a single transaction
    wdTickSz String The withdrawal precision, indicating the number of digits after the decimal point.
    The withdrawal fee precision kept the same as withdrawal precision.
    The accuracy of internal transfer withdrawal is 8 decimal places.
    wdQuota String The withdrawal limit in the past 24 hours (including on-chain withdrawal and internal transfer), unit in USD
    usedWdQuota String The amount of currency withdrawal used in the past 24 hours, unit in USD
    minFee String The minimum withdrawal fee for normal address
    Apply to on-chain withdrawal
    maxFee String The maximum withdrawal fee for normal address
    Apply to on-chain withdrawal
    minFeeForCtAddr String The minimum withdrawal fee for contract address
    Apply to on-chain withdrawal
    maxFeeForCtAddr String The maximum withdrawal fee for contract address
    Apply to on-chain withdrawal
    mainNet Boolean If current chain is main net, then it will return true, otherwise it will return false
    needTag Boolean Whether tag/memo information is required for withdrawal, e.g. EOS will return true
    minDepArrivalConfirm String The minimum number of blockchain confirmations to acknowledge fund deposit. The account is credited after that, but the deposit can not be withdrawn
    minWdUnlockConfirm String The minimum number of blockchain confirmations required for withdrawal of a deposit
    depQuotaFixed String The fixed deposit limit, unit in USD
    Return empty string if there is no deposit limit
    usedDepQuotaFixed String The used amount of fixed deposit quota, unit in USD
    Return empty string if there is no deposit limit
    depQuoteDailyLayer2 String The layer2 network daily deposit limit

    Get balance

    Retrieve the funding account balances of all the assets and the amount that is available or on hold.

    Rate Limit: 6 requests per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/balances

    Request Example

    GET /api/v5/asset/balances
    
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get balane
    result = fundingAPI.get_balances()
    print(result)
    

    Request Parameters

    Parameters Types Required Description
    ccy String No Single currency or multiple currencies (no more than 20) separated with comma, e.g. BTC or BTC,ETH.

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [
            {
                "availBal": "37.11827078",
                "bal": "37.11827078",
                "ccy": "ETH",
                "frozenBal": "0"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Currency
    bal String Balance
    frozenBal String Frozen balance
    availBal String Available balance

    Get non-tradable assets

    Rate Limit: 6 requests per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/non-tradable-assets

    Request Example

    GET /api/v5/asset/non-tradable-assets
    
    

    Request Parameters

    Parameters Types Required Description
    ccy String No Single currency or multiple currencies (no more than 20) separated with comma, e.g. BTC or BTC,ETH.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "bal": "989.84719571",
                "canWd": true,
                "ccy": "CELT",
                "chain": "CELT-OKTC",
                "ctAddr": "f403fb",
                "fee": "2",
                "logoLink": "https://static.coinall.ltd/cdn/assets/imgs/221/460DA8A592400393.png",
                "minWd": "0.1",
                "name": "",
                "needTag": false,
                "wdAll": false,
                "wdTickSz": "8"
            },
            {
                "bal": "0.001",
                "canWd": true,
                "ccy": "MEME",
                "chain": "MEME-ERC20",
                "ctAddr": "09b760",
                "fee": "5",
                "logoLink": "https://static.coinall.ltd/cdn/assets/imgs/207/2E664E470103C613.png",
                "minWd": "0.001",
                "name": "MEME Inu",
                "needTag": false,
                "wdAll": false,
                "wdTickSz": "8"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Currency, e.g. CELT
    name String Chinese name of currency. There is no related name when it is not shown.
    logoLink String Logo link of currency
    bal String Withdrawable balance
    canWd Boolean Availability to withdraw to chain.
    false: not available true: available
    chain String Chain for withdrawal
    minWd String Minimum withdrawal amount of currency in a single transaction
    wdAll Boolean Whether all assets in this currency must be withdrawn at one time
    fee String Fixed withdrawal fee, unit in USDT. Withdrawal fee precision is 8 digits after the decimal point.
    ctAddr String Last 6 digits of contract address
    wdTickSz String Withdrawal precision, indicating the number of digits after the decimal point
    needTag Boolean Whether tag/memo information is required for withdrawal

    Get account asset valuation

    View account asset valuation

    Rate Limit: 1 request per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/asset-valuation

    Request Example

    GET /api/v5/asset/asset-valuation
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get account asset valuation
    result = fundingAPI.get_asset_valuation()
    print(result)
    

    Request Parameters

    Parameters Types Required Description
    ccy String No Asset valuation calculation unit
    BTC, USDT
    USD, CNY, JP, KRW, RUB, EUR
    VND, IDR, INR, PHP, THB, TRY
    AUD, SGD, ARS, SAR, AED, IQD
    The default is the valuation in BTC.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "details": {
                    "classic": "124.6",
                    "earn": "1122.73",
                    "funding": "0.09",
                    "trading": "2544.28"
                },
                "totalBal": "3790.09",
                "ts": "1637566660769"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    totalBal String Valuation of total account assets
    ts String Unix timestamp format in milliseconds, e.g.1597026383085
    details Object Asset valuation details for each account
    > funding String Funding account
    > trading String Trading account
    > classic String [Deprecated] Classic account
    > earn String Earn account

    Funds transfer

    Only API keys with Trade privilege can call this endpoint.

    This endpoint supports the transfer of funds between your funding account and trading account, and from the master account to sub-accounts.

    Sub-account can transfer out to master account by default. Need to call Set permission of transfer out to grant privilege first if you want sub-account transferring to another sub-account (sub-accounts need to belong to same master account.)

    Rate Limit: 2 requests per second

    Rate limit rule: UserID + Currency

    HTTP Request

    POST /api/v5/asset/transfer

    Request Example

    # Transfer 1.5 USDT from funding account to Trading account when current account is master-account
    POST /api/v5/asset/transfer
    body
    {
        "ccy":"USDT",
        "amt":"1.5",
        "from":"6",
        "to":"18"
    }
    
    # Transfer 1.5 USDT from funding account to subAccount when current account is master-account
    POST /api/v5/asset/transfer
    body
    {
        "ccy":"USDT",
        "type":"1",
        "amt":"1.5",
        "from":"6",
        "to":"6",
        "subAcct":"mini"
    }
    
    # Transfer 1.5 USDT from funding account to subAccount when current account is sub-account
    POST /api/v5/asset/transfer
    body 
    {
        "ccy":"USDT",
        "type":"4",
        "amt":"1.5",
        "from":"6",
        "to":"6",
        "subAcct":"mini"
    }
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Funds transfer
    result = fundingAPI.funds_transfer(
        ccy="USDT",
        amt="1.5",
        from_="6",
        to="18"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    type String No Transfer type
    0: transfer within account
    1: master account to sub-account (Only applicable to API Key from master account)
    2: sub-account to master account (Only applicable to API Key from master account)
    3: sub-account to master account (Only applicable to APIKey from sub-account)
    4: sub-account to sub-account (Only applicable to APIKey from sub-account, and target account needs to be another sub-account which belongs to same master account. Sub-account directly transfer out permission is disabled by default, set permission please refer to Set permission of transfer out)
    The default is 0.
    If you want to make transfer between sub-accounts by master account API key, refer to Master accounts manage the transfers between sub-accounts
    ccy String Yes Transfer currency, e.g. USDT
    amt String Yes Amount to be transferred
    from String Yes The remitting account
    6: Funding account
    18: Trading account
    to String Yes The beneficiary account
    6: Funding account
    18: Trading account
    subAcct String Conditional Name of the sub-account
    When type is 1/2/4, this parameter is required.
    loanTrans Boolean No Whether or not borrowed coins can be transferred out under Multi-currency margin and Portfolio margin
    true: borrowed coins can be transferred out
    false: borrowed coins cannot be transferred out
    the default is false
    omitPosRisk String No Ignore position risk
    Default is false
    Applicable to Portfolio margin
    clientId String No Client-supplied ID
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
          "transId": "754147",
          "ccy": "USDT",
          "clientId": "",
          "from": "6",
          "amt": "0.1",
          "to": "18"
        }
      ]
    }
    

    Response Parameters

    Response Example

    Parameter Type Description
    transId String Transfer ID
    clientId String Client-supplied ID
    ccy String Currency
    from String The remitting account
    amt String Transfer amount
    to String The beneficiary account

    Get funds transfer state

    Retrieve the transfer state data of the last 2 weeks.

    Rate Limit: 1 request per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/transfer-state

    Request Example

    GET /api/v5/asset/transfer-state?transId=1&type=1
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "1"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get funds transfer state
    result = fundingAPI.transfer_state(
        transId="248424899",
        type="0"
    )
    print(result)
    
    

    Request Parameters

    Parameter Type Required Description
    transId String Conditional Transfer ID
    Either transId or clientId is required. If both are passed, transId will be used.
    clientId String Conditional Client-supplied ID
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    type String No Transfer type
    0: transfer within account
    1: master account to sub-account (Only applicable to API Key from master account)
    2: sub-account to master account (Only applicable to API Key from master account)
    3: sub-account to master account (Only applicable to APIKey from sub-account)
    4: sub-account to sub-account (Only applicable to APIKey from sub-account, and target account needs to be another sub-account which belongs to same master account)
    The default is 0

    Response Example

    {
        "code": "0",
        "data": [
            {
                "amt": "1.5",
                "ccy": "USDT",
                "clientId": "",
                "from": "18",
                "instId": "", //deprecated
                "state": "success",
                "subAcct": "test",
                "to": "6",
                "toInstId": "", //deprecated
                "transId": "1",
                "type": "1"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    transId String Transfer ID
    clientId String Client-supplied ID
    ccy String Currency, e.g. USDT
    amt String Amount to be transferred
    type String Transfer type
    0: transfer within account
    1: master account to sub-account (Only applicable to API Key from master account)
    2: sub-account to master account (Only applicable to APIKey from master account)
    3: sub-account to master account (Only applicable to APIKey from sub-account)
    4: sub-account to sub-account (Only applicable to APIKey from sub-account, and target account needs to be another sub-account which belongs to same master account)
    from String The remitting account
    6: Funding account
    18: Trading account
    to String The beneficiary account
    6: Funding account
    18: Trading account
    subAcct String Name of the sub-account
    instId String deprecated
    toInstId String deprecated
    state String Transfer state
    success
    pending
    failed

    Asset bills details

    Query the billing record.

    Rate Limit: 6 Requests per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/bills

    Request Example

    GET /api/v5/asset/bills
    
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get asset bills details
    result = fundingAPI.get_bills()
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ccy String No Currency
    type String No Bill type
    1: Deposit
    2: Withdrawal
    13: Canceled withdrawal
    20: Transfer to sub account (for master account)
    21: Transfer from sub account (for master account)
    22: Transfer out from sub to master account (for sub-account)
    23: Transfer in from master to sub account (for sub-account)
    28: Manually claimed Airdrop
    47: System reversal
    48: Event Reward
    49: Event Giveaway
    50: Received from appointments
    51: Deducted from appointments
    52: Red packet sent
    53: Red packet snatched
    54: Red packet refunded
    61: Convert
    68: Fee rebate (by rebate card)
    69: Distribute rebate card
    72: Token received
    73: Token given away
    74: Token refunded
    75: Subscription to savings
    76: Redemption to savings
    77: Distribute
    78: Lock up
    79: Node voting
    80: DEFI/Staking purchase
    81: Vote redemption
    82: DEFI/Staking redemption
    83: Staking yield
    84: Violation fee
    85: PoW mining yield
    86: Cloud mining pay
    87: Cloud mining yield
    88: Subsidy
    89: DEFI yield
    92: Add collateral
    93: Redeem collateral
    94: Investment
    95: Borrower borrows
    96: Principal transferred in
    97: Borrower transferred loan out
    98: Borrower transferred interest out
    99: Investor transferred interest in
    102: Prepayment penalty transferred in
    103: Prepayment penalty transferred out
    104: Mortgage fee transferred in
    105: Mortgage fee transferred out
    106: Overdue fee transferred in
    107: Overdue fee transferred out
    108: Overdue interest transferred out
    109: Overdue interest transferred in
    110: Collateral for closed position transferred in
    111: Collateral for closed position transferred out
    112: Collateral for liquidation transferred in
    113: Collateral for liquidation transferred out
    114: Insurance fund transferred in
    115: Insurance fund transferred out
    116: Place an order
    117: Fulfill an order
    118: Cancel an order
    119: Merchants unlock deposit
    120: Merchants add deposit
    121: FiatGateway Place an order
    122: FiatGateway Cancel an order
    123: FiatGateway Fulfill an order
    124: Jumpstart unlocking
    125: Manual deposit
    126: Interest deposit
    127: Investment fee transferred in
    128: Investment fee transferred out
    129: Rewards transferred in
    130: Transferred from Trading account
    131: Transferred to Trading account
    132: Frozen by customer service
    133: Unfrozen by customer service
    134: Transferred by customer service
    135: Cross chain exchange
    136: ETH 2.0 staking system account increase ETH (for on-chain operation)
    137: ETH 2.0 Subscription
    138: ETH 2.0 Swapping
    139: ETH 2.0 Earnings
    143: System Reverse
    144: Trading account reserve transferred out
    145: Reward Expired
    146: Customer feedback
    147: vested sushi rewards
    150: Affiliate commission
    151: Referral reward
    152: Broker reward
    153: Joiner reward
    154: Mystery box reward
    155: Rewards withdraw
    160: Dual Investment subscribe
    161: Dual Investment collection
    162: Dual Investment profit
    163: Dual Investment refund
    169: 2022 new year rewards
    172: Sub-affiliate commission
    173: Fee rebate (by trading fee)
    174: Pay
    175: Locked collateral
    176: Loan
    177: Added collateral
    178: Returned collateral
    179: Repayment
    180: Unlocked collateral
    181: Airdrop Payment
    182: Feedback bounty
    183: Invite friends rewards
    184: Divide the reward pool
    185: Broker Convert Reward
    186: FreeETH
    187: Convert transfer
    188: Slot Auction Conversion
    189: Mystery box bonus
    193: Card payment Buy
    195: Untradable asset withdrawal
    196: Untradable asset withdrawal revoked
    197: Untradable asset deposit
    198: Untradable asset collection reduce
    199: Untradable asset collection increase
    200: Buy
    202: Price Lock Subscribe
    203: Price Lock Collection
    204: Price Lock Profit
    205: Price Lock Refund
    207: Dual Investment Lite Subscribe
    208: Dual Investment Lite Collection
    209: Dual Investment Lite Profit
    210: Dual Investment Lite Refund
    211: Win crypto with Satoshi
    212: (Flexible loan) Multi-collateral loan collateral locked
    213: (Flexible loan) Collateral transfer out from user's funding account
    214: (Flexible loan) Collateral returned to users
    215: (Flexible loan) Multi-collateral loan collateral released
    216: (Flexible loan) Loan transfer into user's funding account
    217: (Flexible loan) Multi-collateral loan borrowed
    218: (Flexible loan) Multi-collateral loan repaid
    219: (Flexible loan) Loan repayment transfer out from user's funding account
    220: Delisted crypto
    221: Blockchain's withdrawal fee
    222: Withdrawal fee refund
    223: SWAP lead trading profit share
    266: SPOT lead trading profit share
    224: Service fee
    225: Shark Fin subscribe
    226: Shark Fin collection
    227: Shark Fin profit
    228: Shark Fin refund
    229: Airdrop
    230: Token migration completed
    232: Subsidized interest received
    233: Broker rebate compensation
    249: Seagull subscribe
    250: Seagull collection
    251: Seagull profit
    252: Seagull refund
    263: Strategy bots profit share
    270: DCD broker transfer
    271: DCD broker rebate
    284: Transfer out trading sub-account
    285: Transfer in trading sub-account
    286: Transfer out custody funding account
    287: Transfer in custody funding account
    288: Custody fund delegation
    289: Custody fund undelegation
    303: Snowball market maker transfer
    311: Crypto dust auto-transfer in
    clientId String No Client-supplied ID for transfer or withdrawal
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    after String No Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085
    before String No Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1597026383085
    limit String No Number of results per request. The maximum is 100. The default is 100.

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "billId": "12344",
            "ccy": "BTC",
            "clientId": "",
            "balChg": "2",
            "bal": "12",
            "type": "1",
            "ts": "1597026383085"
        }]
    }
    

    Response Parameters

    Parameter Type Description
    billId String Bill ID
    ccy String Account balance currency
    clientId String Client-supplied ID for transfer or withdrawal
    balChg String Change in balance at the account level
    bal String Balance at the account level
    type String Bill type
    ts String Creation time, Unix timestamp format in milliseconds, e.g.1597026383085

    Lightning deposits

    Users can create up to 10,000 different invoices within 24 hours.

    Rate Limit: 2 requests per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/deposit-lightning

    Request Example

    GET /api/v5/asset/deposit-lightning?ccy=BTC&amt=0.01
    
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Lightning deposits
    result = fundingAPI.get_deposit_lightning(
        ccy="USDT",
        amt="100"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ccy String Yes Token symbol. Currently only BTC is supported.
    amt String Yes Deposit amount between 0.000001 - 0.1
    to String No Receiving account
    6: Funding account
    18: Trading account
    Default is 6.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "cTime": "1631171307612",
                "invoice": "lnbc100u1psnnvhtpp5yq2x3q5hhrzsuxpwx7ptphwzc4k4wk0j3stp0099968m44cyjg9sdqqcqzpgxqzjcsp5hzzdszuv6yv6yw5svctl8kc8uv6y77szv5kma2kuculj86tk3yys9qyyssqd8urqgcensh9l4zwlwr3lxlcdqrlflvvlwldutm6ljx486h7lylqmd06kky6scas7warx69sregzrx20ffmsr4sp865x3wasrjd8ttgqrlx3tr",
                "verifiedName":"John Corner"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    invoice String Invoice text
    cTime String Invoice creation time
    verifiedName String Verified name (for recipient)

    Get deposit address

    Retrieve the deposit addresses of currencies, including previously-used addresses.

    Rate Limit: 6 requests per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/deposit-address

    Request Example

    GET /api/v5/asset/deposit-address?ccy=BTC
    
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get deposit address
    result = fundingAPI.get_deposit_address(
        ccy="USDT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ccy String Yes Currency, e.g. BTC

    Response Example

    {
        "code": "0",
        "data": [
            {
                "chain": "BTC-Bitcoin",
                "ctAddr": "",
                "ccy": "BTC",
                "to": "6",
                "addr": "39XNxK1Ryqgg3Bsyn6HzoqV4Xji25pNkv6",
                "verifiedName":"John Corner",
                "selected": true
            },
            {
                "chain": "BTC-OKC",
                "ctAddr": "",
                "ccy": "BTC",
                "to": "6",
                "addr": "0x66d0edc2e63b6b992381ee668fbcb01f20ae0428",
                "verifiedName":"John Corner",
                "selected": true
            },
            {
                "chain": "BTC-ERC20",
                "ctAddr": "5807cf",
                "ccy": "BTC",
                "to": "6",
                "addr": "0x66d0edc2e63b6b992381ee668fbcb01f20ae0428",
                "verifiedName":"John Corner",
                "selected": true
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    addr String Deposit address
    tag String Deposit tag (This will not be returned if the currency does not require a tag for deposit)
    memo String Deposit memo (This will not be returned if the currency does not require a memo for deposit)
    pmtId String Deposit payment ID (This will not be returned if the currency does not require a payment_id for deposit)
    addrEx Object Deposit address attachment (This will not be returned if the currency does not require this)
    e.g. TONCOIN attached tag name is comment, the return will be {'comment':'123456'}
    ccy String Currency, e.g. BTC
    chain String Chain name, e.g. USDT-ERC20, USDT-TRC20
    to String The beneficiary account
    6: Funding account 18: Trading account
    verifiedName String Verified name (for recipient)
    selected Boolean Return true if the current deposit address is selected by the website page
    ctAddr String Last 6 digits of contract address

    Get deposit history

    Retrieve the deposit records according to the currency, deposit status, and time range in reverse chronological order. The 100 most recent records are returned by default.
    Websocket API is also available, refer to Deposit info channel.

    Rate Limit: 6 requests per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/asset/deposit-history

    Request Example

    
    GET /api/v5/asset/deposit-history
    
    # Query deposit history from 2022-06-01 to 2022-07-01
    GET /api/v5/asset/deposit-history?ccy=BTC&after=1654041600000&before=1656633600000
    
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Get deposit history
    result = fundingAPI.get_deposit_history()
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ccy String No Currency, e.g. BTC
    depId String No Deposit ID
    fromWdId String No Internal transfer initiator's withdrawal ID
    If the deposit comes from internal transfer, this field displays the withdrawal ID of the internal transfer initiator
    txId String No Hash record of the deposit
    type String No Deposit Type
    3: internal transfer
    4: deposit from chain
    state String No Status of deposit
    0: waiting for confirmation
    1: deposit credited
    2: deposit successful
    8: pending due to temporary deposit suspension on this crypto currency
    11: match the address blacklist
    12: account or deposit is frozen
    13: sub-account deposit interception
    14: KYC limit
    after String No Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1654041600000
    before String No Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1656633600000
    limit string No Number of results per request. The maximum is 100; The default is 100

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
            "actualDepBlkConfirm": "2",
            "amt": "1",
            "areaCodeFrom": "",
            "ccy": "USDT",
            "chain": "USDT-TRC20",
            "depId": "88****33",
            "from": "",
            "fromWdId": "",
            "state": "2",
            "to": "TN4hGjVXMzy*********9b4N1aGizqs",
            "ts": "1674038705000",
            "txId": "fee235b3e812********857d36bb0426917f0df1802"
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Currency
    chain String Chain name
    amt String Deposit amount
    from String Deposit account
    If the deposit comes from an internal transfer, this field displays the account information of the internal transfer initiator, which can be a mobile phone number, email address, account name, and will return "" in other cases
    areaCodeFrom String If from is a phone number, this parameter return area code of the phone number
    to String Deposit address
    If the deposit comes from the on-chain, this field displays the on-chain address, and will return "" in other cases
    txId String Hash record of the deposit
    ts String The timestamp that the deposit record is created, Unix timestamp format in milliseconds, e.g. 1655251200000
    state String Status of deposit
    0: waiting for confirmation
    1: deposit credited
    2: deposit successful
    8: pending due to temporary deposit suspension on this crypto currency
    11: match the address blacklist
    12: account or deposit is frozen
    13: sub-account deposit interception
    14: KYC limit
    depId String Deposit ID
    fromWdId String Internal transfer initiator's withdrawal ID
    If the deposit comes from internal transfer, this field displays the withdrawal ID of the internal transfer initiator, and will return "" in other cases
    actualDepBlkConfirm String The actual amount of blockchain confirmed in a single deposit

    Withdrawal

    Withdrawal of tokens. Common sub-account does not support withdrawal.

    Rate Limit: 6 requests per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/asset/withdrawal

    Request Example

    # on-chain withdrawal
    POST /api/v5/asset/withdrawal
    body
    {
        "amt":"1",
        "fee":"0.0005",
        "dest":"4",
        "ccy":"BTC",
        "chain":"BTC-Bitcoin",
        "toAddr":"17DKe3kkkkiiiiTvAKKi2vMPbm1Bz3CMKw"
    }
    
    # internal withdrawal 
    POST /api/v5/asset/withdrawal
    body
    {
        "amt":"10",
        "fee":"0",
        "dest":"3",
        "ccy":"USDT",
        "areaCode":"86"
        "toAddr":"15651000000"
    }
    
    # Specific country/region certified users need to provide receiver's info
    POST /api/v5/asset/withdrawal
    body
    {
        "amt":"1",
        "fee":"0.0005",
        "dest":"4",
        "ccy":"BTC",
        "chain":"BTC-Bitcoin",
        "toAddr":"17DKe3kkkkiiiiTvAKKi2vMPbm1Bz3CMKw",
        "rcvrInfo":{
            "walletType":"exchange",
            "exchId":"did:ethr:0xfeb4f99829a9acdf52979abee87e83addf22a7e1",
            "rcvrFirstName":"Bruce",
            "rcvrLastName":"Wayne"
        }
    }
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Withdrawal
    result = fundingAPI.withdrawal(
        ccy="USDT",
        toAddr="TXtvfb7cdrn6VX9H49mgio8bUxZ3DGfvYF",
        amt="100",
        fee="0.0005",
        dest="4",
        chain="USDT-TRC20"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ccy String Yes Currency, e.g. USDT
    amt String Yes Withdrawal amount
    Withdrawal fee is not included in withdrawal amount.
    dest String Yes Withdrawal method
    3: internal transfer
    4: on-chain withdrawal
    toAddr String Yes toAddr should be a trusted address/account.
    If your dest is 4, some crypto currency addresses are formatted as 'address:tag', e.g. 'ARDOR-7JF3-8F2E-QUWZ-CAN7F:123456'
    If your dest is 3,toAddr should be a recipient address which can be email, phone or login account name (account name is only for sub-account).
    fee String Yes Transaction fee
    You can get fee amount by the endpoint of Get currencies.
    For internal transfer, transaction fee is always 0.
    chain String Conditional Chain name
    There are multiple chains under some currencies, such as USDT has USDT-ERC20, USDT-TRC20
    If the parameter is not filled in, the default will be the main chain.
    When you withdrawal the non-tradable asset, if the parameter is not filled in, the default will be the unique withdrawal chain.
    Apply to on-chain withdrawal.
    You can get supported chain name by the endpoint of Get currencies.
    areaCode String Conditional Area code for the phone number, e.g. 86
    If toAddr is a phone number, this parameter is required.
    Apply to internal transfer
    rcvrInfo Object Conditional Receiver's info
    Specific country/region certified users need to provide this information for on-chain withdrawal
    > walletType String Yes Wallet Type
    exchange: Withdraw to exchange wallet
    private: Withdraw to private wallet
    If you withdraw to exchange wallet,exchId&rcvrFirstName&rcvrLastName is required
    If you withdraw to private wallet, no additional information is required.
    > exchId String Conditional Exchange ID
    You can query supported exchanges through the endpoint of Get exchange list (public)
    If the exchange is not in the exchange list, fill in '0' in this field.
    > rcvrFirstName String Conditional Receiver's first name, e.g. Bruce
    > rcvrLastName String Conditional Receiver's last name, e.g. Wayne
    clientId String No Client-supplied ID
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "amt": "0.1",
            "wdId": "67485",
            "ccy": "BTC",
            "clientId": "",
            "chain": "BTC-Bitcoin"
        }]
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Currency
    chain String Chain name, e.g. USDT-ERC20, USDT-TRC20
    amt String Withdrawal amount
    wdId String Withdrawal ID
    clientId String Client-supplied ID
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

    Lightning withdrawals

    The maximum withdrawal amount is 0.1 BTC per request, and 1 BTC in 24 hours. The minimum withdrawal amount is approximately 0.000001 BTC. Sub-account does not support withdrawal.

    Rate Limit: 2 requests per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/asset/withdrawal-lightning

    Request Example

    POST /api/v5/asset/withdrawal-lightning
    body
    {
        "ccy":"BTC",
        "invoice":"lnbc100u1psnnvhtpp5yq2x3q5hhrzsuxpwx7ptphwzc4k4wk0j3stp0099968m44cyjg9sdqqcqzpgxqzjcsp5hz"
    }
    
    
    import okx.Funding as Funding
    
    # API initialization
    apikey = "YOUR_API_KEY"
    secretkey = "YOUR_SECRET_KEY"
    passphrase = "YOUR_PASSPHRASE"
    
    flag = "0"  # Production trading: 0, Demo trading: 1
    
    fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
    
    # Lightning withdrawals
    result = fundingAPI.withdrawal_lightning(
        ccy="BTC",
        invoice="lnbc100u1psnnvhtpp5yq2x3q5hhrzsuxpwx7ptphwzc4k4wk0j3stp0099968m44cyjg9sdqqcqzpgxqzjcsp5hz"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ccy String Yes Token symbol. Currently only BTC is supported.
    invoice String Yes Invoice text
    memo String No Lightning withdrawal memo
    rcvrInfo Object Conditional Receiver's info
    Specific country/region certified users need to provide this information for on-chain withdrawal
    > walletType String Yes Wallet Type
    exchange:Withdraw to exchange wallet
    private:Withdraw to private wallet
    If you withdraw to exchange wallet,exchId&rcvrFirstName&rcvrLastName is required
    If you withdraw to private wallet, no additional information is required
    > exchId String Conditional Exchange ID
    You can query supported exchanges through the endpoint of Get exchange list (public)
    If the exchange is not in the exchange list, fill in '0' in this field
    > rcvrFirstName String Conditional Receiver's first name, e.g. Bruce
    > rcvrLastName String Conditional Receiver's last name, e.g. Wayne

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "wdId": "121212",
            "cTime": "1597026383085"
        }]
    }
    

    Response Parameters

    Parameter Type Description
    wdId String Withdrawal ID
    cTime String Withdrawal ID creation time

    Cancel withdrawal

    You can cancel normal withdrawal requests, but you cannot cancel withdrawal requests on Lightning.

    Rate Limit: 6 requests per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/asset/cancel-withdrawal

    Request Example

    POST /api/v5/asset/cancel-withdrawal
    body {
       "wdId":"1123456"
    }
    
    
    import