NAV
中文
HTTP Python

Overview

Welcome to our V5 API documentation. OKX 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.

Connection count limit

The limit will be set at 20 WebSocket connections per specific WebSocket channel per sub-account. Each WebSocket connection is identified by the unique connId.


The WebSocket channels subject to this limitation are as follows:

  1. Orders channel
  2. Account channel
  3. Positions channel
  4. Balance and positions channel
  5. Position risk warning channel
  6. Account greeks channel

If users subscribe to the same channel through the same WebSocket connection through multiple arguments, for example, by using {"channel": "orders", "instType": "ANY"} and {"channel": "orders", "instType": "SWAP"}, it will be counted once only. If users subscribe to the listed channels (such as orders and accounts) using either the same or different connections, it will not affect the counting, as these are considered as two different channels. The system calculates the number of WebSocket connections per channel.


The platform will send the number of active connections to clients through the channel-conn-count event message to new channel subscriptions.

Connection count update

{
    "event":"channel-conn-count",
    "channel":"orders",
    "connCount": "2",
    "connId":"abcd1234"
}


When the limit is breached, generally the latest connection that sends the subscription request will be rejected. Client will receive the usual subscription acknowledgement followed by the channel-conn-count-error from the connection that the subscription has been terminated. In exceptional circumstances the platform may unsubscribe existing connections.

Connection limit error

{
    "event": "channel-conn-count-error",
    "channel": "orders",
    "connCount": "20",
    "connId":"a4d3ae55"
}


Order operations through WebSocket, including place, amend and cancel orders, are not impacted through this change.

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

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

passphrase: API Key password

timestamp: the Unix Epoch time, the unit is seconds, e.g. 1704876947

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, limit price channel, order book channel, and mark price channel etc.

Private channels -- including account channel, order channel, and position 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-USD-200327"
    },
    {
      "channel": "candle1m",
      "instId": "LTC-USD-200327"
    }
  ]
}

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
MARGIN
SWAP
FUTURES
OPTION
ANY
> instFamily String No Instrument family
Applicable to FUTURES/SWAP/OPTION
> instId String No Instrument ID

Response Example

{
  "event": "subscribe",
  "arg": {
    "channel": "tickers",
    "instId": "LTC-USD-200327"
  },
  "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
MARGIN
SWAP
FUTURES
OPTION
ANY
> instFamily String No Instrument family
Applicable to FUTURES/SWAP/OPTION
> 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-USD-200327"
    },
    {
      "channel": "candle1m",
      "instId": "LTC-USD-200327"
    }
  ]
}

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
MARGIN
SWAP
FUTURES
OPTION
ANY
> instFamily String No Instrument family
Applicable to FUTURES/SWAP/OPTION
> instId String No Instrument ID

Response Example

{
  "event": "unsubscribe",
  "arg": {
    "channel": "tickers",
    "instId": "LTC-USD-200327"
  },
  "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
MARGIN
SWAP
FUTURES
OPTION
> instFamily String No Instrument family
Applicable to FUTURES/SWAP/OPTION
> instId String No Instrument ID
code String No Error code
msg String No Error message

Account mode

To facilitate your trading experience, please set the appropriate account mode before starting trading.

In the trading account trading system, 4 account modes are supported: Spot mode, Spot and futures mode, Multi-currency margin mode, and Portfolio margin mode.

You need to set on the Web/App for the first set of every account mode.

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 account can be used for login on Demo Trading. If you already have an OKX account, you can log in directly.

Start API Demo Trading by the following steps:
Login OKX —> 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

Demo Trading Explorer

You need to sign in to your OKX account before accessing the explorer. The interface only allow access to the demo trading environment.

Try demo trading explorer

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:


The introduction of instFamily:

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:

Sub-account rate limit

At the sub-account level, we allow a maximum of 1000 order requests per 2 seconds. Only new order requests and amendment order requests will be counted towards this limit. The limit encompasses all requests from the endpoints below. For batch order requests consisting of multiple orders, each order will be counted individually. Error code 50061 is returned when the sub-account rate limit is exceeded. The existing rate limit rule per instrument ID remains unchanged and the existing rate limit and sub-account rate limit will operate in parallel. If clients require a higher rate limit, clients can trade via multiple sub-accounts.

Fill ratio based sub-account rate limit

This is only applicable to >= VIP5 customers.
As an incentive for more efficient trading, the exchange will offer a higher sub-account rate limit to clients with a high trade fill ratio.

The exchange calculates two ratios based on the transaction data from the past 7 days at 00:00 UTC.

  1. Sub-account fill ratio: This ratio is determined by dividing (the trade volume in USDT of the sub-account) by (sum of (new and amendment request count per symbol * symbol multiplier) of the sub-account). Note that the master trading account itself is also considered as a sub-account in this context.
  2. Master account aggregated fill ratio: This ratio is calculated by dividing (the trade volume in USDT on the master account level) by (the sum (new and amendment count per symbol * symbol multiplier] of all sub-accounts).


The symbol multiplier allows for fine-tuning the weight of each symbol. A smaller symbol multiplier (<1) is used for smaller pairs that require more updates per trading volume. All instruments have a default symbol multiplier, and some instruments will have overridden symbol multipliers.

InstType Override rule Overridden symbol multiplier Default symbol multiplier
Perpetual Futures Per instrument ID 1
Instrument ID:
BTC-USDT-SWAP
BTC-USD-SWAP
ETH-USDT-SWAP
ETH-USD-SWAP
0.2
Expiry Futures Per instrument Family 0.3
Instrument Family:
BTC-USDT
BTC-USD
ETH-USDT
ETH-USD
0.1
Spot Per instrument ID 0.5
Instrument ID:
BTC-USDT
ETH-USDT
0.1
Options Per instrument Family 0.1

The fill ratio computation excludes block trading, spread trading, MMP and fiat orders for order count; and excludes block trading, spread trading for trade volume. Only successful order requests (sCode=0) are considered.



At 08:00 UTC, the system will use the maximum value between the sub-account fill ratio and the master account aggregated fill ratio based on the data snapshot at 00:00 UTC to determine the sub-account rate limit based on the table below. For broker (non-disclosed) clients, the system considers the sub-account fill ratio only.

Fill ratio[x<=ratio<y) Sub-account rate limit per 2 seconds(new and amendment)
Tier 1 [0,1) 1,000
Tier 2 [1,2) 1,250
Tier 3 [2,3) 1,500
Tier 4 [3,5) 1,750
Tier 5 [5,10) 2,000
Tier 6 [10,20) 2,500
Tier 7 [20,50) 3,000
Tier 8 >= 50 10,000

If there is an improvement in the fill ratio and rate limit to be uplifted, the uplift will take effect immediately at 08:00 UTC. However, if the fill ratio decreases and the rate limit needs to be lowered, a one-day grace period will be granted, and the lowered rate limit will only be implemented on T+1 at 08:00 UTC. On T+1, if the fill ratio improves, the higher rate limit will be applied accordingly. In the event of client demotion to VIP4, their rate limit will be downgraded to Tier 1, accompanied by a one-day grace period.


If the 7-day trading volume of a sub-account is less than 1,000,000 USDT, the fill ratio of the master account will be applied to it.


For newly created sub-accounts, the Tier 1 rate limit will be applied at creation until T+1 8am UTC, at which the normal rules will be applied.


Block trading, spread trading, MMP and spot/margin orders are exempted from the sub-account rate limit.


The exchange offers GET / Account rate limit endpoint that provides ratio and rate limit data, which will be updated daily at 8am UTC. It will return the sub-account fill ratio, the master account aggregated fill ratio, current sub-account rate limit and sub-account rate limit on T+1 (applicable if the rate limit is going to be demoted).

The fill ratio and rate limit calculation example is shown below. Client has 3 accounts, symbol multiplier for BTC-USDT-SWAP = 1 and XRP-USDT = 0.1.

  1. Account A (master account):
    1. BTC-USDT-SWAP trade volume = 100 USDT, order count = 10;
    2. XRP-USDT trade volume = 20 USDT, order count = 15;
    3. Sub-account ratio = (100+20) / (10 * 1 + 15 * 0.1) = 10.4
  2. Account B (sub-account):
    1. BTC-USDT-SWAP trade volume = 200 USDT, order count = 100;
    2. XRP-USDT trade volume = 20 USDT, order count = 30;
    3. Sub-account ratio = (200+20) / (100 * 1 + 30 * 0.1) = 2.13
  3. Account C (sub-account):
    1. BTC-USDT-SWAP trade volume = 300 USDT, order count = 1000;
    2. XRP-USDT trade volume = 20 USDT, order count = 45;
    3. Sub-account ratio = (300+20) / (100 * 1 + 45 * 0.1) = 3.06
  4. Master account aggregated fill ratio = (100+20+200+20+300+20) / (10 * 1 + 15 * 0.1 + 100 * 1 + 30 * 0.1 + 100 * 1 + 45 * 0.1) = 3.01
  5. Rate limit of accounts
    1. Account A = max(10.4, 3.01) = 10.4 -> 2500 order requests/2s
    2. Account B = max(2.13, 3.01) = 3.01 -> 1750 order requests/2s
    3. Account C = max(3.06, 3.01) = 3.06 -> 1750 order requests/2s

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.

Market Maker Program

High-caliber trading teams are welcomed to work with OKX as market makers in providing a liquid, fair, and orderly platform to all users. OKX market makers could enjoy favourable fees in return for meeting the market making obligations.

Prerequisites (Satisfy any condition):

Interested parties can reach out to us using this form: https://okx.typeform.com/contact-sales

Remarks:

Market making obligations and trading fees will be shared to successful parties only.

Broker Program

If your business platform offers cryptocurrency services, you can apply to join the OKX Broker Program, become our partner broker, enjoy exclusive broker services, and earn high rebates through trading fees generated by OKX users.
The Broker Program includes, and is not limited to, integrated trading platforms, trading bots, copy trading platforms, trading bot providers, quantitative strategy institutions, asset management platforms etc.

Relevant information for specific Broker Program documentation and product services will be provided following successful applications.

Trading Account

The API endpoints of Account require authentication.

REST API

Get instruments

Retrieve available instruments info of current account.

Rate Limit: 20 requests per 2 seconds

Rate limit rule: UserId + InstrumentType

HTTP Request

GET /api/v5/account/instruments

Request Example

GET /api/v5/account/instruments?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)

result = accountAPI.get_instruments(instType="SPOT")
print(result)

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
MARGIN: Margin
SWAP: Perpetual Futures
FUTURES: Expiry Futures
OPTION: Option
uly String Conditional Underlying
Only applicable to FUTURES/SWAP/OPTION.If instType is OPTION, either uly or instFamily is required.
instFamily String Conditional Instrument family
Only applicable to FUTURES/SWAP/OPTION. If instType is OPTION, either uly or instFamily is required.
instId String No Instrument ID

Response Example

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

Response Parameters

Parameter Type Description
instType String Instrument type
instId String Instrument ID, e.g. BTC-USD-SWAP
uly String Underlying, e.g. BTC-USD
Only applicable to MARGIN/FUTURES/SWAP/OPTION
instFamily String Instrument family, e.g. BTC-USD
Only applicable to MARGIN/FUTURES/SWAP/OPTION
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
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
ruleType String Trading rule types
normal: normal trading
pre_market: pre-market trading
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.
The minimum order quantity of a single TWAP order is minSz*2
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 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",
                    "smtSyncEq": "0",
                    "fixedBal": "0",
                    "frozenBal": "158.573",
                    "imr": "",
                    "interest": "0",
                    "isoEq": "0",
                    "isoLiab": "0",
                    "isoUpl": "0",
                    "liab": "0",
                    "maxLoan": "0",
                    "mgnRatio": "",
                    "mmr": "",
                    "notionalLever": "",
                    "ordFrozen": "0",
                    "rewardBal": "0",
                    "spotInUseAmt": "",
                    "clSpotInUseAmt": "",
                    "maxSpotInUse": "",
                    "spotIsoBal": "0",
                    "stgyEq": "150",
                    "twap": "0",
                    "uTime": "1705449605015",
                    "upl": "-7.545600000000006",
                    "uplLiab": "0",
                    "spotBal": "",
                    "openAvgPx": "",
                    "accAvgPx": "",
                    "spotUpl": "",
                    "spotUplRatio": "",
                    "totalPnl": "",
                    "totalPnlRatio": ""
                }
            ],
            "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 Spot and futures mode/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 Spot and futures mode/Multi-currency margin/Portfolio margin
> availEq String Available equity of currency
Applicable to Spot and futures mode/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
> frozenBal String Frozen balance of currency
> ordFrozen String Margin frozen for open orders
Applicable to Spot mode/Spot and futures mode/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 Spot and futures mode/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
> rewardBal String Trial fund balance
> isoLiab String Isolated liabilities of currency
Applicable to Multi-currency margin/Portfolio margin
> mgnRatio String Cross margin ratio of currency
The index for measuring the risk of a certain asset in the account.
Applicable to Spot and futures mode and when there is cross position
> imr String Cross initial margin requirement at the currency level
Applicable to Spot and futures mode and when there is cross position
> mmr String Cross maintenance margin requirement at the currency level
Applicable to Spot and futures mode and when there is cross position
> 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 Spot and futures mode
> stgyEq String Strategy equity
> isoUpl String Isolated unrealized profit and loss of currency
Applicable to Spot and futures mode/Multi-currency margin/Portfolio margin
> spotInUseAmt String Spot in use amount
Applicable to Portfolio margin
> clSpotInUseAmt String User-defined spot risk offset amount
Applicable to Portfolio margin
> maxSpotInUse String Max possible spot risk offset amount
Applicable to Portfolio margin
> spotIsoBal String Spot isolated balance
Applicable to copy trading
Applicable to Spot mode/Spot and futures mode
> smtSyncEq String Smark sync equity
The default is "0", only applicable to copy trader
> spotBal String Spot balance. The unit is currency, e.g. BTC. Clicking knows more
> openAvgPx Array Spot average cost price. The unit is USD. Clicking knows more
> accAvgPx Array Spot accumulated cost price. The unit is USD. Clicking knows more
> spotUpl String Spot unrealized profit and loss. The unit is USD. Clicking knows more
> spotUplRatio String Spot unrealized profit and loss ratio. Clicking knows more
> totalPnl String Spot accumulated profit and loss. The unit is USD. Clicking knows more
> totalPnlRatio String Spot accumulated profit and loss ratio. Clicking knows more

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

Parameters Spot mode Spot and futures mode Multi-currency margin mode Portfolio margin mode
uTime Yes Yes Yes Yes
totalEq Yes Yes Yes Yes
isoEq Yes Yes Yes
adjEq Yes Yes
ordFroz Yes Yes
imr Yes Yes
mmr Yes Yes
mgnRatio Yes Yes
notionalUsd Yes Yes
upl Yes Yes
details Yes Yes
> ccy Yes Yes Yes Yes
> eq Yes Yes Yes Yes
> cashBal Yes Yes Yes Yes
> uTime Yes Yes Yes Yes
> isoEq Yes Yes Yes
> availEq Yes Yes Yes
> disEq Yes Yes Yes Yes
> availBal Yes Yes Yes Yes
> frozenBal Yes Yes Yes Yes
> ordFrozen Yes Yes Yes Yes
> liab Yes Yes
> upl Yes Yes Yes
> uplLiab Yes Yes
> crossLiab Yes Yes
> isoLiab Yes Yes
> mgnRatio Yes
> interest Yes Yes
> twap Yes Yes
> maxLoan Yes Yes
> eqUsd Yes Yes Yes Yes
> notionalLever Yes
> stgyEq Yes Yes Yes Yes
> isoUpl Yes Yes Yes
> spotInUseAmt Yes
> spotIsoBal Yes Yes
> imr Yes
> mmr Yes
> smtSyncEq Yes Yes Yes Yes
> spotBal Yes Yes Yes Yes
> openAvgPx Yes Yes Yes Yes
> accAvgPx Yes Yes Yes Yes
> spotUpl Yes Yes Yes Yes
> spotUplRatio Yes Yes Yes Yes
> totalPnl Yes Yes Yes Yes
> totalPnlRatio Yes Yes Yes Yes

Get positions

Retrieve information on your positions. When the account is in net mode, net positions will be displayed, and when the account is in long/short mode, long or short positions will be displayed. Return in reverse chronological order using ctime.

Rate Limit: 10 requests per 2 seconds

Rate limit rule: UserID

HTTP Request

GET /api/v5/account/positions

Request Example

# Query BTC-USDT position information
GET /api/v5/account/positions?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 positions information
result = accountAPI.get_positions()
print(result)

Request Parameters

Parameter Type Required Description
instType String No Instrument type
MARGIN
SWAP
FUTURES
OPTION
instId will be checked against instType when both parameters are passed.
instId String No Instrument ID, e.g. BTC-USDT-SWAP. Single instrument ID or multiple instrument IDs (no more than 10) separated with comma
posId String No Single position ID or multiple position IDs (no more than 20) separated with comma.
There is attribute expiration, the posId and position information will be cleared if it is more than 30 days after the last full close position.

Response Example

{
    "code": "0",
    "data": [
        {
            "adl": "1",
            "availPos": "0.00190433573",
            "avgPx": "62961.4",
            "baseBal": "",
            "baseBorrowed": "",
            "baseInterest": "",
            "bePx": "",
            "bizRefId": "",
            "bizRefType": "",
            "cTime": "1724740225685",
            "ccy": "BTC",
            "clSpotInUseAmt": "",
            "closeOrderAlgo": [],
            "deltaBS": "",
            "deltaPA": "",
            "fee": "",
            "fundingFee": "",
            "gammaBS": "",
            "gammaPA": "",
            "idxPx": "62890.5",
            "imr": "",
            "instId": "BTC-USDT",
            "instType": "MARGIN",
            "interest": "0",
            "last": "62892.9",
            "lever": "5",
            "liab": "-99.9998177776581948",
            "liabCcy": "USDT",
            "liqPenalty": "",
            "liqPx": "53615.448336593756",
            "margin": "0.000317654",
            "markPx": "62891.9",
            "maxSpotInUseAmt": "",
            "mgnMode": "isolated",
            "mgnRatio": "9.404143929947395",
            "mmr": "0.0000318005395854",
            "notionalUsd": "119.756628017499",
            "optVal": "",
            "pendingCloseOrdLiabVal": "0",
            "pnl": "",
            "pos": "0.00190433573",
            "posCcy": "BTC",
            "posId": "1752810569801498626",
            "posSide": "net",
            "quoteBal": "",
            "quoteBorrowed": "",
            "quoteInterest": "",
            "realizedPnl": "",
            "spotInUseAmt": "",
            "spotInUseCcy": "",
            "thetaBS": "",
            "thetaPA": "",
            "tradeId": "785524470",
            "uTime": "1724742632153",
            "upl": "-0.0000033452492717",
            "uplLastPx": "-0.0000033199677697",
            "uplRatio": "-0.0105311101755551",
            "uplRatioLastPx": "-0.0104515220008934",
            "usdPx": "",
            "vegaBS": "",
            "vegaPA": ""
        }
    ],
    "msg": ""
}

Response Parameters

Parameter Type Description
instType String Instrument type
mgnMode String Margin mode
cross
isolated
posId String Position ID
posSide String Position side
long, pos is positive
short, pos is positive
net (FUTURES/SWAP/OPTION: positive pos means long position and negative pos means short position. For MARGIN, pos is always positive, posCcy being base currency means long position, posCcy being quote currency means short position.)
pos String Quantity of positions. In the isolated margin mode, when doing manual transfers, a position with pos of 0 will be generated after the deposit is transferred
baseBal String Base currency balance, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
quoteBal String Quote currency balance, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
baseBorrowed String Base currency amount already borrowed, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
baseInterest String Base Interest, undeducted interest that has been incurred, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
quoteBorrowed String Quote currency amount already borrowed, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
quoteInterest String Quote Interest, undeducted interest that has been incurred, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
posCcy String Position currency, only applicable to MARGIN positions.
availPos String Position that can be closed
Only applicable to MARGIN, FUTURES/SWAP in the long-short mode and OPTION.
For Margin position, the rest of sz will be SPOT trading after the liability is repaid while closing the position. Please get the available reduce-only amount from "Get maximum available tradable amount" if you want to reduce the amount of SPOT trading as much as possible.
avgPx String Average open price
markPx String Latest Mark price
upl String Unrealized profit and loss calculated by mark price.
uplRatio String Unrealized profit and loss ratio calculated by mark price.
uplLastPx String Unrealized profit and loss calculated by last price. Main usage is showing, actual value is upl.
uplRatioLastPx String Unrealized profit and loss ratio calculated by last price.
instId String Instrument ID, e.g. BTC-USDT-SWAP
lever String Leverage
Not applicable to OPTION and positions of cross margin mode under Portfolio margin
liqPx String Estimated liquidation price
Not applicable to OPTION
imr String Initial margin requirement, only applicable to cross.
margin String Margin, can be added or reduced. Only applicable to isolated.
mgnRatio String Margin ratio
mmr String Maintenance margin requirement
liab String Liabilities, only applicable to MARGIN.
liabCcy String Liabilities currency, only applicable to MARGIN.
interest String Interest. Undeducted interest that has been incurred.
tradeId String Last trade ID
optVal String Option Value, only applicable to OPTION.
pendingCloseOrdLiabVal String The amount of close orders of isolated margin liability.
notionalUsd String Notional value of positions in USD
adl String Auto-deleveraging (ADL) indicator
Divided into 5 levels, from 1 to 5, the smaller the number, the weaker the adl intensity.
ccy String Currency used for margin
last String Latest traded price
idxPx String Latest underlying index price
usdPx String Latest USD price of the ccy on the market, only applicable to OPTION
bePx String Breakeven price
deltaBS String delta: Black-Scholes Greeks in dollars, only applicable to OPTION
deltaPA String delta: Greeks in coins, only applicable to OPTION
gammaBS String gamma: Black-Scholes Greeks in dollars, only applicable to OPTION
gammaPA String gamma: Greeks in coins, only applicable to OPTION
thetaBS String theta:Black-Scholes Greeks in dollars, only applicable to OPTION
thetaPA String theta:Greeks in coins, only applicable to OPTION
vegaBS String vega:Black-Scholes Greeks in dollars, only applicable to OPTION
vegaPA String vega:Greeks in coins, only applicable to OPTION
spotInUseAmt String Spot in use amount
Applicable to Portfolio margin
spotInUseCcy String Spot in use unit, e.g. BTC
Applicable to Portfolio margin
clSpotInUseAmt String User-defined spot risk offset amount
Applicable to Portfolio margin
maxSpotInUseAmt String Max possible spot risk offset amount
Applicable to Portfolio margin
bizRefId String External business id, e.g. experience coupon id
bizRefType String External business type
realizedPnl String Realized profit and loss
Only applicable to FUTURES/SWAP/OPTION
realizedPnl=pnl+fee+fundingFee+liqPenalty
pnl String Accumulated pnl of closing order(s)
fee String Accumulated fee
Negative number represents the user transaction fee charged by the platform.Positive number represents rebate.
fundingFee String Accumulated funding fee
liqPenalty String Accumulated liquidation penalty. It is negative when there is a value.
closeOrderAlgo Array Close position algo orders attached to the position. This array will have values only after you request "Place algo order" with closeFraction=1.
> algoId String Algo ID
> slTriggerPx String Stop-loss trigger price.
> slTriggerPxType String Stop-loss trigger price type.
last:last price
index:index price
mark:mark price
> tpTriggerPx String Take-profit trigger price.
> tpTriggerPxType String Take-profit trigger price type.
last:last price
index:index price
mark:mark price
> closeFraction String Fraction of position to be closed when the algo order is triggered.
cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
uTime String Latest time position was adjusted, Unix timestamp format in milliseconds, e.g. 1597026383085

Get positions history

Retrieve the updated position data for the last 3 months. Return in reverse chronological order using utime. Getting positions history is not supported under Portfolio margin mode.

Rate Limit: 10 request per 2 seconds

Rate limit rule: UserID

HTTP Request

GET /api/v5/account/positions-history

Request Example

GET /api/v5/account/positions-history
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 positions history
result = accountAPI.get_positions_history()
print(result)

Request Parameters

Parameter Type Required Description
instType String No Instrument type
MARGIN
SWAP
FUTURES
OPTION
instId String No Instrument ID, e.g. BTC-USD-SWAP
mgnMode String No Margin mode
cross isolated
type String No The type of latest close position
1: Close position partially;2:Close all;3:Liquidation;4:Partial liquidation; 5:ADL;
It is the latest type if there are several types for the same position.
posId String No Position ID. There is attribute expiration. The posId will be expired if it is more than 30 days after the last full close position, then position will use new posId.
after String No Pagination of data to return records earlier than the requested uTime, Unix timestamp format in milliseconds, e.g. 1597026383085
before String No Pagination of data to return records newer than the requested uTime, Unix timestamp format in milliseconds, e.g. 1597026383085
limit String No Number of results per request. The maximum is 100. The default is 100. All records that have the same uTime will be returned at the current request

Response Example

{
    "code": "0",
    "data": [
        {
            "cTime": "1654177169995",
            "ccy": "BTC",
            "closeAvgPx": "29786.5999999789081085",
            "closeTotalPos": "1",
            "instId": "BTC-USD-SWAP",
            "instType": "SWAP",
            "lever": "10.0",
            "mgnMode": "cross",
            "openAvgPx": "29783.8999999995535393",
            "openMaxPos": "1",
            "realizedPnl": "0.001",
            "fee": "-0.0001",
            "fundingFee": "0",
            "liqPenalty": "0",
            "pnl": "0.0011",
            "pnlRatio": "0.000906447858888",
            "posId": "452587086133239818",
            "posSide": "long",
            "direction": "long",
            "triggerPx": "",
            "type": "1",
            "uTime": "1654177174419",
            "uly": "BTC-USD"
        }
    ],
    "msg": ""
}

Response Parameters

Parameter Type Description
instType String Instrument type
instId String Instrument ID
mgnMode String Margin mode
cross isolated
type String The type of latest close position
1:Close position partially;2:Close all;3:Liquidation;4:Partial liquidation; 5:ADL;
It is the latest type if there are several types for the same position.
cTime String Created time of position
uTime String Updated time of position
openAvgPx String Average price of opening position
closeAvgPx String Average price of closing position
posId String Position ID
openMaxPos String Max quantity of position
closeTotalPos String Position's cumulative closed volume
realizedPnl String Realized profit and loss
Only applicable to FUTURES/SWAP/OPTION
realizedPnl=pnl+fee+fundingFee+liqPenalty
fee String Accumulated fee
Negative number represents the user transaction fee charged by the platform.Positive number represents rebate.
fundingFee String Accumulated funding fee
liqPenalty String Accumulated liquidation penalty. It is negative when there is a value.
pnl String Profit and loss
pnlRatio String P&L ratio
posSide String Position mode side
long: Hedge mode long
short: Hedge mode short
net: Net mode
lever String Leverage
direction String Direction: long short
Only applicable to MARGIN/FUTURES/SWAP/OPTION
triggerPx String trigger mark price. There is value when type is equal to 3, 4 or 5. It is "" when type is equal to 1 or 2
uly String Underlying
ccy String Currency used for margin

Get account and position risk

Get account and position risk

Rate Limit: 10 requests per 2 seconds

Rate limit rule: UserID

HTTP Requests

GET /api/v5/account/account-position-risk

Request Example

GET /api/v5/account/account-position-risk

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 and position risk
result = accountAPI.get_account_position_risk()
print(result)

Request Parameters

Parameter Type Required Description
instType String No Instrument type
MARGIN
SWAP
FUTURES
OPTION

Response Example

{
    "code":"0",
    "data":[
        {
            "adjEq":"174238.6793649711331679",
            "balData":[
                {
                    "ccy":"BTC",
                    "disEq":"78846.7803721021362242",
                    "eq":"1.3863533369419636"
                },
                {
                    "ccy":"USDT",
                    "disEq":"73417.2495112863300127",
                    "eq":"73323.395564963177146"
                }
            ],
            "posData":[
                {
                    "baseBal": "0.4",
                    "ccy": "",
                    "instId": "BTC-USDT",
                    "instType": "MARGIN",
                    "mgnMode": "isolated",
                    "notionalCcy": "0",
                    "notionalUsd": "0",
                    "pos": "0",
                    "posCcy": "",
                    "posId": "310388685292318723",
                    "posSide": "net",
                    "quoteBal": "0"
                }
            ],
            "ts":"1620282889345"
        }
    ],
    "msg":""
}

Response Parameters

Parameters Types Description
ts String Update time of account information, millisecond format of Unix timestamp, e.g. 1597026383085
adjEq String Adjusted / Effective equity in USD
Applicable to Multi-currency margin and Portfolio margin
balData Array Detailed asset information in all currencies
> ccy String Currency
> eq String Equity of currency
> disEq String Discount equity of currency in USD.
posData Array Detailed position information in all currencies
> instType String Instrument type
> mgnMode String Margin mode
cross
isolated
> posId String Position ID
> instId String Instrument ID, e.g. BTC-USDT-SWAP
> pos String Quantity of positions contract. In the isolated margin mode, when doing manual transfers, a position with pos of 0 will be generated after the deposit is transferred
> baseBal String Base currency balance, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
> quoteBal String Quote currency balance, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
> posSide String Position side
long
short
net (FUTURES/SWAP/OPTION: positive pos means long position and negative pos means short position. MARGIN: posCcy being base currency means long position, posCcy being quote currency means short position.)
> posCcy String Position currency, only applicable to MARGIN positions.
> ccy String Currency used for margin
> notionalCcy String Notional value of positions in coin
> notionalUsd String Notional value of positions in USD

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=MARGIN

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
MARGIN
SWAP
FUTURES
OPTION
instId String No Instrument ID, e.g. BTC-USDT
ccy String No Bill currency
mgnMode String No Margin mode
isolated
cross
ctType String No Contract type
linear
inverse
Only applicable to FUTURES/SWAP
type String No Bill type
1: Transfer
2: Trade
3: Delivery
4: Forced repayment
5: Liquidation
6: Margin transfer
7: Interest deduction
8: Funding fee
9: ADL
10: Clawback
11: System token conversion
12: Strategy transfer
13: DDH
14: Block trade
15: Quick Margin
22: Repay
24: Spread trading
26: Structured products
250: Copy trader profit sharing expenses
251: Copy trader profit sharing refund
subType String No Bill subtype
1: Buy
2: Sell
3: Open long
4: Open short
5: Close long
6: Close short
9: Interest deduction for Market loans
11: Transfer in
12: Transfer out
14: Interest deduction for VIP loans
160: Manual margin increase
161: Manual margin decrease
162: Auto margin increase
114: Forced repayment buy
115: Forced repayment sell
118: System token conversion transfer in
119: System token conversion transfer out
100: Partial liquidation close long
101: Partial liquidation close short
102: Partial liquidation buy
103: Partial liquidation sell
104: Liquidation long
105: Liquidation short
106: Liquidation buy
107: Liquidation sell
108:clawback
109: Liquidation fees
110: Liquidation transfer in
111: Liquidation transfer out
125: ADL close long
126: ADL close short
127: ADL buy
128: ADL sell
131: ddh buy
132: ddh sell
170: Exercised(ITM buy side)
171: Counterparty exercised(ITM sell side)
172: Expired(Non-ITM buy and sell side)
112: Delivery long
113: Delivery short
117: Delivery/Exercise clawback
173: Funding fee expense
174: Funding fee income
200:System transfer in
201: Manually transfer in
202: System transfer out
203: Manually transfer out
204: block trade buy
205: block trade sell
206: block trade open long
207: block trade open short
208: block trade close open
209: block trade close short
210: Manual Borrowing of quick margin
211: Manual Repayment of quick margin
212: Auto borrow of quick margin
213: Auto repay of quick margin
220: Transfer in when using USDT to buy OPTION
221: Transfer out when using USDT to buy OPTION
16: Repay forcibly
17: Repay interest by borrowing forcibly
224: Repayment transfer in
225: Repayment transfer out
236: Easy convert in
237: Easy convert out
250: Profit sharing expenses
251: Profit sharing refund
280: SPOT profit sharing expenses
281: SPOT profit sharing refund
270: Spread trading buy
271: Spread trading sell
272: Spread trading open long
273: Spread trading open short
274: Spread trading close long
275: Spread trading close short
280: SPOT profit sharing expenses
281: SPOT profit sharing refund
284: Copy trade automatic transfer in
285: Copy trade manual transfer in
286: Copy trade automatic transfer out
287: Copy trade manual transfer out
290: Crypto dust auto-transfer out
293: Fixed loan interest deduction
294: Fixed loan interest refund
295 : Fixed loan overdue penalty
296: From structured order placements
297: To structured order placements
298: From structured settlements
299: To structured settlements
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 ts. Unix timestamp format in milliseconds, e.g. 1597026383085
end String No Filter with an end timestamp 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": [{
        "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 3: Open long 4: Open short 5: Close long 6: Close short 204: block trade buy 205: block trade sell 206: block trade open long 207: block trade open short 208: block trade close open 209: block trade close short 114: Forced repayment buy 115: Forced repayment sell
  • Liquidation Price for
  • 100: Partial liquidation close long 101: Partial liquidation close short 102: Partial liquidation buy 103: Partial liquidation sell 104: Liquidation long 105: Liquidation short 106: Liquidation buy 107: Liquidation sell 16: Repay forcibly 17: Repay interest by borrowing forcibly 110: Liquidation transfer in 111: Liquidation transfer out
  • Delivery price for
  • 112: Delivery long 113: Delivery short
  • Exercise price for
  • 170: Exercised 171: Counterparty exercised 172: Expired OTM
  • Mark price for
  • 173: Funding fee expense 174: Funding fee income
    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.
    Trading fee rule
    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=MARGIN
    
    
    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
    MARGIN
    SWAP
    FUTURES
    OPTION
    instId String No Instrument ID, e.g. BTC-USDT
    ccy String No Bill currency
    mgnMode String No Margin mode
    isolated
    cross
    ctType String No Contract type
    linear
    inverse
    Only applicable to FUTURES/SWAP
    type String No Bill type
    1: Transfer
    2: Trade
    3: Delivery
    4: Forced repayment
    5: Liquidation
    6: Margin transfer
    7: Interest deduction
    8: Funding fee
    9: ADL
    10: Clawback
    11: System token conversion
    12: Strategy transfer
    13: DDH
    14: Block trade
    15: Quick Margin
    22: Repay
    24: Spread trading
    26: Structured products
    250: Copy trader profit sharing expenses
    251: Copy trader profit sharing refund
    subType String No Bill subtype
    1: Buy
    2: Sell
    3: Open long
    4: Open short
    5: Close long
    6: Close short
    9: Interest deduction for Market loans
    11: Transfer in
    12: Transfer out
    14: Interest deduction for VIP loans
    160: Manual margin increase
    161: Manual margin decrease
    162: Auto margin increase
    114: Forced repayment buy
    115: Forced repayment sell
    118: System token conversion transfer in
    119: System token conversion transfer out
    100: Partial liquidation close long
    101: Partial liquidation close short
    102: Partial liquidation buy
    103: Partial liquidation sell
    104: Liquidation long
    105: Liquidation short
    106: Liquidation buy
    107: Liquidation sell
    108:clawback
    109: Liquidation fees
    110: Liquidation transfer in
    111: Liquidation transfer out
    125: ADL close long
    126: ADL close short
    127: ADL buy
    128: ADL sell
    131: ddh buy
    132: ddh sell
    170: Exercised(ITM buy side)
    171: Counterparty exercised(ITM sell side)
    172: Expired(Non-ITM buy and sell side)
    112: Delivery long
    113: Delivery short
    117: Delivery/Exercise clawback
    173: Funding fee expense
    174: Funding fee income
    200:System transfer in
    201: Manually transfer in
    202: System transfer out
    203: Manually transfer out
    204: block trade buy
    205: block trade sell
    206: block trade open long
    207: block trade open short
    208: block trade close open
    209: block trade close short
    210: Manual Borrowing of quick margin
    211: Manual Repayment of quick margin
    212: Auto borrow of quick margin
    213: Auto repay of quick margin
    220: Transfer in when using USDT to buy OPTION
    221: Transfer out when using USDT to buy OPTION
    16: Repay forcibly
    17: Repay interest by borrowing forcibly
    224: Repayment transfer in
    225: Repayment transfer out
    236: Easy convert in
    237: Easy convert out
    250: Profit sharing expenses
    251: Profit sharing refund
    280: SPOT profit sharing expenses
    281: SPOT profit sharing refund
    270: Spread trading buy
    271: Spread trading sell
    272: Spread trading open long
    273: Spread trading open short
    274: Spread trading close long
    275: Spread trading close short
    280: SPOT profit sharing expenses
    281: SPOT profit sharing refund
    284: Copy trade automatic transfer in
    285: Copy trade manual transfer in
    286: Copy trade automatic transfer out
    287: Copy trade manual transfer out
    290: Crypto dust auto-transfer out
    293: Fixed loan interest deduction
    294: Fixed loan interest refund
    295 : Fixed loan overdue penalty
    296: From structured order placements
    297: To structured order placements
    298: From structured settlements
    299: To structured settlements
    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 ts. Unix timestamp format in milliseconds, e.g. 1597026383085
    end String No Filter with an end timestamp 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": [{
            "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 3: Open long 4: Open short 5: Close long 6: Close short 204: block trade buy 205: block trade sell 206: block trade open long 207: block trade open short 208: block trade close open 209: block trade close short 114: Forced repayment buy 115: Forced repayment sell
  • Liquidation Price for
  • 100: Partial liquidation close long 101: Partial liquidation close short 102: Partial liquidation buy 103: Partial liquidation sell 104: Liquidation long 105: Liquidation short 106: Liquidation buy 107: Liquidation sell 16: Repay forcibly 17: Repay interest by borrowing forcibly 110: Liquidation transfer in 111: Liquidation transfer out
  • Delivery price for
  • 112: Delivery long 113: Delivery short
  • Exercise price for
  • 170: Exercised 171: Counterparty exercised 172: Expired OTM
  • Mark price for
  • 173: Funding fee expense 174: Funding fee income
    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.
    Trading fee rule
    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

    Apply bills details (since 2021)

    Apply for bill data since 1 February, 2021 except for the current quarter.

    Rate Limit:12 requests per day

    Rate limit rule: UserID

    Permissions: Read

    HTTP Request

    POST /api/v5/account/bills-history-archive

    Request Example

    POST /api/v5/account/bills-history-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": [
            {
                "result": "true",
                "ts": "1646892328000"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    result String Whether there is already a download link for this section
    true: Existed, can check from "Get bills details (since 2021)".
    false: Does not exist and is generating, can check the download link after 30 hours
    ts String Download link generation time, Unix timestamp format in milliseconds, e.g. 1597026383085

    Get bills details (since 2021)

    Apply for bill data since 1 February, 2021 except for the current quarter.

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: UserID

    Permissions: Read

    HTTP Request

    GET /api/v5/account/bills-history-archive

    Response Example

    GET /api/v5/account/bills-history-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" "failed": Failed, please apply again

    Field descriptions in the decompressed CSV file

    Parameter Type Description
    instType String Instrument type
    billId String Bill ID
    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 3: Open long 4: Open short 5: Close long 6: Close short 204: block trade buy 205: block trade sell 206: block trade open long 207: block trade open short 208: block trade close open 209: block trade close short 114: Forced repayment buy 115: Forced repayment sell
  • Liquidation Price for
  • 100: Partial liquidation close long 101: Partial liquidation close short 102: Partial liquidation buy 103: Partial liquidation sell 104: Liquidation long 105: Liquidation short 106: Liquidation buy 107: Liquidation sell 16: Repay forcibly 17: Repay interest by borrowing forcibly 110: Liquidation transfer in 111: Liquidation transfer out
  • Delivery price for
  • 112: Delivery long 113: Delivery short
  • Exercise price for
  • 170: Exercised 171: Counterparty exercised 172: Expired OTM
  • Mark price for
  • 173: Funding fee expense 174: Funding fee income
    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.
    Trading fee rule
    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
    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",
                "acctStpMode": "cancel_maker",
                "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",
                "discountType": "0",
                "liquidationGear": "0"
            }
        ],
        "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: Spot mode
    2: Spot and futures mode
    3: Multi-currency margin
    4: Portfolio margin
    acctStpMode String Account self-trade prevention mode
    cancel_maker
    cancel_taker
    cancel_both
    Users can log in to the webpage through the master account to modify this configuration
    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 or Access token
    read_only: Read
    trade: Trade
    withdraw: Withdraw
    discountType String Discount rule type for current account
    0: Original discount rate rules, the default value
    1: New discount rules
    After new discount rate rules are effective completely, this parameter will be removed from the endpoint. Advice you to prepare in advance.
    liquidationGear String The margin ratio level of liquidation alert
    3 means that you will get hourly liquidation alerts on app and channel "Position risk warning" when your margin level drops to or below 300%
    0 means that there is not alert

    Set position mode

    Spot and futures mode and Multi-currency mode: FUTURES and SWAP support both long/short mode and net mode. In net mode, users can only have positions in one direction; In long/short mode, users can hold positions in long and short directions.
    Portfolio margin mode: FUTURES and SWAP only support net mode

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/set-position-mode

    Request Example

    POST /api/v5/account/set-position-mode
    body 
    {
        "posMode":"long_short_mode"
    }
    
    
    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)
    
    # Set position mode
    result = accountAPI.set_position_mode(
        posMode="long_short_mode"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    posMode String Yes Position mode
    long_short_mode: long/short, only applicable to FUTURES/SWAP
    net_mode: net

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "posMode": "long_short_mode"
        }]
    }
    

    Response Parameters

    Parameter Type Description
    posMode String Position mode

    Set leverage


    There are 10 different scenarios for leverage setting:

    1. Set leverage for MARGIN instruments under isolated-margin trade mode at pairs level.
    2. Set leverage for MARGIN instruments under cross-margin trade mode and Spot and futures mode account mode at pairs level.
    3. Set leverage for MARGIN instruments under cross-margin trade mode and Multi-currency margin at currency level.
    4. Set leverage for MARGIN instruments under cross-margin trade mode and Portfolio margin at currency level.
    5. Set leverage for FUTURES instruments under cross-margin trade mode at underlying level.
    6. Set leverage for FUTURES instruments under isolated-margin trade mode and buy/sell position mode at contract level.
    7. Set leverage for FUTURES instruments under isolated-margin trade mode and long/short position mode at contract and position side level.
    8. Set leverage for SWAP instruments under cross-margin trade at contract level.
    9. Set leverage for SWAP instruments under isolated-margin trade mode and buy/sell position mode at contract level.
    10. Set leverage for SWAP instruments under isolated-margin trade mode and long/short position mode at contract and position side level.

    Note that the request parameter posSide is only required when margin mode is isolated in long/short position mode for FUTURES/SWAP instruments (see scenario 7 and 10 above).
    Please refer to the request examples on the right for each case.

    Rate limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/set-leverage

    Request Example

    # 1. Set leverage for `MARGIN` instruments under `isolated-margin` trade mode at pairs level.
    POST /api/v5/account/set-leverage
    body
    {
        "instId":"BTC-USDT",
        "lever":"5",
        "mgnMode":"isolated"
    }
    
    # 2. Set leverage for `MARGIN` instruments under `cross-margin` trade mode and Spot and futures mode account mode at pairs level.
    POST /api/v5/account/set-leverage
    body
    {
        "instId":"BTC-USDT",
        "lever":"5",
        "mgnMode":"cross"
    }
    
    # 3. Set leverage for `MARGIN` instruments under `cross-margin` trade mode and Multi-currency margin at currency level.
    POST /api/v5/account/set-leverage
    body
    {
        "ccy":"BTC",
        "lever":"5",
        "mgnMode":"cross"
    }
    
    # 4. Set leverage for `MARGIN` instruments under `cross-margin` trade mode and Portfolio margin at currency level.
    POST /api/v5/account/set-leverage
    body
    {
        "ccy":"BTC",
        "lever":"5",
        "mgnMode":"cross"
    }
    
    # 5. Set leverage for `FUTURES` instruments under `cross-margin` trade mode at underlying level.
    POST /api/v5/account/set-leverage
    body
    {
        "instId":"BTC-USDT-200802",
        "lever":"5",
        "mgnMode":"cross"
    }
    
    # 6. Set leverage for `FUTURES` instruments under `isolated-margin` trade mode and buy/sell order placement mode at contract level.
    POST /api/v5/account/set-leverage
    body
    {
        "instId":"BTC-USDT-200802",
        "lever":"5",
        "mgnMode":"isolated"
    }
    
    # 7. Set leverage for `FUTURES` instruments under `isolated-margin` trade mode and long/short order placement mode at contract and position side level.
    POST /api/v5/account/set-leverage
    body
    {
        "instId":"BTC-USDT-200802",
        "lever":"5",
        "posSide":"long",
        "mgnMode":"isolated"
    }
    
    # 8. Set leverage for `SWAP` instruments under `cross-margin` trade at contract level.
    POST /api/v5/account/set-leverage
    body
    {
        "instId":"BTC-USDT-SWAP",
        "lever":"5",
        "mgnMode":"cross"
    }
    
    # 9. Set leverage for `SWAP` instruments under `isolated-margin` trade mode and buy/sell order placement mode at contract level.
    POST /api/v5/account/set-leverage
    body
    {
        "instId":"BTC-USDT-SWAP",
        "lever":"5",
        "mgnMode":"isolated"
    }
    
    # 10. Set leverage for `SWAP` instruments under `isolated-margin` trade mode and long/short order placement mode at contract and position side level.
    POST /api/v5/account/set-leverage
    body
    {
        "instId":"BTC-USDT-SWAP",
        "lever":"5",
        "posSide":"long",
        "mgnMode":"isolated"
    }
    
    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)
    
    # Set leverage for MARGIN instruments under isolated-margin trade mode at pairs level.
    result = accountAPI.set_leverage(
        instId="BTC-USDT",
        lever="5",
        mgnMode="isolated"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Conditional Instrument ID
    Under cross mode, either instId or ccy is required; if both are passed, instId will be used by default.
    ccy String Conditional Currency used for margin, used for the leverage setting for the currency in auto borrow.
    Only applicable to cross MARGIN of Multi-currency margin and Portfolio margin
    Required when setting the leverage for automatically borrowing coin.
    lever String Yes Leverage
    mgnMode String Yes Margin mode
    isolated cross
    Can only be cross if ccy is passed.
    posSide String Conditional Position side
    long short
    Only required when margin mode is isolated in long/short mode for FUTURES/SWAP.

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
          "lever": "30",
          "mgnMode": "isolated",
          "instId": "BTC-USDT-SWAP",
          "posSide": "long"
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    lever String Leverage
    mgnMode String Margin mode
    cross isolated
    instId String Instrument ID
    posSide String Position side

    Get maximum order quantity

    The maximum quantity to buy or sell. It corresponds to the "sz" from placement.

    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=isolated
    
    
    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="isolated"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Single instrument or multiple instruments (no more than 5) in the smae instrument type separated with comma, e.g. BTC-USDT,ETH-USDT
    tdMode String Yes Trade mode
    cross isolated cash spot_isolated
    ccy String Conditional Currency used for margin
    Only applicable to MARGIN of Spot and futures mode.
    px String No Price
    When the price is not specified, it will be calculated according to the current limit price for FUTURES and SWAP, the last traded price for other instrument types.
    The parameter will be ignored when multiple instruments are specified.
    leverage String No Leverage for instrument
    The default is current leverage
    Only applicable to MARGIN/FUTURES/SWAP
    unSpotOffset Boolean No true: disable Spot-Derivatives risk offset, false: enable Spot-Derivatives risk offset
    Default is false
    Applicable to Portfolio
    It is effective when Spot-Derivatives risk offset is turned on, otherwise this parameter is ignored.

    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/MARGIN: The maximum quantity in base currency that you can buy
    The cross-margin order under Spot and futures mode mode, quantity of coins is based on base currency.
    FUTURES/SWAP/OPTIONS: The maximum quantity of contracts that you can buy
    maxSell String SPOT/MARGIN: The maximum quantity in quote currency that you can sell
    The cross-margin order under Spot and futures mode mode, quantity of coins is based on base currency.
    FUTURES/SWAP/OPTIONS: The maximum quantity of contracts that you can sell

    Get maximum available balance/equity

    Available balance for isolated margin positions and SPOT, available equity for cross margin positions.

    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 when cross MARGIN BTC-USDT use BTC as margin
    GET /api/v5/account/max-avail-size?instId=BTC-USDT&tdMode=cross&ccy=BTC
    
    # 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
    ccy String Conditional Currency used for margin
    Only applicable to cross MARGIN of Spot and futures mode.
    tdMode String Yes Trade mode
    cross isolated cash spot_isolated
    reduceOnly Boolean No Whether to reduce position only
    Only applicable to MARGIN
    px String No The price of closing position.
    Only applicable to reduceOnly MARGIN.
    unSpotOffset Boolean No true: disable Spot-Derivatives risk offset, false: enable Spot-Derivatives risk offset
    Default is false
    Only applicable to Portfolio margin
    It is effective when Spot-Derivatives risk offset is turned on, otherwise this parameter is ignored.
    quickMgnType String No Quick Margin type. Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    The default value is manual
    (Deprecated)

    Response Example

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

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    availBuy String Maximum available balance/equity to buy
    availSell String Maximum available balance/equity to sell

    Increase/decrease margin

    Increase or decrease the margin of the isolated position. Margin reduction may result in the change of the actual leverage.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/position/margin-balance

    Request Example

    POST /api/v5/account/position/margin-balance 
    body
    {
        "instId":"BTC-USDT-200626",
        "posSide":"short",
        "type":"add",
        "amt":"1"
    }
    
    
    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)
    
    # Increase margin
    result = accountAPI.adjustment_margin(
        instId="BTC-USDT-SWAP",
        posSide="short",
        type= "add",
        amt="1"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID
    posSide String Yes Position side, the default is net
    long
    short
    net
    type String Yes add: add margin
    reduce: reduce margin
    amt String Yes Amount to be increased or decreased.
    ccy String Conditional Currency, only applicable to MARGIN(Quick Margin Mode)

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
                "amt": "0.3",
                "ccy": "BTC",
                "instId": "BTC-USDT",
                "leverage": "",
                "posSide": "net",
                "type": "add"
            }]
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    posSide String Position side, long short
    amt String Amount to be increase or decrease
    type String add: add margin
    reduce: reduce margin
    leverage String Real leverage after the margin adjustment
    ccy String Currency

    Get leverage

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/leverage-info

    Request Example

    GET /api/v5/account/leverage-info?instId=BTC-USDT-200626&mgnMode=cross
    
    
    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 leverage
    result = accountAPI.get_leverage(
        instId="BTC-USDT",
        mgnMode="cross"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID
    Single instrument ID or multiple instrument IDs (no more than 20) separated with comma
    mgnMode String Yes Margin mode
    cross isolated

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "instId": "BTC-USDT-200626",
            "mgnMode": "cross",
            "posSide": "long",
            "lever": "10"
        },{
            "instId": "BTC-USDT-200626",
            "mgnMode": "cross",
            "posSide": "short",
            "lever": "10"
        }]
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    mgnMode String Margin mode
    posSide String Position side
    long
    short
    net
    In long/short mode, the leverage in both directions long short will be returned.
    lever String Leverage

    Get leverage estimated info

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/adjust-leverage-info

    Request Example

    GET /api/v5/account/adjust-leverage-info?instType=MARGIN&mgnMode=isolated&lever=3&instId=BTC-USDT
    
    

    Request Parameters

    Parameter Type Required Description
    instType String Yes Instrument type
    MARGIN
    SWAP
    FUTURES
    mgnMode String Yes Margin mode
    isolated
    cross
    lever String Yes Leverage
    instId String Conditional Instrument ID, e.g. BTC-USDT
    It is required for these scenarioes: SWAP and FUTURES, Margin isolation, Margin cross in Spot and futures mode.
    ccy String Conditional Currency used for margin, e.g. BTC
    It is required for Margin cross in Spot and futures mode, Multi-currency margin and Portfolio margin
    posSide String No posSide
    net: The default value
    long
    short

    Response Example

    {
        "code": "0",
        "data": [
            {
                "estAvailQuoteTrans": "",
                "estAvailTrans": "1.1398040558348279",
                "estLiqPx": "",
                "estMaxAmt": "10.6095865868904898",
                "estMgn": "0.0701959441651721",
                "estQuoteMaxAmt": "176889.6871254563042714",
                "estQuoteMgn": "",
                "existOrd": false,
                "maxLever": "10",
                "minLever": "0.01"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    estAvailQuoteTrans String The estimated margin(in quote currency) can be transferred out under the corresponding leverage
    For cross, it is the maximum quantity that can be transferred from the trading account.
    For isolated, it is the maximum quantity that can be transferred from the isolated position
    Only applicable to MARGIN
    estAvailTrans String The estimated margin can be transferred out under the corresponding leverage.
    For cross, it is the maximum quantity that can be transferred from the trading account.
    For isolated, it is the maximum quantity that can be transferred from the isolated position
    The unit is base currency for MARGIN
    estLiqPx String The estimated liquidation price under the corresponding leverage. Only return when there is a position.
    estMgn String The estimated margin needed by position under the corresponding leverage.
    For the MARGIN position, it is margin in base currency
    estQuoteMgn String The estimated margin (in quote currency) needed by position under the corresponding leverage
    estMaxAmt String For MARGIN, it is the estimated maximum loan in base currency under the corresponding leverage
    For SWAP and FUTURES, it is the estimated maximum quantity of contracts that can be opened under the corresponding leverage
    estQuoteMaxAmt String The MARGIN estimated maximum loan in quote currency under the corresponding leverage.
    existOrd Boolean Whether there is pending orders
    true
    false
    maxLever String Maximum leverage
    minLever String Minimum leverage

    Get the maximum loan of instrument

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/max-loan

    Request Example

    # Max loan of isolated `MARGIN` in `Spot and futures mode`
    GET  /api/v5/account/max-loan?instId=BTC-USDT&mgnMode=isolated
    
    # Max loan of cross `MARGIN` in `Spot and futures mode` (Margin Currency is BTC)
    GET  /api/v5/account/max-loan?instId=BTC-USDT&mgnMode=cross&mgnCcy=BTC
    
    # Max loan of cross `MARGIN` in `Multi-currency margin`
    GET  /api/v5/account/max-loan?instId=BTC-USDT&mgnMode=cross
    
    
    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)
    
    # Max loan of cross MARGIN in Spot and futures mode (Margin Currency is BTC)
    result = accountAPI.get_max_loan(
        instId="BTC-USDT",
        mgnMode="cross",
        mgnCcy="BTC"
    )
    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
    mgnMode String Yes Margin mode
    isolated cross
    mgnCcy String Conditional Margin currency
    Only applicable to cross MARGIN in Spot and futures mode

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
          "instId": "BTC-USDT",
          "mgnMode": "isolated",
          "mgnCcy": "",
          "maxLoan": "0.1",
          "ccy": "BTC",
          "side": "sell"
        },
        {
          "instId": "BTC-USDT",
          "mgnMode": "isolated",
          "mgnCcy": "",
          "maxLoan": "0.2",
          "ccy": "USDT",
          "side": "buy"
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    mgnMode String Margin mode
    mgnCcy String Margin currency
    maxLoan String Max loan
    ccy String Currency
    side String Order side
    buy 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
    MARGIN
    SWAP
    FUTURES
    OPTION
    instId String No Instrument ID, e.g. BTC-USDT
    Applicable to SPOT/MARGIN
    uly String No Underlying, e.g. BTC-USD
    Applicable to FUTURES/SWAP/OPTION
    instFamily String No Instrument family, e.g. BTC-USD
    Applicable to FUTURES/SWAP/OPTION
    ruleType String Yes Trading rule types
    normal: normal trading
    pre_market: pre-market trading
    ruleType can not be passed through together with instId/instFamily/uly

    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": "",
        "ruleType": "normal",
        "ts": "1608623351857",
        "fiat": []
      }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    level String Fee rate Level
    taker String For SPOT/MARGIN, it is taker fee rate of the USDT trading pairs.
    For FUTURES/SWAP/OPTION, it is the fee rate of crypto-margined contracts
    maker String For SPOT/MARGIN, it is maker fee rate of the USDT trading pairs.
    For FUTURES/SWAP/OPTION, it is the fee rate of crypto-margined contracts
    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/MARGIN, it is taker fee rate of the USDⓈ&Crypto trading pairs.
    For FUTURES/SWAP, it is the fee rate of USDC-margined contracts
    makerUSDC String For SPOT/MARGIN, it is maker fee rate of the USDⓈ&Crypto trading pairs.
    For FUTURES/SWAP, it is the fee rate of USDC-margined contracts
    ruleType String Trading rule types
    normal: normal trading
    pre_market: pre-market trading
    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

    Get interest accrued data

    Get interest accrued data. Only data within the last one year can be obtained.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/interest-accrued

    Request Example

    GET /api/v5/account/interest-accrued
    
    
    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 interest accrued data
    result = accountAPI.get_interest_accrued()
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    type String No Loan type
    1: VIP loans
    2: Market loans
    Default is Market loans
    ccy String No Loan currency, e.g. BTC
    Only applicable to Market loans
    Only applicable toMARGIN
    instId String No Instrument ID, e.g. BTC-USDT
    Only applicable to Market loans
    mgnMode String No Margin mode
    cross
    isolated
    Only applicable to Market loans
    after String No Pagination of data to return records earlier than the requested timestamp, Unix timestamp format in milliseconds, e.g. 1597026383085
    before String No Pagination of data to return records newer than the requested, 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": [
            {
                "ccy": "USDT",
                "instId": "",
                "interest": "0.0003960833333334",
                "interestRate": "0.0000040833333333",
                "liab": "97",
                "mgnMode": "",
                "ts": "1637312400000",
                "type": "1"
            },
            {
                "ccy": "USDT",
                "instId": "",
                "interest": "0.0004083333333334",
                "interestRate": "0.0000040833333333",
                "liab": "100",
                "mgnMode": "",
                "ts": "1637049600000",
                "type": "1"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    type String Loan type
    1: VIP loans
    2: Market loans
    ccy String Loan currency, e.g. BTC
    instId String Instrument ID, e.g. BTC-USDT
    Only applicable to Market loans
    mgnMode String Margin mode
    cross
    isolated
    interest String Interest
    interestRate String Interest rate (in hour)
    liab String Liability
    ts String Timestamp for interest accured, Unix timestamp format in milliseconds, e.g. 1597026383085

    Get interest rate

    Get the user's current leveraged currency borrowing market interest rate

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Requests

    GET /api/v5/account/interest-rate

    Request Example

    GET /api/v5/account/interest-rate
    
    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 the user's current leveraged currency borrowing interest rate
    result = accountAPI.get_interest_rate()
    print(result)
    

    Request Parameters

    Parameters Types Required Description
    ccy String No Currency, e.g. BTC
    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "ccy":"BTC",
                "interestRate":"0.0001"
            },
            {
                "ccy":"LTC",
                "interestRate":"0.0003"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    interestRate String interest rate(the current hour)
    ccy String currency

    Set greeks (PA/BS)

    Set the display type of Greeks.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/set-greeks

    Request Example

    POST /api/v5/account/set-greeks 
    body
    {
        "greeksType":"PA"
    }
    
    
    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)
    
    # Set greeks (PA/BS)
    result = accountAPI.set_greeks(greeksType="PA")
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    greeksType String Yes Display type of Greeks.
    PA: Greeks in coins
    BS: Black-Scholes Greeks in dollars

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "greeksType": "PA"
        }]
    }
    

    Response Parameters

    Parameter Type Description
    greeksType String Display type of Greeks.

    Isolated margin trading settings

    You can set the currency margin and futures/perpetual Isolated margin trading mode

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/set-isolated-mode

    Request Example

    POST /api/v5/account/set-isolated-mode
    body
    {
        "isoMode":"automatic",
        "type":"MARGIN"
    }
    
    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)
    
    # Isolated margin trading settings
    result = accountAPI.set_isolated_mode(
        isoMode="automatic",
        type="MARGIN"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    isoMode String Yes Isolated margin trading settings
    automatic: Auto transfers
    type String Yes Instrument type
    MARGIN
    CONTRACTS

    Response Example

    {
        "code": "0",
        "data": [
            {
                "isoMode": "automatic"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    isoMode String Isolated margin trading settings
    automatic: Auto transfers

    Get maximum withdrawals

    Retrieve the maximum transferable amount from trading account to funding account. If no currency is specified, the transferable amount of all owned currencies will be returned.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/max-withdrawal

    Request Example

    GET /api/v5/account/max-withdrawal
    
    
    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 withdrawals
    result = accountAPI.get_max_withdrawal()
    print(result)
    

    Request Parameters

    Parameter Type 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": [{
                "ccy": "BTC",
                "maxWd": "124",
                "maxWdEx": "125",
                "spotOffsetMaxWd": "",
                "spotOffsetMaxWdEx": ""
            },
            {
                "ccy": "ETH",
                "maxWd": "10",
                "maxWdEx": "12",
                "spotOffsetMaxWd": "",
                "spotOffsetMaxWdEx": ""
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Currency
    maxWd String Max withdrawal (excluding borrowed assets under Multi-currency margin/Portfolio margin)
    maxWdEx String Max withdrawal (including borrowed assets under Multi-currency margin/Portfolio margin)
    spotOffsetMaxWd String Max withdrawal under Spot-Derivatives risk offset mode (excluding borrowed assets under Portfolio margin)
    Applicable to Portfolio margin
    spotOffsetMaxWdEx String Max withdrawal under Spot-Derivatives risk offset mode (including borrowed assets under Portfolio margin)
    Applicable to Portfolio margin

    Get account risk state

    Only applicable to Portfolio margin account

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Requests

    GET /api/v5/account/risk-state

    Request Example

    GET /api/v5/account/risk-state
    
    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 risk state
    result = accountAPI.get_account_position_risk()
    print(result)
    

    Response Example

    {
        "code": "0",
        "data": [
            {
                "atRisk": false,
                "atRiskIdx": [],
                "atRiskMgn": [],
                "ts": "1635745078794"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameters Types Description
    atRisk String Account risk status in auto-borrow mode
    true: the account is currently in a specific risk state
    false: the account is currently not in a specific risk state
    atRiskIdx Array derivatives risk unit list
    atRiskMgn Array margin risk unit list
    ts String Unix timestamp format in milliseconds, e.g.1597026383085

    Manual borrow and repay in Quick Margin Mode

    Please note that this endpoint will be deprecated soon.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/quick-margin-borrow-repay

    Request Example

    POST /api/v5/account/quick-margin-borrow-repay 
    body
    {
        "instId":"BTC-USDT",
        "ccy":"USDT",
        "side":"borrow",
        "amt":"100"
    }
    
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID, e.g. BTC-USDT
    ccy String Yes Loan currency, e.g. BTC
    side String Yes borrow repay
    amt String Yes borrow/repay amount

    Response Example

    {
        "code": "0",
        "data": [
            {
                "amt": "100",
                "instId":"BTC-USDT",
                "ccy": "USDT",
                "side": "borrow"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID, e.g. BTC-USDT
    ccy String Loan currency, e.g. BTC
    side String borrow repay
    amt String borrow/repay amount

    Get borrow and repay history in Quick Margin Mode

    Get record in the past 3 months.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/quick-margin-borrow-repay-history

    Request Example

    GET /api/v5/account/quick-margin-borrow-repay-history
    
    

    Request Parameters

    Parameter Type Required Description
    instId String No Instrument ID, e.g. BTC-USDT
    ccy String No Loan currency, e.g. BTC
    side String No borrow repay
    after String No Pagination of data to return records earlier than the requested refId
    before String No Pagination of data to return records newer than the requested refId
    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": [
            {
                "instId": "BTC-USDT",
                "ccy": "USDT",
                "side": "borrow",
                "accBorrowed": "0.01",
                "amt": "0.005",
                "refId": "1637310691470124",
                "ts": "1637310691470"
            },
            {
                "instId": "BTC-USDT",
                "ccy": "USDT",
                "side": "borrow",
                "accBorrowed": "0.01",
                "amt": "0.005",
                "refId": "1637310691470123",
                "ts": "1637310691400"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID, e.g. BTC-USDT
    ccy String Loan currency, e.g. BTC
    side String borrow repay
    accBorrowed String Accumulate borrow amount
    amt String borrow/repay amount
    refId String The ID of borrowing or repayment
    ts String Timestamp for Borrow/Repay

    VIP loans borrow and repay

    Maximum number of borrowing orders for a single currency is 20

    Rate Limit: 6 requests per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/borrow-repay

    Request Example

    POST /api/v5/account/borrow-repay 
    body
    {
        "ccy":"USDT",
        "side":"borrow",
        "amt":"100"
    }
    
    
    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)
    
    # VIP loans borrow and repay
    result = accountAPI.borrow_repay(
        ccy="USDT",
        side="borrow",
        amt="100"
    )
    print(result)
    
    

    Request Parameters

    Parameter Type Required Description
    ccy String Yes Loan currency, e.g. BTC
    side String Yes borrow repay
    amt String Yes borrow/repay amount
    ordId String Conditional Order ID of borrowing, it is necessary while repaying

    Response Example

    {
        "code": "0",
        "data": [
            {
                "amt": "70809.316200",
                "ccy": "USDT",
                "ordId": "544199684697214976",
                "side": "borrow",
                "state": "1"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Loan currency, e.g. BTC
    side String borrow repay
    amt String Already borrow/repay amount
    ordId String Order ID of borrowing
    state String State
    1:Borrowing
    2:Borrowed
    3:Repaying
    4:Repaid
    5:Borrow failed

    Get borrow and repay history for VIP loans

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/borrow-repay-history

    Request Example

    GET /api/v5/account/borrow-repay-history
    
    
    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 borrow and repay history for VIP loans
    result = accountAPI.get_borrow_repay_history()
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    ccy String No Loan currency, e.g. BTC
    after String No Pagination of data to return records earlier than the requested timestamp, Unix timestamp format in milliseconds, e.g. 1597026383085
    before String No Pagination of data to return records newer than the requested, 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": [
            {
                "ccy": "USDT",
                "tradedLoan": "102",
                "ts": "1637310691470",
                "type": "2",
                "usedLoan": "97"
            },
            {
                "ccy": "USDT",
                "tradedLoan": "102",
                "ts": "1637050435058",
                "type": "2",
                "usedLoan": "199"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Loan currency, e.g. BTC
    type String Type
    1: borrow
    2: repay
    3: Loan reversed, lack of balance for interest
    tradedLoan String Borrow/Repay amount
    usedLoan String Borrowed amount for current account
    ts String Timestamp for Borrow/Repay

    Get VIP interest accrued data

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/vip-interest-accrued

    Request Example

    GET /api/v5/account/vip-interest-accrued
    
    

    Request Parameters

    Parameter Type Required Description
    ccy String No Loan currency, e.g. BTC
    Only applicable toMARGIN
    ordId String No Order ID of borrowing
    after String No Pagination of data to return records earlier than the requested timestamp, Unix timestamp format in milliseconds, e.g. 1597026383085
    before String No Pagination of data to return records newer than the requested, 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": [
            {
                "ccy": "USDT",
                "interest": "0.0003960833333334",
                "interestRate": "0.0000040833333333",
                "liab": "97",
                "ordId": "16373124000001235",
                "ts": "1637312400000"
            },
            {
                "ccy": "USDT",
                "interest": "0.0004083333333334",
                "interestRate": "0.0000040833333333",
                "liab": "100",
                "ordId": "16370496000001234",
                "ts": "1637049600000"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ordId String Order ID of borrowing
    ccy String Loan currency, e.g. BTC
    interest String Interest
    interestRate String Interest rate (in hours)
    liab String Liability
    ts String Timestamp for interest accrued, Unix timestamp format in milliseconds, e.g. 1597026383085

    Get VIP interest deducted data

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/vip-interest-deducted

    Request Example

    GET /api/v5/account/vip-interest-deducted
    
    

    Request Parameters

    Parameter Type Required Description
    ccy String No Loan currency, e.g. BTC
    Only applicable toMARGIN
    ordId String No Order ID of borrowing
    after String No Pagination of data to return records earlier than the requested timestamp, Unix timestamp format in milliseconds, e.g. 1597026383085
    before String No Pagination of data to return records newer than the requested, 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": [
            {
                "ccy": "USDT",
                "interest": "0.0003960833333334",
                "interestRate": "0.0000040833333333",
                "liab": "97",
                "ordId": "16373124000001235",
                "ts": "1637312400000"
            },
            {
                "ccy": "USDT",
                "interest": "0.0004083333333334",
                "interestRate": "0.0000040833333333",
                "liab": "100",
                "ordId": "16370496000001234",
                "ts": "1637049600000"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ordId String Order ID of borrowing
    ccy String Loan currency, e.g. BTC
    interest String Interest
    interestRate String Interest rate (in hour)
    liab String Liability
    ts String Timestamp for interest accured, Unix timestamp format in milliseconds, e.g. 1597026383085

    Get VIP loan order list

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/vip-loan-order-list

    Request Example

    GET /api/v5/account/vip-loan-order-list
    
    

    Request Parameters

    Parameter Type Required Description
    ordId String No Order ID of borrowing
    state String No State 1:Borrowing 2:Borrowed 3:Repaying 4:Repaid 5:Borrow failed
    ccy String No Loan currency, e.g. BTC
    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": [
             {
                "borrowAmt": "1.5000000000000000",
                "ccy": "USDT",
                "curRate": "0.0000169999999992",
                "dueAmt": "0.0000000000000000",
                "nextRefreshTime": "1688172235000",
                "ordId": "584301085292781568",
                "origRate": "0.0000169999999992",
                "repayAmt": "1.5000000000000000",
                "state": "4",
                "ts": "1685580235000"
            }
       ]
    }
    

    Response Parameters

    Parameter Type Description
    ts String Operation time, unix timestamp format in milliseconds, e.g. 1597026383085
    nextRefreshTime String Next interest rate refresh time, unix timestamp format in milliseconds, e.g. 1597026383085
    ccy String Loan currency, e.g. BTC
    ordId String Order ID
    state String State
    1:Borrowing 2:Borrowed 3:Repaying 4:Repaid 5:Borrow failed
    origRate String Original rate of order
    curRate String Current annual rate of ccy
    dueAmt String Amount due
    borrowAmt String Amount borrowed
    repayAmt String Amount repaid

    Get VIP loan order detail

    Rate limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/vip-loan-order-detail

    Request Example

    GET /api/v5/account/vip-loan-order-detail?ordId=697717437869338879
    
    

    Request Parameters

    Parameter Type Required Description
    ordId String yes Order ID of loan
    ccy String No Loan currency, e.g. BTC
    after String No Pagination of data to return records earlier than the requested timestamp, Unix timestamp format in milliseconds, e.g. 1597026383085
    before String No Pagination of data to return records newer than the requested 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": [
            {
                "amt": "1.5000000000000000",
                "ccy": "USDT",
                "failReason": "",
                "rate": "0.0000000000000000",
                "ts": "1685580264572",
                "type": "2"
            }
       ]
    }
    

    Response Parameters

    Parameter Type Description
    ts String Operation time
    ccy String Loan currency, e.g. BTC
    type String Operation Type:
    1:Borrow
    2:Repayment
    3:System Repayment
    4:Interest Rate Refresh
    rate String Current order rate (daily interest rate)
    amt String Borrow/repay amount
    failReason String Fail reason

    Get borrow interest and limit

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/interest-limits

    Request Example

    GET /api/v5/account/interest-limits?type=1&ccy=BTC
    
    
    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 borrow interest and limit
    result = accountAPI.get_interest_limits(
        type="1",
        ccy="BTC"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    type String No Loan type
    1: VIP loans
    2: Market loans
    Default is Market loans
    ccy String No Loan currency, e.g. BTC

    Response Example

    {
        "code": "0",
        "data": [
            {
                "debt": "97.06402000000000000000000000000000",
                "interest": "",
                "nextDiscountTime": "1637312400000",
                "nextInterestTime": "1637312400000",
                "loanAlloc": "",
                "records": [
                    {
                        "availLoan": "0.0000000000000000",
                        "ccy": "BTC",
                        "interest": "",
                        "loanQuota": "600.0000000000000000",
                        "posLoan": "0",
                        "rate": "0.00199200",
                        "surplusLmt": "600.0000000000000000",
                        "surplusLmtDetails":{
                            "allAcctRemainingQuota": "600.00",
                            "curAcctRemainingQuota": "600.00",
                            "platRemainingQuota": "600.00"
                        },
                        "usedLmt": "0",
                        "usedLoan": "0.0000000000000000"
                    }
                ]
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    debt String Current debt in USDT
    interest String Current interest in USDT, the unit is USDT
    Only applicable to Market loans
    nextDiscountTime String Next deduct time, Unix timestamp format in milliseconds, e.g. 1597026383085
    nextInterestTime String Next accrual time, Unix timestamp format in milliseconds, e.g. 1597026383085
    loanAlloc String VIP Loan allocation for the current trading account
    1. The unit is percent(%). Range is [0, 100]. Precision is 0.01%
    2. If master account did not assign anything, then "0"
    3. "" if shared between master and sub-account
    records Array Details for currencies
    > ccy String Loan currency, e.g. BTC
    > rate String Current daily rate
    > loanQuota String Borrow limit of master account
    If loan allocation has been assigned, then it is the borrow limit of the current trading account
    > surplusLmt String Available amount across all sub-accounts
    If loan allocation has been assigned, then it is the available amount to borrow by the current trading account
    > surplusLmtDetails Object The details of available amount across all sub-accounts
    The value of surplusLmt is the minimum value within this array. It can help you judge the reason that surplusLmt is not enough.
    Only applicable to VIP loans
    >> allAcctRemainingQuota String Total remaining quota for master account and sub-accounts
    >> curAcctRemainingQuota String The remaining quota for the current account.
    Only applicable to the case in which the sub-account is assigned the loan allocation
    >> platRemainingQuota String Remaining quota for the platform.
    The format like "600" will be returned when it is more than curAcctRemainingQuota or allAcctRemainingQuota
    > usedLmt String Borrowed amount across all sub-accounts
    If loan allocation has been assigned, then it is the borrowed amount by the current trading account
    > interest String Interest to be deducted
    Only applicable to Market loans
    > posLoan String Frozen amount for current account (Within the locked quota)
    Only applicable to VIP loans
    > availLoan String Available amount for current account (Within the locked quota)
    Only applicable to VIP loans
    > usedLoan String Borrowed amount for current account
    Only applicable to VIP loans
    > avgRate String Average (hour) interest of already borrowed coin
    only applicable to VIP loans

    Get fixed loan borrow limit

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/fixed-loan/borrowing-limit

    Request Example

    GET /api/v5/account/fixed-loan/borrowing-limit
    
    
    
    

    Request Parameters

    None

    Response Example

    {
        "code": "0",
        "data": [
            {
                "availRepay": "1110.9884",
                "borrowed": "60895.1139",
                "details": [
                    {
                        "availBorrow": "0.0566",
                        "borrowed": "0",
                        "ccy": "BTC",
                        "minBorrow": "0.1433",
                        "used": "0"
                    },
                    {
                        "availBorrow": "0",
                        "borrowed": "0",
                        "ccy": "LTC",
                        "minBorrow": "114.582",
                        "used": "0"
                    },
                    {
                        "availBorrow": "10",
                        "borrowed": "0",
                        "ccy": "ETH",
                        "minBorrow": "2.6666",
                        "used": "0"
                    },
                    {
                        "availBorrow": "248727.5",
                        "borrowed": "61115",
                        "ccy": "USDT",
                        "minBorrow": "9999.5679",
                        "used": "60000"
                    }
                ],
                "totalAvailBorrow": "289336.6564",
                "totalBorrowLmt": "22843016.1921",
                "ts": "1716368077071",
                "used": "59784.1256"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    totalBorrowLmt String (Master account and sub-accounts) Total borrow limit, unit in USD
    totalAvailBorrow String (Master account and sub-accounts) Total available amount to borrow, unit in USD
    borrowed String (Current account) Borrowed amount, unit in USD
    used String (Current account) Used amount, unit in USD
    availRepay String (Current account) Available amount to repay, unit in USD
    details Array of object Borrow limit info in details
    > ccy String Borrowing currency, e.g. BTC
    > used String Used amount of current currency
    > borrowed String Borrowed amount of current currency
    > availBorrow String Available amount to borrow of current currency
    > minBorrow String Minimum borrow amount
    ts String Data return time, Unix timestamp format in milliseconds, e.g. 1597026383085

    Get fixed loan borrow quote

    Rate Limit: 2 requests per second

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/fixed-loan/borrowing-quote

    Request Example

    # Quote for new order
    GET /api/v5/account/fixed-loan/borrowing-quote?type=normal&ccy=BTC&maxRate=0.1&amt=0.1&term=30D
    
    # Quote for renew order
    GET /api/v5/account/fixed-loan/borrowing-quote?type=reborrow&ordId=2405162053378222
    
    
    

    Request Parameters

    Parameters Types Required Description
    type String Yes Type
    normal: new order
    reborrow: renew existing order
    ccy String Optional Borrowing currency, e.g. BTC
    if type=normal, the parameter is required.
    amt String Optional Borrowing amount
    if type=normal, the parameter is required.
    maxRate String Optional Maximum acceptable borrow rate, in decimal. e.g. 0.01 represents 1%
    if type=normal, the parameter is required.
    term String Optional Fixed term for borrowing order
    30D:30 Days
    if type=normal, the parameter is required.
    ordId String Optional Order ID
    if type=reborrow, the parameter is required.

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [
            {
                "ccy": "BTC",
                "term":"30D",
                "estAvailBorrow":"0.1",
                "estRate": "0.01",
                "estInterest": "25",
                "penaltyInterest": "",
                "ts": "1629966436396"
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Borrowing currency, e.g. BTC
    term String Fixed term for borrowing order
    30D:30 Days
    estAvailBorrow String Estimated available borrowing amount
    estRate String Estimated borrowing rate, e.g. "0.01"
    estInterest String Estimated borrowing interest
    penaltyInterest String Penalty interest for reborrowing
    Applicate to type = reborrow, else return ""
    ts String Data return time,Unix timestamp format in milliseconds, e.g. 1597026383085

    Place fixed loan borrowing order

    For new borrowing orders, they belong to the IOC (immediately close and cancel the remaining) type. For renewal orders, they belong to the FOK (Fill-or-kill) type.
    Order book may refer to Get lending volume (public).

    Rate Limit: 2 requests per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/fixed-loan/borrowing-order

    Request Example

    POST /api/v5/account/fixed-loan/borrowing-order
    body
    {
        "ccy": "BTC",
        "amt": "0.1",
        "maxRate": "0.01",
        "term": "30D",
        "reborrow": true,
        "reborrowRate": "0.01"
    }
    
    
    

    Request Parameters

    Parameters Types Required Description
    ccy String Yes Borrowing currency, e.g. BTC
    amt String Yes Borrowing amount
    maxRate String Yes Maximum acceptable borrow rate, in decimal. e.g. 0.01 represents 1%.
    term String Yes Fixed term for borrowing order
    30D:30 Days
    reborrow Boolean No Whether or not auto-renew when the term is due
    true: auto-renew
    false: not auto-renew
    Default is false.
    reborrowRate String No Auto-renew borrowing rate, in decimal. e.g. 0.01 represents 1%.
    If reborrow is true, the parameter is required.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "ordId":"2405162053378222"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ordId String Borrowing order ID

    Amend fixed loan borrowing order

    Rate Limit: 2 requests per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/fixed-loan/amend-borrowing-order

    Request Example

    POST /api/v5/account/fixed-loan/amend-borrowing-order
    body
    {
        "ordId": "2405162053378222",
        "reborrow": true,
        "renewMaxRate": "0.01"
    }
    
    
    

    Request Parameters

    Parameters Types Required Description
    ordId String Yes Borrowing order ID, e.g. BTC
    reborrow Boolean No Whether or not reborrowing when the term is due.
    Default is false.
    renewMaxRate String No Maximum acceptable auto-renew borrow rate for borrowing order, in decimal. e.g. 0.01 represents 1%.
    If reborrow is true, the parameter is required.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "ordId":"2405162053378222"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ordId String Borrowing order ID

    Manual renew fixed loan borrowing order

    Rate Limit: 2 requests per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/fixed-loan/manual-reborrow

    Request Example

    POST /api/v5/account/fixed-loan/manual-reborrow
    body
    {
        "ordId": "2405162053378222",
        "maxRate": "0.01"
    }
    
    
    

    Request Parameters

    Parameters Types Required Description
    ordId String Yes Borrowing order ID
    maxRate String Yes Maximum acceptable borrowing rate, in decimal. e.g. 0.01 represents 1%.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "ordId":"2405162053378222"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ordId String Borrowing order ID

    Repay fixed loan borrowing order

    Rate Limit: 2 requests per second

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/fixed-loan/repay-borrowing-order

    Request Example

    POST /api/v5/account/fixed-loan/repay-borrowing-order
    body
    {
        "ordId": "2405162053378222"
    }
    
    
    

    Request Parameters

    Parameters Types Required Description
    ordId String Yes Borrowing order ID

    Response Example

    {
        "code": "0",
        "data": [
            {
                "ordId":"2405162053378222"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ordId String Borrowing order ID

    Get fixed loan borrow order list

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/fixed-loan/borrowing-orders-list

    Request Example

    GET /api/v5/account/fixed-loan/borrowing-orders-list
    
    
    
    

    Request Parameters

    Parameters Types Required Description
    ordId String No Borrowing order ID
    ccy String No Borrowing currency, e.g. BTC
    state String No State
    1: Borrowing
    2: Borrowed
    3: Settled (Repaid)
    4: Borrow failed
    5: Overdue
    6: Settling
    7: Reborrowing
    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",
        "data": [
            {
                "accruedInterest": "0.0065753424657534",
                "actualBorrowAmt": "0",
                "cTime": "1720701491000",
                "ccy": "ETH",
                "curRate": "0",
                "deadlinePenaltyInterest": "1723271891000",
                "earlyRepayPenaltyInterest": "",
                "expiryTime": "1723293491000",
                "failedReason": "1",
                "forceRepayTime": "1725885491000",
                "ordId": "2407112038109533",
                "overduePenaltyInterest": "",
                "potentialPenaltyInterest": "",
                "reborrow": false,
                "reborrowRate": "",
                "reqBorrowAmt": "8",
                "settleReason": "",
                "state": "4",
                "term": "30D",
                "uTime": "1720701490000"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    ccy String Borrowing currency, e.g. BTC
    ordId String Borrowing order ID
    term String Fixed term for borrowing order
    30D: 30 days
    state String State
    1: Borrowing
    2: Borrowed
    3: Settled (Repaid)
    4: Borrow failed
    5: Overdue
    6: Settling
    7: Reborrowing
    failedReason String Borrowing failed reason
    1: There are currently no matching orders
    2: Unable to pay prepaid interest
    -1: Other reason
    settleReason String Settle reason
    1: Order at maturity
    2: Extension in advance
    3: Early repayment
    curRate String Borrowing annual rate of current order
    accruedInterest String Accrued interest
    reqBorrowAmt String Requested borrowing mount
    actualBorrowAmt String Actual borrowed mount
    reborrow Boolean Whether or not auto-renew when the term is due
    true: auto-renew
    false: not auto-renew
    reborrowRate String Auto-renew borrowing rate, in decimal. e.g. 0.01 represents 1%
    expiryTime String Expiry time, Unix timestamp format in milliseconds, e.g. 1597026383085
    forceRepayTime String Force repayment time, unix timestamp format in milliseconds, e.g. 1597026383085
    deadlinePenaltyInterest String Deadline of penalty interest for early repayment, Unix timestamp format in milliseconds, e.g. 1597026383085
    potentialPenaltyInterest String Potential penalty Interest for early repayment
    overduePenaltyInterest String Overdue penalty interest
    earlyRepayPenaltyInterest String Early repay penalty interest
    cTime String Creation time for borrowing order, unix timestamp format in milliseconds, e.g. 1597026383085
    uTime String Update time for borrowing order, unix timestamp format in milliseconds, e.g. 1597026383085

    Position builder (new)

    Calculates portfolio margin information for virtual position/assets or current position of the user.
    You can add up to 200 virtual positions and 200 virtual assets in one request.

    Rate Limit: 2 requests per 2 seconds

    Rate limit rule: UserID

    Permissions: Read

    HTTP Request

    POST /api/v5/account/position-builder

    Request Example

    # Both real and virtual positions and assets are calculated 
    POST /api/v5/account/position-builder
    body
    {
        "inclRealPosAndEq": false,
        "simPos":[
             {
                "pos":"-10",
                "instId":"BTC-USDT-SWAP"
             },
             {
                "pos":"10",
                "instId":"LTC-USDT-SWAP"
             }
        ],
        "simAsset":[
            {
                "ccy": "USDT",
                "amt": "100"
            }
        ],
        "spotOffsetType":"1",
        "greeksType":"CASH"
    }
    
    
    # Only existing real positions are calculated
    POST /api/v5/account/position-builder
    body
    {
       "inclRealPosAndEq":true
    }
    
    
    # Only virtual positions are calculated
    POST /api/v5/account/position-builder
    body
    {
       "inclRealPosAndEq": false,
       "simPos":[
         {
              "pos":"10",
              "instId":"BTC-USDT-SWAP"
         },
         {
              "pos":"10",
              "instId":"LTC-USDT-SWAP"
         }
       ]
    }
    
    
    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)
    
    result = accountAPI.position_builder(
        inclRealPosAndEq=True,
        simPos=[
            {
                "pos": "10",
                "instId": "BTC-USDT-SWAP"
            },
            {
                "pos": "10",
                "instId": "LTC-USDT-SWAP"
            }
        ]
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    inclRealPosAndEq Boolean No Whether import existing positions and assets
    The default is true
    spotOffsetType String No Spot-derivatives risk offset mode
    1: Spot-derivatives (USDT)
    2: Spot-derivatives (crypto)
    3: Derivatives-only
    The default is 3
    simPos Array of object No List of simulated positions
    > instId String No Instrument ID, e.g. BTC-USDT-SWAP
    Applicable to SWAP/FUTURES/OPTION
    > pos String No Quantity of positions
    simAsset Array of object No List of simulated assets
    When inclRealPosAndEq is true, only real assets are considered and virtual assets are ignored
    > ccy String No Currency, e.g. BTC
    > amt String No Currency amount
    greeksType String No Greeks type
    BS: Black-Scholes Model Greeks
    PA: Crypto Greeks
    CASH: Empirical Greeks
    The default is BS

    Response Example

    {
        "code": "0",
        "data": [
            {
                "assets": [
                    {
                        "availEq": "2.92259509161",
                        "borrowImr": "0",
                        "borrowMmr": "0",
                        "ccy": "BTC",
                        "spotInUse": "0"
                    },
                    {
                        "availEq": "1",
                        "borrowImr": "0",
                        "borrowMmr": "0",
                        "ccy": "ETH",
                        "spotInUse": "0"
                    },
                    {
                        "availEq": "-76819.72721896428",
                        "borrowImr": "9612.484308105535",
                        "borrowMmr": "1920.4931804741072",
                        "ccy": "USDT",
                        "spotInUse": "0"
                    },
                    {
                        "availEq": "100.000001978",
                        "borrowImr": "0",
                        "borrowMmr": "0",
                        "ccy": "OKB",
                        "spotInUse": "0"
                    },
                    {
                        "availEq": "1.1618286584225905",
                        "borrowImr": "0",
                        "borrowMmr": "0",
                        "ccy": "USDC",
                        "spotInUse": "0"
                    }
                ],
                "borrowMmr": "1919.9362374517698",
                "derivMmr": "61.63384859899599",
                "eq": "50503.83298678435",
                "marginRatio": "24.513003004865656",
                "riskUnitData": [
                    {
                        "delta": "0.010000438961223",
                        "gamma": "0",
                        "imr": "79.93948582424999",
                        "indexUsd": "0.99971",
                        "mmr": "61.49191217249999",
                        "mr1": "61.49191217249999",
                        "mr1FinalResult": {
                            "pnl": "-61.49191217249999",
                            "spotShock": "-0.15",
                            "volShock": "up"
                        },
                        "mr1Scenarios": {
                            "volSame": {
                                "0": "0",
                                "-0.05": "-20.497304057499974",
                                "-0.1": "-40.99460811500002",
                                "0.1": "40.99460811500002",
                                "0.15": "61.49191217249999",
                                "0.05": "20.497304057499974",
                                "-0.15": "-61.49191217249999"
                            },
                            "volShockDown": {
                                "0": "0",
                                "-0.05": "-20.497304057499974",
                                "-0.1": "-40.99460811500002",
                                "0.1": "40.99460811500002",
                                "0.15": "61.49191217249999",
                                "0.05": "20.497304057499974",
                                "-0.15": "-61.49191217249999"
                            },
                            "volShockUp": {
                                "0": "0",
                                "-0.05": "-20.497304057499974",
                                "-0.1": "-40.99460811500002",
                                "0.1": "40.99460811500002",
                                "0.15": "61.49191217249999",
                                "0.05": "20.497304057499974",
                                "-0.15": "-61.49191217249999"
                            }
                        },
                        "mr2": "0",
                        "mr3": "0",
                        "mr4": "0",
                        "mr5": "0",
                        "mr6": "61.49191217249999",
                        "mr6FinalResult": {
                            "pnl": "-122.98382434499997",
                            "spotShock": "-0.3"
                        },
                        "mr7": "1.8448113495150003",
                        "portfolios": [
                            {
                                "amt": "10",
                                "delta": "0.010000438961223",
                                "gamma": "0",
                                "instId": "BTC-USDT-SWAP",
                                "instType": "SWAP",
                                "isRealPos": false,
                                "notionalUsd": "409.968",
                                "theta": "0",
                                "vega": "0"
                            }
                        ],
                        "riskUnit": "BTC-USDT",
                        "theta": "0",
                        "vega": "0"
                    },
                    {
                        "delta": "0.009998760367833",
                        "gamma": "0",
                        "imr": "0.1845173544448",
                        "indexUsd": "0.99971",
                        "mmr": "0.141936426496",
                        "mr1": "0.141936426496",
                        "mr1FinalResult": {
                            "pnl": "-0.141936426496",
                            "spotShock": "-0.2",
                            "volShock": "volatility_shock_up"
                        },
                        "mr1Scenarios": {
                            "volSame": {
                                "0": "0",
                                "-0.07": "-0.0496777492736",
                                "-0.2": "-0.141936426496",
                                "0.07": "0.0496777492736",
                                "0.2": "0.141936426496",
                                "0.14": "0.0993554985472",
                                "-0.14": "-0.0993554985472"
                            },
                            "volShockDown": {
                                "0": "0",
                                "-0.07": "-0.0496777492736",
                                "-0.2": "-0.141936426496",
                                "0.07": "0.0496777492736",
                                "0.2": "0.141936426496",
                                "0.14": "0.0993554985472",
                                "-0.14": "-0.0993554985472"
                            },
                            "volShockUp": {
                                "0": "0",
                                "-0.07": "-0.0496777492736",
                                "-0.2": "-0.141936426496",
                                "0.07": "0.0496777492736",
                                "0.2": "0.141936426496",
                                "0.14": "0.0993554985472",
                                "-0.14": "-0.0993554985472"
                            }
                        },
                        "mr2": "0",
                        "mr3": "0",
                        "mr4": "0",
                        "mr5": "0",
                        "mr6": "0.141936426496",
                        "mr6FinalResult": {
                            "pnl": "-0.283872852992",
                            "spotShock": "-0.4"
                        },
                        "mr7": "0.004967159106",
                        "portfolios": [
                            {
                                "amt": "10",
                                "delta": "0.009998760367833",
                                "gamma": "0",
                                "instId": "LTC-USDT-SWAP",
                                "instType": "SWAP",
                                "isRealPos": false,
                                "notionalUsd": "0.7098000000000001",
                                "theta": "0",
                                "vega": "0"
                            }
                        ],
                        "riskUnit": "LTC-USDT",
                        "theta": "0",
                        "vega": "0"
                    }
                ],
                "totalImr": "9689.820690834878",
                "totalMmr": "1981.5700860507657",
                "ts": "1705915813386"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameters Types Description
    eq String Adjusted equity (USD) for the account
    totalMmr String Total MMR (USD) for the account
    totalImr String Total IMR (USD) for the account
    borrowMmr String Borrow MMR (USD) for the account
    derivMmr String Derivatives MMR (USD) for the account
    marginRatio String Cross margin ratio for the account
    ts String Update time for the account, Unix timestamp format in milliseconds, e.g. 1597026383085
    assets Array of object Asset info
    > ccy String Currency, e.g. BTC
    > availEq String Currency equity
    > spotInUse String Spot in use
    > borrowMmr String Borrowing MMR (USD)
    > borrowImr String Borrowing IMR (USD)
    riskUnitData Array of object Risk unit info
    > riskUnit String Risk unit, e.g. BTC-USDT
    > indexUsd String Risk unit index price (USD)
    > mmr String Risk unit MMR (USD)
    > imr String Risk unit IMR (USD)
    > mr1 String Stress testing value of spot and volatility (all derivatives, and spot trading in spot-derivatives risk offset mode)
    > mr2 String Stress testing value of time value of money (TVM) (for options)
    > mr3 String Stress testing value of volatility span (for options)
    > mr4 String Stress testing value of basis (for all derivatives)
    > mr5 String Stress testing value of interest rate risk (for options)
    > mr6 String Stress testing value of extremely volatile markets (for all derivatives, and spot trading in spot-derivatives risk offset mode)
    > mr7 String Stress testing value of position reduction cost (for all derivatives)
    > mr1Scenarios Object MR1 scenario analysis
    >> volShockDown Object When the volatility shock down, the P&L of stress tests under different price volatility ratios, format in {change: value,...}
    change: price volatility ratio (in percentage), e.g. 0.01 representing 1%
    value: P&L under stress tests, measured in USD
    e.g. {"-0.15":"-2333.23", ...}
    >> volSame Object When the volatility keep the same, the P&L of stress tests under different price volatility ratios, format in {change: value,...}
    change: price volatility ratio (in percentage), e.g. 0.01 representing 1%
    value: P&L under stress tests, measured in USD
    e.g. {"-0.15":"-2333.23", ...}
    >> volShockUp Object When the volatility shock up, the P&L of stress tests under different price volatility ratios, format in {change: value,...}
    change: price volatility ratio (in percentage), e.g. 0.01 representing 1%
    value: P&L under stress tests, measured in USD
    e.g. {"-0.15":"-2333.23", ...}
    > mr1FinalResult Object MR1 worst-case scenario
    >> pnl String MR1 stress P&L (USD)
    >> spotShock String MR1 worst-case scenario spot shock (in percentage), e.g. 0.01 representing 1%
    >> volShock String MR1 worst-case scenario volatility shock
    down: volatility shock down
    unchange: volatility unchanged
    up: volatility shock up
    > mr6FinalResult String MR6 scenario analysis
    >> pnl String MR6 stress P&L (USD)
    >> spotShock String MR6 worst-case scenario spot shock (in percentage), e.g. 0.01 representing 1%
    > delta String (Risk unit) The rate of change in the contract’s price with respect to changes in the underlying asset’s price.
    When the price of the underlying changes by x, the option’s price changes by delta multiplied by x.
    > gamma String (Risk unit) The rate of change in the delta with respect to changes in the underlying price.
    When the price of the underlying changes by x%, the option’s delta changes by gamma multiplied by x%.
    > theta String (Risk unit) The change in contract price each day closer to expiry.
    > vega String (Risk unit) The change of the option price when underlying volatility increases by 1%.
    > portfolios Array of object Portfolios info
    >> instId String Instrument ID, e.g. BTC-USDT-SWAP
    >> instType String Instrument type
    SPOT
    SWAP
    FUTURES
    OPTION
    >> amt String When instType is SPOT, it represents spot in use.
    When instType is SWAP/FUTURES/OPTION, it represents position amount.
    >> notionalUsd String Notional in USD
    >> delta String When instType is SPOT, it represents asset amount.
    When instType is SWAP/FUTURES/OPTION, it represents the rate of change in the contract’s price with respect to changes in the underlying asset’s price (by Instrument ID).
    >> gamma String The rate of change in the delta with respect to changes in the underlying price (by Instrument ID).
    When instType is SPOT, it will returns "".
    >> theta String The change in contract price each day closer to expiry (by Instrument ID).
    When instType is SPOT, it will returns "".
    >> vega String The change of the option price when underlying volatility increases by 1% (by Instrument ID).
    When instType is SPOT, it will returns "".
    >> isRealPos Boolean Whether it is a real position
    If instType is SWAP/FUTURES/OPTION, it is a valid parameter, else it will returns false

    Set risk offset amount

    Set risk offset amount. This does not represent the actual spot risk offset amount. Only applicable to Portfolio Margin Mode.

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/set-riskOffset-amt

    Request Example

    # Set spot risk offset amount
    POST /api/v5/account/set-riskOffset-amt
    {
       "ccy": "BTC",
       "clSpotInUseAmt": "0.5"
    }
    
    

    Request Parameters

    Parameter Type Required Description
    ccy String Yes Currency
    clSpotInUseAmt String Yes Spot risk offset amount defined by users

    Response Example

    {
       "code": "0",
       "msg": "",
       "data": [
          {
             "ccy": "BTC",
             "clSpotInUseAmt": "0.5"
          }
       ]
    }
    

    Response Parameters

    Parameters Types Description
    ccy String Currency
    clSpotInUseAmt String Spot risk offset amount defined by users

    Get Greeks

    Retrieve a greeks list of all assets in the account.

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Requests

    GET /api/v5/account/greeks

    Request Example

    # Get the greeks of all assets in the account
    GET /api/v5/account/greeks
    
    # Get the greeks of BTC assets in the account
    GET /api/v5/account/greeks?ccy=BTC
    
    
    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 a greeks list of all assets in the account
    result = accountAPI.get_greeks()
    print(result)
    

    Request Parameters

    Parameters Types Required Description
    ccy String No Single currency, e.g. BTC.

    Response Example

    {
        "code":"0",
        "data":[
            {            
               "thetaBS": "",
               "thetaPA":"",
               "deltaBS":"",
               "deltaPA":"",
               "gammaBS":"",
               "gammaPA":"",
               "vegaBS":"",    
               "vegaPA":"",
               "ccy":"BTC",
               "ts":"1620282889345"
            }
        ],
        "msg":""
    }
    

    Response Parameters

    Parameters Types Description
    deltaBS String delta: Black-Scholes Greeks in dollars
    deltaPA String delta: Greeks in coins
    gammaBS String gamma: Black-Scholes Greeks in dollars, only applicable to OPTION
    gammaPA String gamma: Greeks in coins, only applicable to OPTION
    thetaBS String theta: Black-Scholes Greeks in dollars, only applicable to OPTION
    thetaPA String theta: Greeks in coins, only applicable to OPTION
    vegaBS String vega: Black-Scholes Greeks in dollars, only applicable to OPTION
    vegaPA String vega:Greeks in coins, only applicable to OPTION
    ccy String Currency
    ts String Time of getting Greeks, Unix timestamp format in milliseconds, e.g. 1597026383085

    Get PM position limitation

    Retrieve cross position limitation of SWAP/FUTURES/OPTION under Portfolio margin mode.

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/position-tiers

    Request Example

    # Query limitation of BTC-USDT
    GET /api/v5/account/position-tiers?instType=SWAP&uly=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 PM position limitation
    result = accountAPI.get_account_position_tiers(
        instType="SWAP",
        uly="BTC-USDT"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String Yes Instrument type
    SWAP
    FUTURES
    OPTION
    uly String Conditional Single underlying or multiple underlyings (no more than 3) separated with comma.
    Either uly or instFamily is required. If both are passed, instFamily will be used.
    instFamily String Conditional Single instrument family or instrument families (no more than 5) separated with comma.
    Either uly or instFamily is required. If both are passed, instFamily will be used.

    Response Example

    {
      "code": "0",
      "data": [
        {
          "instFamily": "BTC-USDT",
          "maxSz": "10000",
          "posType": "",
          "uly": "BTC-USDT"
        }
      ],
      "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    uly String Underlying
    Applicable to FUTURES/SWAP/OPTION
    instFamily String Instrument family
    Applicable to FUTURES/SWAP/OPTION
    maxSz String Max number of positions
    posType String Limitation of position type, only applicable to cross OPTION under portfolio margin mode
    1: Contracts of pending orders and open positions for all derivatives instruments. 2: Contracts of pending orders for all derivatives instruments. 3: Pending orders for all derivatives instruments. 4: Contracts of pending orders and open positions for all derivatives instruments on the same side. 5: Pending orders for one derivatives instrument. 6: Contracts of pending orders and open positions for one derivatives instrument. 7: Contracts of one pending order.

    Set risk offset type

    Configure the risk offset type in portfolio margin mode.

    Rate Limit: 10 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/set-riskOffset-type

    Request Example

    POST /api/v5/account/set-riskOffset-type
    body 
    {
        "type":"1"
    }
    
    

    Request Parameters

    Parameter Type Required Description
    type String Yes Risk offset type
    1: Spot-derivatives (USDT) risk offset
    2: Spot-derivatives (Crypto) risk offset
    3:Derivatives only mode
    4: Spot-derivatives (USDC) risk offset

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "type": "1"
        }]
    }
    

    Response Parameters

    Parameter Type Description
    type String Risk offset type
    1: Spot-derivatives (USDT) risk offset
    2: Spot-derivatives (Crypto) risk offset
    3:Derivatives only mode
    4: Spot-derivatives (USDC) risk offset

    Activate option

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/activate-option

    Request Parameters

    None

    Response Example

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

    Response Parameters

    Parameter Type Description
    ts String Activation time

    Set auto loan

    Only applicable to Multi-currency margin and Portfolio margin

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/set-auto-loan

    Request Example

    POST /api/v5/account/set-auto-loan
    body
    {
        "autoLoan":true,
    }
    

    Request Parameters

    Parameter Type Required Description
    autoLoan Boolean No Whether to automatically make loans
    Valid values are true, false
    The default is true

    Response Example

    {
        "code": "0",
        "msg": "",
        "data": [{
            "autoLoan": true
        }]
    }
    

    Response Parameters

    Parameter Type Description
    autoLoan Boolean Whether to automatically make loans

    Set account mode

    You need to set on the Web/App for the first set of every account mode.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/set-account-level

    Request Example

    POST /api/v5/account/set-account-level
    body
    {
        "acctLv":"1"
    }
    

    Request Parameters

    Parameter Type Required Description
    acctLv String Yes Account mode
    1: Spot mode
    2: Spot and futures mode
    3: Multi-currency margin code
    4: Portfolio margin mode

    Response Example

    {
        "code": "0",
        "data": [
            {
                "acctLv": "1"
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    acctLv String Account mode

    Reset MMP Status

    You can unfreeze by this endpoint once MMP is triggered.

    Only applicable to Option in Portfolio Margin mode, and MMP privilege is required.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/mmp-reset

    Request Example

    POST /api/v5/account/mmp-reset
    body
    {
        "instType":"OPTION",
        "instFamily":"BTC-USD"
    }
    

    Request Parameters

    Parameter Type Required Description
    instType String No Instrument type
    OPTION
    The default is `OPTION
    instFamily String Yes Instrument family

    Response Example

    {
        "code":"0",
        "msg":"",
        "data":[
            {
                "result":true
            }
        ]
    }
    

    Response Parameters

    Parameter Type Description
    result Boolean Result of the request true, false

    Set MMP

    This endpoint is used to set MMP configure

    Only applicable to Option in Portfolio Margin mode, and MMP privilege is required.

    Rate Limit: 2 requests per 10 seconds

    Rate limit rule: UserID

    HTTP Request

    POST /api/v5/account/mmp-config

    Request Example

    POST /api/v5/account/mmp-config
    body
    {
        "instFamily":"BTC-USD",
        "timeInterval":"5000",
        "frozenInterval":"2000",
        "qtyLimit": "100"
    }
    
    

    Request Parameters

    Parameter Type Required Description
    instFamily String Yes Instrument family
    timeInterval String Yes Time window (ms). MMP interval where monitoring is done
    "0" means disable MMP
    frozenInterval String Yes Frozen period (ms).
    "0" means the trade will remain frozen until you request "Reset MMP Status" to unfrozen
    qtyLimit String Yes Trade qty limit in number of contracts
    Must be > 0

    Response Example

    {
      "code": "0",
      "msg": "",
      "data": [
        {
            "frozenInterval":"2000",
            "instFamily":"BTC-USD",
            "qtyLimit": "100",
            "timeInterval":"5000"
        }
      ]
    }
    

    Response Parameters

    Parameter Type Description
    instFamily String Instrument family
    timeInterval String Time window (ms). MMP interval where monitoring is done
    frozenInterval String Frozen period (ms).
    qtyLimit String Trade qty limit in number of contracts

    GET MMP Config

    This endpoint is used to get MMP configure information

    Only applicable to Option in Portfolio Margin mode, and MMP privilege is required.

    Rate Limit: 5 requests per 2 seconds

    Rate limit rule: UserID

    HTTP Request

    GET /api/v5/account/mmp-config

    Request Example

    GET /api/v5/account/mmp-config?instFamily=BTC-USD
    
    

    Request Parameters

    Parameter Type Required Description
    instFamily String No Instrument Family

    Response Example

    {
      "code": "0",
      "data": [
        {
          "frozenInterval": "2000",
          "instFamily": "ETH-USD",
          "mmpFrozen": true,
          "mmpFrozenUntil": "2326882",
          "qtyLimit": "10",
          "timeInterval": "5000"
        }
      ],
      "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instFamily String Instrument Family
    mmpFrozen Boolean Whether MMP is currently triggered. true or false
    mmpFrozenUntil String If frozenInterval is configured and mmpFrozen = True, it is the time interval (in ms) when MMP is no longer triggered, otherwise "".
    timeInterval String Time window (ms). MMP interval where monitoring is done
    frozenInterval String Frozen period (ms). "0" means the trade will remain frozen until manually reset
    qtyLimit String Trade qty limit in number of contracts

    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.

    Concurrent connection to this channel will be restricted by the following rules: WebSocket connection count limit.

    URL Path

    /ws/v5/private (required login)

    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",
                "smtSyncEq": "0",
                "fixedBal": "0",
                "frozenBal": "158.57998",
                "imr": "",
                "interest": "0",
                "isoEq": "0",
                "isoLiab": "0",
                "isoUpl": "0",
                "liab": "0",
                "maxLoan": "0",
                "mgnRatio": "",
                "mmr": "",
                "notionalLever": "",
                "ordFrozen": "0",
                "rewardBal": "0",
                "spotInUseAmt": "",
                "clSpotInUseAmt": "",
                "maxSpotInUseAmt": "",          
                "spotIsoBal": "0",
                "stgyEq": "150",
                "twap": "0",
                "uTime": "1705564213903",
                "upl": "-7.475800000000003",
                "uplLiab": "0",
                "spotBal": "",
                "openAvgPx": "",
                "accAvgPx": "",
                "spotUpl": "",
                "spotUplRatio": "",
                "totalPnl": "",
                "totalPnlRatio": ""
            }],
            "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 Spot and futures mode/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 Spot and futures mode/Multi-currency margin/Portfolio margin
    >> availEq String Available equity of currency
    Applicable to Spot and futures mode/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
    >> frozenBal String Frozen balance of currency
    >> ordFrozen String Margin frozen for open orders
    Applicable to Spot mode/Spot and futures mode/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 Spot and futures mode/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
    >> rewardBal String Trial fund balance
    >> mgnRatio String Cross margin ratio of currency
    The index for measuring the risk of a certain asset in the account.
    Applicable to Spot and futures mode and when there is cross position
    >> imr String Cross initial margin requirement at the currency level
    Applicable to Spot and futures mode and when there is cross position
    >> mmr String Cross maintenance margin requirement at the currency level
    Applicable to Spot and futures mode and when there is cross position
    >> 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 Spot and futures mode
    >> coinUsdPrice String Price index usd of currency
    >> stgyEq String strategy equity
    >> isoUpl String Isolated unrealized profit and loss of currency
    Applicable to Spot and futures mode/Multi-currency margin/Portfolio margin
    >> spotInUseAmt String Spot in use amount
    Applicable to Portfolio margin
    >> clSpotInUseAmt String User-defined spot risk offset amount
    Applicable to Portfolio margin
    >> maxSpotInUseAmt String Max possible spot risk offset amount
    Applicable to Portfolio margin
    >> smtSyncEq String Smark sync equity
    The default is "0", only applicable to copy trader

    Positions channel

    Retrieve position information. Initial snapshot will be pushed according to subscription granularity. Data will be pushed when triggered by events such as placing/canceling order, and will also be pushed in regular interval according to subscription granularity.

    Concurrent connection to this channel will be restricted by the following rules: WebSocket connection count limit.

    URL Path

    /ws/v5/private (required login)

    Request Example : single

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "positions",
          "instType": "FUTURES",
          "instFamily": "BTC-USD",
          "instId": "BTC-USD-200329"
        }
      ]
    }
    

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "positions",
          "instType": "ANY",
          "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
    positions
    > instType String Yes Instrument type
    MARGIN
    SWAP
    FUTURES
    OPTION
    ANY
    > instFamily String No Instrument family
    Applicable to FUTURES/SWAP/OPTION
    > instId String No Instrument ID
    > extraParams String No Additional configuration
    >> updateInterval int No 0: only push due to positions events
    2000, 3000, 4000: push by events and regularly according to the time interval setting (ms)

    The data will be pushed both by events and around per 5 seconds regularly if this field is omitted or set to other values than the valid values above.

    The following format should be strictly followed when using this field.
    "extraParams": "
    {
    \"updateInterval\": \"0\"
    }
    "

    Successful Response Example : single

    {
      "event": "subscribe",
      "arg": {
        "channel": "positions",
        "instType": "FUTURES",
        "instFamily": "BTC-USD",
        "instId": "BTC-USD-200329"
      },
      "connId": "a4d3ae55"
    }
    

    Successful Response Example

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

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"positions\", \"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
    OPTION
    FUTURES
    SWAP
    MARGIN
    ANY
    > instFamily String No Instrument family
    > 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":"positions",
          "uid": "77982378738415879",
          "instType":"FUTURES"
      },
      "data":[
        {
          "adl":"1",
          "availPos":"1",
          "avgPx":"2566.31",
          "cTime":"1619507758793",
          "ccy":"ETH",
          "deltaBS":"",
          "deltaPA":"",
          "gammaBS":"",
          "gammaPA":"",
          "imr":"",
          "instId":"ETH-USD-210430",
          "instType":"FUTURES",
          "interest":"0",
          "idxPx":"2566.13",
          "last":"2566.22",
          "lever":"10",
          "liab":"",
          "liabCcy":"",
          "liqPx":"2352.8496681818233",
          "markPx":"2353.849",
          "margin":"0.0003896645377994",
          "mgnMode":"isolated",
          "mgnRatio":"11.731726509588816",
          "mmr":"0.0000311811092368",
          "notionalUsd":"2276.2546609009605",
          "optVal":"",
          "pTime":"1619507761462",
          "pendingCloseOrdLiabVal":"0.1",
          "pos":"1",
          "baseBorrowed": "",
          "baseInterest": "",
          "quoteBorrowed": "",
          "quoteInterest": "",
          "posCcy":"",
          "posId":"307173036051017730",
          "posSide":"long",
          "spotInUseAmt": "",
          "clSpotInUseAmt": "",
          "maxSpotInUseAmt": "",
          "bizRefId": "",
          "bizRefType": "",
          "spotInUseCcy": "",
          "thetaBS":"",
          "thetaPA":"",
          "tradeId":"109844",
          "uTime":"1619507761462",
          "upl":"-0.0000009932766034",
          "uplLastPx":"-0.0000009932766034",
          "uplRatio":"-0.0025490556801078",
          "uplRatioLastPx":"-0.0025490556801078",
          "vegaBS":"",
          "vegaPA":"",
          "realizedPnl":"0.001",
          "pnl":"0.0011",
          "fee":"-0.0001",
          "fundingFee":"0",
          "liqPenalty":"0",
          "closeOrderAlgo":[
              {
                  "algoId":"123",
                  "slTriggerPx":"123",
                  "slTriggerPxType":"mark",
                  "tpTriggerPx":"123",
                  "tpTriggerPxType":"mark",
                  "closeFraction":"0.6"
              },
              {
                  "algoId":"123",
                  "slTriggerPx":"123",
                  "slTriggerPxType":"mark",
                  "tpTriggerPx":"123",
                  "tpTriggerPxType":"mark",
                  "closeFraction":"0.4"
              }
          ]
        }
      ]
    }
    

    Push Data Example

    {
        "arg": {
            "channel": "positions",
            "uid": "77982378738415879",
            "instType": "ANY"
        },
        "data": [
        {
          "adl":"1",
          "availPos":"1",
          "avgPx":"2566.31",
          "cTime":"1619507758793",
          "ccy":"ETH",
          "deltaBS":"",
          "deltaPA":"",
          "gammaBS":"",
          "gammaPA":"",
          "imr":"",
          "instId":"ETH-USD-210430",
          "instType":"FUTURES",
          "interest":"0",
          "idxPx":"2566.13",
          "last":"2566.22",
          "usdPx":"",
          "bePx":"2353.949",
          "lever":"10",
          "liab":"",
          "liabCcy":"",
          "liqPx":"2352.8496681818233",
          "markPx":"2353.849",
          "margin":"0.0003896645377994",
          "mgnMode":"isolated",
          "mgnRatio":"11.731726509588816",
          "mmr":"0.0000311811092368",
          "notionalUsd":"2276.2546609009605",
          "optVal":"",
          "pTime":"1619507761462",
          "pendingCloseOrdLiabVal":"0.1",
          "pos":"1",
          "baseBorrowed": "",
          "baseInterest": "",
          "quoteBorrowed": "",
          "quoteInterest": "",
          "posCcy":"",
          "posId":"307173036051017730",
          "posSide":"long",
          "spotInUseAmt": "",
          "clSpotInUseAmt": "",
          "maxSpotInUseAmt": "",
          "spotInUseCcy": "",
          "bizRefId": "",
          "bizRefType": "",
          "thetaBS":"",
          "thetaPA":"",
          "tradeId":"109844",
          "uTime":"1619507761462",
          "upl":"-0.0000009932766034",
          "uplLastPx":"-0.0000009932766034",
          "uplRatio":"-0.0025490556801078",
          "uplRatioLastPx":"-0.0025490556801078",
          "vegaBS":"",
          "vegaPA":"",
          "realizedPnl":"0.001",
          "pnl":"0.0011",
          "fee":"-0.0001",
          "fundingFee":"0",
          "liqPenalty":"0",
          "closeOrderAlgo":[
              {
                  "algoId":"123",
                  "slTriggerPx":"123",
                  "slTriggerPxType":"mark",
                  "tpTriggerPx":"123",
                  "tpTriggerPxType":"mark",
                  "closeFraction":"0.6"
              },
              {
                  "algoId":"123",
                  "slTriggerPx":"123",
                  "slTriggerPxType":"mark",
                  "tpTriggerPx":"123",
                  "tpTriggerPxType":"mark",
                  "closeFraction":"0.4"
              }
          ]
        }, {
          "adl":"1",
          "availPos":"1",
          "avgPx":"2566.31",
          "cTime":"1619507758793",
          "ccy":"ETH",
          "deltaBS":"",
          "deltaPA":"",
          "gammaBS":"",
          "gammaPA":"",
          "imr":"",
          "instId":"ETH-USD-SWAP",
          "instType":"SWAP",
          "interest":"0",
          "idxPx":"2566.13",
          "last":"2566.22",
          "usdPx":"",
          "bePx":"2353.949",
          "lever":"10",
          "liab":"",
          "liabCcy":"",
          "liqPx":"2352.8496681818233",
          "markPx":"2353.849",
          "margin":"0.0003896645377994",
          "mgnMode":"isolated",
          "mgnRatio":"11.731726509588816",
          "mmr":"0.0000311811092368",
          "notionalUsd":"2276.2546609009605",
          "optVal":"",
          "pTime":"1619507761462",
          "pendingCloseOrdLiabVal":"0.1",
          "pos":"1",
          "baseBorrowed": "",
          "baseInterest": "",
          "quoteBorrowed": "",
          "quoteInterest": "",
          "posCcy":"",
          "posId":"307173036051017730",
          "posSide":"long",
          "spotInUseAmt": "",
          "clSpotInUseAmt": "",
          "maxSpotInUseAmt": "",
          "spotInUseCcy": "",
          "bizRefId": "",
          "bizRefType": "",
          "thetaBS":"",
          "thetaPA":"",
          "tradeId":"109844",
          "uTime":"1619507761462",
          "upl":"-0.0000009932766034",
          "uplLastPx":"-0.0000009932766034",
          "uplRatio":"-0.0025490556801078",
          "uplRatioLastPx":"-0.0025490556801078",
          "vegaBS":"",
          "vegaPA":"",
          "realizedPnl":"0.001",
          "pnl":"0.0011",
          "fee":"-0.0001",
          "fundingFee":"0",
          "liqPenalty":"0",
          "closeOrderAlgo":[
              {
                  "algoId":"123",
                  "slTriggerPx":"123",
                  "slTriggerPxType":"mark",
                  "tpTriggerPx":"123",
                  "tpTriggerPxType":"mark",
                  "closeFraction":"0.6"
              },
              {
                  "algoId":"123",
                  "slTriggerPx":"123",
                  "slTriggerPxType":"mark",
                  "tpTriggerPx":"123",
                  "tpTriggerPxType":"mark",
                  "closeFraction":"0.4"
              }
          ]
        }
      ]
    }
    

    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
    > mgnMode String Margin mode, cross isolated
    > posId String Position ID
    > posSide String Position side
    long
    short
    net (FUTURES/SWAP/OPTION: positive pos means long position and negative pos means short position. MARGIN: posCcy being base currency means long position, posCcy being quote currency means short position.)
    > pos String Quantity of positions. In the isolated margin mode, when doing manual transfers, a position with pos of 0 will be generated after the deposit is transferred
    > baseBal String Base currency balance, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
    > quoteBal String Quote currency balance, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
    > baseBorrowed String Base currency amount already borrowed, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
    > baseInterest String Base Interest, undeducted interest that has been incurred, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
    > quoteBorrowed String Quote currency amount already borrowed, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
    > quoteInterest String Quote Interest, undeducted interest that has been incurred, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
    > posCcy String Position currency, only applicable to MARGIN positions
    > availPos String Position that can be closed
    Only applicable to MARGIN, FUTURES/SWAP in the long-short mode and OPTION.
    For Margin position, the rest of sz will be SPOT trading after the liability is repaid while closing the position. Please get the available reduce-only amount from "Get maximum available tradable amount" if you want to reduce the amount of SPOT trading as much as possible.
    > avgPx String Average open price
    > upl String Unrealized profit and loss calculated by mark price.
    > uplRatio String Unrealized profit and loss ratio calculated by mark price.
    > uplLastPx String Unrealized profit and loss calculated by last price. Main usage is showing, actual value is upl.
    > uplRatioLastPx String Unrealized profit and loss ratio calculated by last price.
    > instId String Instrument ID, e.g. BTC-USDT-SWAP
    > lever String Leverage, not applicable to OPTION seller
    > liqPx String Estimated liquidation price
    Not applicable to OPTION
    > markPx String Latest Mark price
    > imr String Initial margin requirement, only applicable to cross
    > margin String Margin, can be added or reduced. Only applicable to isolated Margin.
    > mgnRatio String Margin ratio
    > mmr String Maintenance margin requirement
    > liab String Liabilities, only applicable to MARGIN.
    > liabCcy String Liabilities currency, only applicable to MARGIN.
    > interest String Interest accrued that has not been settled.
    > tradeId String Last trade ID
    > notionalUsd String Notional value of positions in USD
    > optVal String Option Value, only applicable to OPTION.
    > pendingCloseOrdLiabVal String The amount of close orders of isolated margin liability.
    > adl String Auto decrease line, signal area
    Divided into 5 levels, from 1 to 5, the smaller the number, the weaker the adl intensity.
    > bizRefId String External business id, e.g. experience coupon id
    > bizRefType String External business type
    > ccy String Currency used for margin
    > last String Latest traded price
    > idxPx String Latest underlying index price
    > usdPx String Latest USD price of the ccy on the market, only applicable to OPTION
    > bePx String Breakeven price
    > deltaBS String delta: Black-Scholes Greeks in dollars, only applicable to OPTION
    > deltaPA String delta: Greeks in coins, only applicable to OPTION
    > gammaBS String gamma: Black-Scholes Greeks in dollars, only applicable to OPTION
    > gammaPA String gamma: Greeks in coins, only applicable to OPTION
    > thetaBS String theta: Black-Scholes Greeks in dollars, only applicable to OPTION
    > thetaPA String theta: Greeks in coins, only applicable to OPTION
    > vegaBS String vega: Black-Scholes Greeks in dollars, only applicable to OPTION
    > vegaPA String vega: Greeks in coins, only applicable to OPTION
    > spotInUseAmt String Spot in use amount
    Applicable to Portfolio margin
    > spotInUseCcy String Spot in use unit, e.g. BTC
    Applicable to Portfolio margin
    > clSpotInUseAmt String User-defined spot risk offset amount
    Applicable to Portfolio margin
    > maxSpotInUseAmt String Max possible spot risk offset amount
    Applicable to Portfolio margin
    > realizedPnl String Realized profit and loss
    Only applicable to FUTURES/SWAP/OPTION
    realizedPnl=pnl+fee+fundingFee+liqPenalty
    > pnl String Accumulated pnl of closing order(s)
    > fee String Accumulated fee
    Negative number represents the user transaction fee charged by the platform.Positive number represents rebate.
    > fundingFee String Accumulated funding fee
    > liqPenalty String Accumulated liquidation penalty. It is negative when there is a value.
    > closeOrderAlgo Array Close position algo orders attached to the position. This array will have values only after you request "Place algo order" with closeFraction=1.
    >> algoId String Algo ID
    >> slTriggerPx String Stop-loss trigger price.
    >> slTriggerPxType String Stop-loss trigger price type.
    last: last price
    index: index price
    mark: mark price
    >> tpTriggerPx String Take-profit trigger price.
    >> tpTriggerPxType String Take-profit trigger price type.
    last: last price
    index: index price
    mark: mark price
    >> closeFraction String Fraction of position to be closed when the algo order is triggered.
    > cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085.
    > uTime String Latest time position was adjusted, Unix timestamp format in milliseconds, e.g. 1597026383085.
    > pTime String Push time of positions information, Unix timestamp format in milliseconds, e.g. 1597026383085.

    Balance and position channel

    Retrieve account balance and position information. Data will be pushed when triggered by events such as filled order, funding transfer.
    This channel applies to getting the account cash balance and the change of position asset ASAP.
    Concurrent connection to this channel will be restricted by the following rules: WebSocket connection count limit.

    URL Path

    /ws/v5/private (required login)

    Request Example

    {
        "op": "subscribe",
        "args": [{
            "channel": "balance_and_position"
        }]
    }
    

    Request Parameters

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

    Response Example

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

    Failure Response Example

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

    Response parameters

    Parameter Type Required Description
    event String Yes Operation
    subscribe
    unsubscribe
    error
    arg Object No List of subscribed channels
    > channel String Yes Channel name
    balance_and_position
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example

    {
        "arg": {
            "channel": "balance_and_position",
            "uid": "77982378738415879"
        },
        "data": [{
            "pTime": "1597026383085",
            "eventType": "snapshot",
            "balData": [{
                "ccy": "BTC",
                "cashBal": "1",
                "uTime": "1597026383085"
            }],
            "posData": [{
                "posId": "1111111111",
                "tradeId": "2",
                "instId": "BTC-USD-191018",
                "instType": "FUTURES",
                "mgnMode": "cross",
                "posSide": "long",
                "pos": "10",
                "ccy": "BTC",
                "posCcy": "",
                "avgPx": "3320",
                "uTIme": "1597026383085"
            }],
            "trades": [{
                "instId": "BTC-USD-191018",
                "tradeId": "2",
            }]
        }]
    }
    

    Push data parameters

    Parameter Type Description
    arg Object Channel to subscribe to
    > channel String Channel name
    > uid String User Identifier
    data Array Subscribed data
    > pTime String Push time of both balance and position information, millisecond format of Unix timestamp, e.g. 1597026383085
    > eventType String Event Type
    snapshot,delivered,exercised,transferred,filled,liquidation,claw_back,adl,funding_fee,adjust_margin,set_leverage,interest_deduction
    > balData String Balance data
    >> ccy String Currency
    >> cashBal String Cash Balance
    >> uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    > posData String Position data
    >> posId String Position ID
    >> tradeId String Last trade ID
    >> instId String Instrument ID, e.g BTC-USD-180213
    >> instType String Instrument type
    >> mgnMode String Margin mode
    isolated, cross
    >> avgPx String Average open price
    >> ccy String Currency used for margin
    >> posSide String Position side
    long, short, net
    >> pos String Quantity of positions. In the isolated margin mode, when doing manual transfers, a position with pos of 0 will be generated after the deposit is transferred
    >> baseBal String Base currency balance, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
    >> quoteBal String Quote currency balance, only applicable to MARGIN(Quick Margin Mode)(Deprecated)
    >> posCcy String Position currency, only applicable to MARGIN positions.
    >> uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    > trades Array Details of trade
    >> instId String Instrument ID, e.g. BTC-USDT
    >> tradeId String Trade ID

    Position risk warning

    This push channel is only used as a risk warning, and is not recommended as a risk judgment for strategic trading
    In the case that the market is volatile, there may be the possibility that the position has been liquidated at the same time that this message is pushed.
    The warning is sent when a position is at risk of liquidation for isolated margin positions. The warning is sent when all the positions are at risk of liquidation for cross-margin positions.
    Concurrent connection to this channel will be restricted by the following rules: WebSocket connection count limit.

    URL Path

    /ws/v5/private (required login)

    Request Example

    {
      "op": "subscribe",
      "args": [
        {
          "channel": "liquidation-warning",
          "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
    liquidation-warning
    > instType String Yes Instrument type
    MARGIN
    SWAP
    FUTURES
    OPTION
    ANY
    > instFamily String No Instrument family
    Applicable to FUTURES/SWAP/OPTION
    > instId String No Instrument ID

    Successful Response Example

    {
      "event": "subscribe",
      "arg": {
        "channel": "liquidation-warning",
        "instType": "ANY"
      },
      "connId": "a4d3ae55"
    }
    

    Failure Response Example

    {
      "event": "error",
      "code": "60012",
      "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"liquidation-warning\", \"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
    OPTION
    FUTURES
    SWAP
    MARGIN
    ANY
    > instFamily String No Instrument family
    > 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":"liquidation-warning",
            "uid": "77982378738415879",
            "instType":"FUTURES"
        },
        "data":[
            {
                "cTime":"1619507758793",
                "ccy":"ETH",
                "instId":"ETH-USD-210430",
                "instType":"FUTURES",
                "lever":"10",
                "markPx":"2353.849",
                "mgnMode":"isolated",
                "mgnRatio":"11.731726509588816",
                "pTime":"1619507761462",
                "pos":"1",
                "posCcy":"",
                "posId":"307173036051017730",
                "posSide":"long",
                "uTime":"1619507761462",
            }
        ]
    }
    

    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
    > mgnMode String Margin mode, cross isolated
    > posId String Position ID
    > posSide String Position side
    long
    short
    net (FUTURES/SWAP/OPTION: positive pos means long position and negative pos means short position. MARGIN: posCcy being base currency means long position, posCcy being quote currency means short position.)
    > pos String Quantity of positions
    > posCcy String Position currency, only applicable to MARGIN positions
    > instId String Instrument ID, e.g. BTC-USDT-SWAP
    > lever String Leverage, not applicable to OPTION seller
    > markPx String Mark price
    > mgnRatio String Margin ratio
    > ccy String Currency used for margin
    > cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085.
    > uTime String Latest time position was adjusted, Unix timestamp format in milliseconds, e.g. 1597026383085.
    > pTime String Push time of positions information, Unix timestamp format in milliseconds, e.g. 1597026383085.

    Account greeks channel

    Retrieve account greeks information. Data will be pushed when triggered by events such as increase/decrease positions or cash balance in account, and will also be pushed in regular interval according to subscription granularity.
    Concurrent connection to this channel will be restricted by the following rules: WebSocket connection count limit.

    URL Path

    /ws/v5/private (required login)

    Request Example : single

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

    Request Example

    {
        "op": "subscribe",
        "args": [{
            "channel": "account-greeks"
        }]
    }
    

    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-greeks
    > ccy String No Currency

    Successful Response Example : single

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

    Successful Response Example

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

    Failure Response Example

    {
        "event": "error",
        "code": "60012",
        "msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"account-greeks\", \"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-greeks
    > ccy String No Currency
    code String No Error code
    msg String No Error message
    connId String Yes WebSocket connection ID

    Push Data Example: single

    {
      "arg": {
        "channel": "account-greeks",
        "uid": "77982378738415879",
        "ccy": "BTC"
      },
      "data": [
        {           
          "thetaBS": "",
          "thetaPA":"",
          "deltaBS":"",
          "deltaPA":"",
          "gammaBS":"",
          "gammaPA":"",
          "vegaBS":"",    
          "vegaPA":"",
          "ccy":"BTC",
          "ts":"1620282889345"
        }
      ]
    }
    

    Push Data Example

    {
      "arg": {
        "channel": "account-greeks",
        "uid": "77982378738415879",
        "ccy": "BTC"
      },
      "data": [
        {           
          "thetaBS": "",
          "thetaPA":"",
          "deltaBS":"",
          "deltaPA":"",
          "gammaBS":"",
          "gammaPA":"",
          "vegaBS":"",    
          "vegaPA":"",
          "ccy":"BTC",
          "ts":"1620282889345"
        },
        {           
          "thetaBS": "",
          "thetaPA":"",
          "deltaBS":"",
          "deltaPA":"",
          "gammaBS":"",
          "gammaPA":"",
          "vegaBS":"",    
          "vegaPA":"",
          "ccy":"USDT",
          "ts":"1620282889345"
        }
      ]
    }
    

    Push data parameters

    Parameters Types Description
    arg Object Successfully subscribed channel
    > channel String Channel name
    > uid String User Identifier
    data Array Subscribed data
    > deltaBS String delta: Black-Scholes Greeks in dollars
    > deltaPA String delta: Greeks in coins
    > gammaBS String gamma: Black-Scholes Greeks in dollars, only applicable to OPTION
    > gammaPA String gamma: Greeks in coins, only applicable to OPTION
    > thetaBS String theta: Black-Scholes Greeks in dollars, only applicable to OPTION
    > thetaPA String theta: Greeks in coins, only applicable to OPTION
    > vegaBS String vega: Black-Scholes Greeks in dollars, only applicable to OPTION
    > vegaPA String vega: Greeks in coins, only applicable to OPTION
    > ccy String Currency
    > ts String Push time of account greeks, Unix timestamp format in milliseconds, e.g. 1597026383085

    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 of lead instruments for Copy Trading: 4 requests per 2 seconds

    Rate limit rule (except Options): UserID + Instrument ID

    Rate limit rule (Options only): UserID + Instrument Family

    Rate limit of this endpoint will also be affected by the rules Sub-account rate limit and Fill ratio based sub-account rate limit.

    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)
    
    # Spot 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
    Margin mode cross isolated
    Non-Margin mode cash
    spot_isolated (only applicable to SPOT lead trading, tdMode should be spot_isolated for SPOT lead trading.)
    ccy String No Margin currency
    Only applicable to cross MARGIN orders in Spot and futures mode.
    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
    posSide String Conditional Position side
    The default is net in the net mode
    It is required in the long/short mode, and can only be long or short.
    Only applicable to FUTURES/SWAP.
    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
    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)
    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.
    When placing an option order, one of px/pxUsd/pxVol must be filled in, and only one can be filled in
    pxUsd String Conditional Place options orders in USD
    Only applicable to options
    When placing an option order, one of px/pxUsd/pxVol must be filled in, and only one can be filled in
    pxVol String Conditional Place options orders based on implied volatility, where 1 represents 100%
    Only applicable to options
    When placing an option order, one of px/pxUsd/pxVol must be filled in, and only one can be filled in
    reduceOnly Boolean No Whether orders can only reduce in position size.
    Valid options: true or false. The default value is false.
    Only applicable to MARGIN orders, and FUTURES/SWAP orders in net mode
    Only applicable to Spot and futures mode and Multi-currency margin
    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
    quickMgnType String No Quick Margin type. Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    The default value is manual
    (Deprecated)
    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
    (deprecated)
    stpMode String No Self trade prevention mode.
    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
    For condition TP order, if you fill in this parameter, you should fill in the take-profit order price as well.
    > tpOrdPx String Conditional Take-profit order price

    For condition TP order, if you fill in this parameter, you should fill in the take-profit trigger price as well.
    For limit TP order, you need to fill in this parameter, take-profit trigger needn‘t to be filled.
    If the price is -1, take-profit will be executed at the market price.
    > tpOrdKind String No TP order kind
    condition
    limit
    The default is condition
    > 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
    index: index price
    mark: mark price
    The default is last
    > slTriggerPxType String No Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark 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": "",
          "ts":"1695190491421",
          "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
    > ts String Timestamp when the order request processing is finished by our system, Unix timestamp format in milliseconds, e.g. 1597026383085
    > 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 of lead instruments for Copy Trading: 4 requests per 2 seconds

    Rate limit rule (except Options): UserID + Instrument ID

    Rate limit rule (Options only): UserID + Instrument Family

    Rate limit of this endpoint will also be affected by the rules Sub-account rate limit and Fill ratio based sub-account rate limit.

    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
    Margin mode cross isolated
    Non-Margin mode cash
    spot_isolated (only applicable to SPOT lead trading, tdMode should be spot_isolated for SPOT lead trading.)
    ccy String No Margin currency
    Only applicable to cross MARGIN orders in Spot and futures mode.
    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
    posSide String Conditional Position side
    The default is net in the net mode
    It is required in the long/short mode, and can only be long or short.
    Only applicable to FUTURES/SWAP.
    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
    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)
    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.
    When placing an option order, one of px/pxUsd/pxVol must be filled in, and only one can be filled in
    pxUsd String Conditional Place options orders in USD
    Only applicable to options
    When placing an option order, one of px/pxUsd/pxVol must be filled in, and only one can be filled in
    pxVol String Conditional Place options orders based on implied volatility, where 1 represents 100%
    Only applicable to options
    When placing an option order, one of px/pxUsd/pxVol must be filled in, and only one can be filled in
    reduceOnly Boolean No Whether the order can only reduce position size.
    Valid options: true or false. The default value is false.
    Only applicable to MARGIN orders, and FUTURES/SWAP orders in net mode
    Only applicable to Spot and futures mode and Multi-currency margin
    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
    quickMgnType String No Quick Margin type. Only applicable to Quick Margin Mode of isolated margin
    manual, auto_borrow, auto_repay
    The default value is manual
    (Deprecated)
    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
    (deprecated)
    stpMode String No Self trade prevention mode.
    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
    For condition TP order, if you fill in this parameter, you should fill in the take-profit order price as well.
    > tpOrdPx String Conditional Take-profit order price
    For condition TP order, if you fill in this parameter, you should fill in the take-profit trigger price as well.
    For limit TP order, you need to fill in this parameter, take-profit trigger needn't to be filled.
    If the price is -1, take-profit will be executed at the market price.
    > tpOrdKind String No TP order kind
    condition
    limit
    The default is condition
    > 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
    index: index price
    mark: mark price
    The default is last
    > slTriggerPxType String No Stop-loss trigger price type
    last: last price
    index: index price
    mark: mark 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":"",
                "ts":"1695190491421",
                "sCode":"0",
                "sMsg":""
            },
            {
                "clOrdId":"oktswap7",
                "ordId":"12344",
                "tag":"",
                "ts":"1695190491421",
                "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
    > ts String Timestamp when the order request processing is finished by our system, Unix timestamp format in milliseconds, e.g. 1597026383085
    > 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 (except Options): UserID + Instrument ID

    Rate limit rule (Options only): UserID + Instrument Family

    HTTP Request

    POST /api/v5/trade/cancel-order

    Request Example

    POST /api/v5/trade/cancel-order
    body
    {
        "ordId":"590908157585625111",
        "instId":"BTC-USD-190927"
    }
    
    
    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",
                "ts":"1695190491421",
                "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
    > ts String Timestamp when the order request processing is finished by our system, Unix timestamp format in milliseconds, e.g. 1597026383085
    > 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 (except Options): UserID + Instrument ID

    Rate limit rule (Options only): UserID + Instrument Family

    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",
                "ts":"1695190491421",
                "sCode":"0",
                "sMsg":""
            },
            {
                "clOrdId":"oktswap7",
                "ordId":"12344",
                "ts":"1695190491421",
                "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
    > ts String Timestamp when the order request processing is finished by our system, Unix timestamp format in milliseconds, e.g. 1597026383085
    > 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 of lead instruments for Copy Trading: 4 requests per 2 seconds

    Rate limit rule (except Options): UserID + Instrument ID

    Rate limit rule (Options only): UserID + Instrument Family

    Rate limit of this endpoint will also be affected by the rules Sub-account rate limit and Fill ratio based sub-account rate limit.

    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 and it has to be larger than 0. When amending a partially-filled order, the newSz should include the amount that has been filled.
    newPx String Conditional New price after amendment.
    When modifying options orders, users can only fill in one of the following: newPx, newPxUsd, or newPxVol. It must be consistent with parameters when placing orders. For example, if users placed the order using px, they should use newPx when modifying the order.
    newPxUsd String Conditional Modify options orders using USD prices
    Only applicable to options.
    When modifying options orders, users can only fill in one of the following: newPx, newPxUsd, or newPxVol.
    newPxVol String Conditional Modify options orders based on implied volatility, where 1 represents 100%
    Only applicable to options.
    When modifying options orders, users can only fill in one of the following: newPx, newPxUsd, or newPxVol.
    attachAlgoOrds Array of object No TP/SL information attached when placing order
    > attachAlgoId String Conditional The order ID of attached TP/SL order. It can be used to identity the TP/SL order when amending. 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.
    > newTpOrdPx String Conditional Take-profit order price
    If the price is -1, take-profit will be executed at the market price.
    > newTpOrdKind String No TP order kind
    condition
    limit
    > 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.
    > newSlOrdPx String Conditional Stop-loss order price
    If the price is -1, stop-loss will be executed at the market price.
    > 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",
             "ts":"1695190491421",
             "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
    > ts String Timestamp when the order request processing is finished by our system, Unix timestamp format in milliseconds, e.g. 1597026383085
    > 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 of lead instruments for Copy Trading: 4 requests per 2 seconds

    Rate limit rule (except Options): UserID + Instrument ID

    Rate limit rule (Options only): UserID + Instrument Family

    Rate limit of this endpoint will also be affected by the rules 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 and it has to be larger than 0. When amending a partially-filled order, the newSz should include the amount that has been filled.
    newPx String Conditional New price after amendment.
    When modifying options orders, users can only fill in one of the following: newPx, newPxUsd, or newPxVol. It must be consistent with parameters when placing orders. For example, if users placed the order using px, they should use newPx when modifying the order.
    newPxUsd String Conditional Modify options orders using USD prices
    Only applicable to options.
    When modifying options orders, users can only fill in one of the following: newPx, newPxUsd, or newPxVol.
    newPxVol String Conditional Modify options orders based on implied volatility, where 1 represents 100%
    Only applicable to options.
    When modifying options orders, users can only fill in one of the following: newPx, newPxUsd, or newPxVol.
    attachAlgoOrds Array of object No TP/SL information attached when placing order
    > attachAlgoId String Conditional The order ID of attached TP/SL order. It can be used to identity the TP/SL order when amending. 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.
    > newTpOrdPx String Conditional Take-profit order price
    If the price is -1, take-profit will be executed at the market price.
    > newTpOrdKind String No TP order kind
    condition
    limit
    > 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.
    > newSlOrdPx String Conditional Stop-loss order price
    If the price is -1, stop-loss will be executed at the market price.
    > 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",
                "ts":"1695190491421",
                "reqId":"b12344",
                "sCode":"0",
                "sMsg":""
            },
            {
                "clOrdId":"oktswap7",
                "ordId":"12344",
                "ts":"1695190491421",
                "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
    > ts String Timestamp when the order request processing is finished by our system, Unix timestamp format in milliseconds, e.g. 1597026383085
    > 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 / Close positions

    Close the position of an instrument via a market order.

    Rate Limit: 20 requests per 2 seconds

    Rate limit rule (except Options): UserID + Instrument ID

    Rate limit rule (Options only): UserID + Instrument Family

    HTTP Request

    POST /api/v5/trade/close-position

    Request Example

    POST /api/v5/trade/close-position
    body
    {
        "instId":"BTC-USDT-SWAP",
        "mgnMode":"cross"
    }
    
    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)
    
    # Close the position of an instrument via a market order
    result = tradeAPI.close_positions(
        instId="BTC-USDT-SWAP",
        mgnMode="cross"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instId String Yes Instrument ID
    posSide String Conditional Position side
    This parameter can be omitted in net mode, and the default value is net. You can only fill with net.
    This parameter must be filled in under the long/short mode. Fill in long for close-long and short for close-short.
    mgnMode String Yes Margin mode
    cross isolated
    ccy String Conditional Margin currency, required in the case of closing cross MARGIN position for Spot and futures mode.
    autoCxl Boolean No Whether any pending orders for closing out needs to be automatically canceled when close position via a market order.
    false or true, the default is false.
    clOrdId String No Client-supplied ID
    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.

    Response Example

    {
        "code": "0",
        "data": [
            {
                "clOrdId": "",
                "instId": "BTC-USDT-SWAP",
                "posSide": "long",
                "tag": ""
            }
        ],
        "msg": ""
    }
    

    Response Parameters

    Parameter Type Description
    instId String Instrument ID
    posSide String Position side
    clOrdId String Client-supplied ID
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
    tag String Order tag
    A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.

    GET / Order details

    Retrieve order details.

    Rate Limit: 60 requests per 2 seconds

    Rate limit rule (except Options): UserID + Instrument ID

    Rate limit rule (Options only): UserID + Instrument Family

    HTTP Request

    GET /api/v5/trade/order

    Request Example

    GET /api/v5/trade/order?ordId=1753197687182819328&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
    MARGIN
    SWAP
    FUTURES
    OPTION
    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 Spot and futures mode.
    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
    (deprecated)
    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 can be used to identity the TP/SL order when amending. 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.
    > tpOrdKind String TP order kind
    condition
    limit
    > 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
    > amendPxOnTriggerType String Whether to enable Cost-price SL. Only applicable to SL order of split TPs.
    0: disable, the default value
    1: Enable
    > failCode String The error code when failing to place TP/SL order, e.g. 51020
    The default is ""
    > failReason String The error reason when failing to place TP/SL order.
    The default is ""
    linkedAlgoOrd Object Linked SL order detail, only applicable to the order that is placed by one-cancels-the-other (OCO) order that contains the TP limit order.
    > algoId Object Algo ID
    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
    25: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.
    isTpLimit String Whether it is TP limit order. 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
    MARGIN
    SWAP
    FUTURES
    OPTION
    uly String No Underlying
    instFamily String No Instrument family
    Applicable to FUTURES/SWAP/OPTION
    instId String No Instrument ID, e.g. BTC-USD-200927
    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
    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)
    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",
        "data": [
            {
                "accFillSz": "0",
                "algoClOrdId": "",
                "algoId": "",
                "attachAlgoClOrdId": "",
                "attachAlgoOrds": [],
                "avgPx": "",
                "cTime": "1724733617998",
                "cancelSource": "",
                "cancelSourceReason": "",
                "category": "normal",
                "ccy": "",
                "clOrdId": "",
                "fee": "0",
                "feeCcy": "BTC",
                "fillPx": "",
                "fillSz": "0",
                "fillTime": "",
                "instId": "BTC-USDT",
                "instType": "SPOT",
                "isTpLimit": "false",
                "lever": "",
                "linkedAlgoOrd": {
                    "algoId": ""
                },
                "ordId": "1752588852617379840",
                "ordType": "post_only",
                "pnl": "0",
                "posSide": "net",
                "px": "13013.5",
                "pxType": "",
                "pxUsd": "",
                "pxVol": "",
                "quickMgnType": "",
                "rebate": "0",
                "rebateCcy": "USDT",
                "reduceOnly": "false",
                "side": "buy",
                "slOrdPx": "",
                "slTriggerPx": "",
                "slTriggerPxType": "",
                "source": "",
                "state": "live",
                "stpId": "",
                "stpMode": "cancel_maker",
                "sz": "0.001",
                "tag": "",
                "tdMode": "cash",
                "tgtCcy": "",
                "tpOrdPx": "",
                "tpTriggerPx": "",
                "tpTriggerPxType": "",
                "tradeId": "",
                "uTime": "1724733617998"
            }
        ],
        "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 Spot and futures mode.
    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 can be used to identity the TP/SL order when amending. 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.
    > tpOrdKind String TP order kind
    condition
    limit
    > 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
    > failCode String The error code when failing to place TP/SL order, e.g. 51020
    The default is ""
    > failReason String The error reason when failing to place TP/SL order.
    The default is ""
    linkedAlgoOrd Object Linked SL order detail, only applicable to the order that is placed by one-cancels-the-other (OCO) order that contains the TP limit order.
    > algoId Object Algo ID
    stpId String Self trade prevention ID
    Return "" if self trade prevention is not applicable
    (deprecated)
    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
    25: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 "".
    isTpLimit String Whether it is TP limit order. true or false
    uTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
    cTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
    cancelSource String Code of the cancellation source.
    cancelSourceReason String Reason for the cancellation.

    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
    MARGIN
    SWAP
    FUTURES
    OPTION
    uly String No Underlying
    Applicable to FUTURES/SWAP/OPTION
    instFamily String No Instrument family
    Applicable to FUTURES/SWAP/OPTION
    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
    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)
    state String No State
    canceled
    filled
    mmp_canceled: Order canceled automatically due to Market Maker Protection
    category String No Category
    twap
    adl
    full_liquidation
    partial_liquidation
    delivery
    ddh: Delta dynamic hedge
    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 cTime. Unix timestamp format in milliseconds, e.g. 1597026383085
    end String No Filter with an end timestamp cTime. 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",
                "lever": "",
                "linkedAlgoOrd": {
                    "algoId": ""
                },
                "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",
                "isTpLimit": "false"
            }
        ],
        "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 Spot and futures mode.
    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 can be used to identity the TP/SL order when amending. 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.
    > tpOrdKind String TP order kind
    condition
    limit
    > 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
    > failCode String The error code when failing to place TP/SL order, e.g. 51020
    The default is ""
    > failReason String The error reason when failing to place TP/SL order.
    The default is ""
    linkedAlgoOrd Object Linked SL order detail, only applicable to the order that is placed by one-cancels-the-other (OCO) order that contains the TP limit order.
    > algoId Object Algo ID
    stpId String Self trade prevention ID
    Return "" if self trade prevention is not applicable
    (deprecated)
    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
    25: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 "".
    isTpLimit String Whether it is TP limit order. true or false
    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)

    Get completed orders which are placed in the last 3 months, including those placed 3 months ago but completed in the last 3 months.

    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
    
    
    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 3 months
    result = tradeAPI.get_orders_history_archive(
        instType="SPOT",
        ordType="post_only,fok,ioc"
    )
    print(result)
    

    Request Parameters

    Parameter Type Required Description
    instType String yes Instrument type
    SPOT
    MARGIN
    SWAP
    FUTURES
    OPTION
    uly String No Underlying
    Applicable to FUTURES/SWAP/OPTION
    instFamily String No Instrument family
    Applicable to FUTURES/SWAP/OPTION
    instId String No Instrument ID, e.g. BTC-USD-200927
    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
    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)
    state String No State
    canceled
    filled
    mmp_canceled: Order canceled automatically due to Market Maker Protection
    category String No Category
    twap
    adl
    full_liquidation
    partial_liquidation
    delivery
    ddh: Delta dynamic hedge
    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 cTime. Unix timestamp format in milliseconds, e.g. 1597026383085
    end String No Filter with an end timestamp cTime. 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",
                "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",
                "isTpLimit": "false",
                "linkedAlgoOrd": {
                    "algoId": ""
                }
            }
        ],
        "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 Spot and futures mode.
    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 can be used to identity the TP/SL order when amending. 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.
    > tpOrdKind String TP order kind
    condition
    limit
    > 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
    > failCode String The error code when failing to place TP/SL order, e.g. 51020
    The default is ""
    > failReason String The error reason when failing to place TP/SL order.
    The default is ""
    linkedAlgoOrd Object Linked SL order detail, only applicable to the order that is placed by one-cancels-the-other (OCO) order that contains the TP limit order.
    > algoId Object Algo ID
    stpId String Self trade prevention ID
    Return "" if self trade prevention is not applicable
    (deprecated)
    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
    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
    25:The normal order triggered by the trailing stop order
    rebateCcy String Rebate currency
    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 "".
    isTpLimit String Whether it is TP limit order. true or false
    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
    MARGIN
    SWAP
    FUTURES
    OPTION
    uly String No Underlying
    Applicable to FUTURES/SWAP/OPTION
    instFamily String No Instrument family
    Applicable to FUTURES/SWAP/OPTION
    instId String No Instrument ID, e.g. BTC-USDT
    ordId String No Order ID
    subType String No Transaction type
    1: Buy
    2: Sell
    3: Open long
    4: Open short
    5: Close long
    6: Close short
    100: Partial liquidation close long
    101: Partial liquidation close short
    102: Partial liquidation buy
    103: Partial liquidation sell
    104: Liquidation long
    105: Liquidation short
    106: Liquidation buy
    107: Liquidation sell
    110: Liquidation transfer in
    111: Liquidation transfer out
    118: System token conversion transfer in
    119: System token conversion transfer out
    125: ADL close long
    126: ADL close short
    127: ADL buy
    128: ADL sell
    212: Auto borrow of quick margin
    213: Auto repay of quick margin
    204: block trade buy
    205: block trade sell
    206: block trade open long
    207: block trade open short
    208: block trade close open
    209: block trade close short
    270: Spread trading buy
    271: Spread trading sell
    272: Spread trading open long
    273: Spread trading open short
    274: Spread trading close long
    275: Spread trading close short
    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 ts. Unix timestamp format in milliseconds, e.g. 1597026383085
    end String No Filter with an end timestamp 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",
        "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",
                "subType": "1",
                "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
    subType String Transaction type
    tag String Order tag
    fillPx String Last filled price. It is the same as the px from "Get bills details".
    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?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 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
    MARGIN
    SWAP
    FUTURES
    OPTION
    uly String No Underlying
    Applicable to FUTURES/SWAP/OPTION