Overview
Welcome to our V5 API documentation. Turkey provides REST and WebSocket APIs to suit your trading needs.
API Resources and Support
Tutorials
- Learn how to trade with V5 API: Best practice to OKX’s v5 API
- Learn python spot trading step by step: Python Spot Trading Tutorial
- Learn python derivatives trading step by step: Python Derivatives Trading Tutorial
Python libraries
- Use Python SDK for easier integration: Python SDK
- Get access to our market maker python sample code Python market maker sample
Customer service
- Get support in our Telegram group: https://t.me/OKXAPI
- Subscribe to API related changes: https://t.me/OKExAPIChannel
- Please take 1 minute to help us improve: V5 API Satisfaction Survey
- If you have any questions, please consult online 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:
- APIKey
- SecretKey
- Passphrase
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.
- Read : Can request and view account info such as bills and order history which need read permission
- Trade : Can place and cancel orders, funding transfer, make settings which need write permission
- Withdraw : Can make withdrawals
REST Authentication
Making Requests
All private REST requests must contain the following headers:
OK-ACCESS-KEY
The API Key as a String.OK-ACCESS-SIGN
The Base64-encoded signature (see Signing Messages subsection for details).OK-ACCESS-TIMESTAMP
The UTC timestamp of your request .e.g : 2020-12-08T09:08:57.715ZOK-ACCESS-PASSPHRASE
The passphrase you specified when creating the APIKey.
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:
- Create a prehash string of timestamp + method + requestPath + body (where + represents String concatenation).
- Prepare the SecretKey.
- Sign the prehash string with the SecretKey using the HMAC SHA256.
- Encode the signature in the Base64 format.
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:
- The WebSocket request header size for data transmission between client and server is only 2 bytes.
- Either the client or server can initiate data transmission.
- There's no need to repeatedly create and delete TCP connections, saving resources on bandwidth and server.
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:
- Orders channel
- Account channel
- Positions channel
- Balance and positions channel
- Position risk warning channel
- 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 | Operationlogin |
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 | Operationlogin error |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
api_key: Unique identification for invoking API. Requires user to apply one manually.
passphrase: API Key password
timestamp: the Unix Epoch time, the unit is seconds
sign: signature string, the signature algorithm is as follows:
First concatenate timestamp
, method
, requestPath
, strings, then use HMAC SHA256 method to encrypt the concatenated string with SecretKey, and then perform Base64 encoding.
secretKey: The security key generated when the user applies for APIKey, e.g. : 22582BD0CFF14C41EDBF1AB98506286D
Example of timestamp: const timestamp = '' + Date.now() / 1,000
Among sign example: sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(timestamp +'GET'+'/users/self/verify', secretKey))
method: always 'GET'.
requestPath : always '/users/self/verify'
Subscribe
Subscription Instructions
Request format description
{
"op": "subscribe",
"args": ["<SubscriptionTopic>"]
}
WebSocket channels are divided into two categories: public
and private
channels.
Public channels
-- No authentication is required, include tickers channel, K-Line channel, 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 | Operationsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel name |
> instType | String | No | Instrument typeSPOT 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 typeSPOT 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 | Operationunsubscribe |
args | Array | Yes | List of channels to unsubscribe from |
> channel | String | Yes | Channel name |
> instType | String | No | Instrument typeSPOT 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 typeSPOT 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:
- REST:
https://tr.okx.com
- Public WebSocket:
wss://ws.okx.com:8443/ws/v5/public
- Private WebSocket:
wss://ws.okx.com:8443/ws/v5/private
- Business WebSocket:
wss://ws.okx.com:8443/ws/v5/business
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:
WebSocket login and subscription rate limits are based on connection.
Public unauthenticated REST rate limits are based on IP address.
Private REST rate limits are based on User ID (sub-accounts have individual User IDs).
WebSocket order management rate limits are based on User ID (sub-accounts have individual User IDs).
Trading-related APIs
For Trading-related APIs (place order, cancel order, and amend order) the following conditions apply:
Rate limits are shared across the REST and WebSocket channels.
Rate limits for placing orders, amending orders, and cancelling orders are independent from each other.
Rate limits are defined on the Instrument ID level (except Options)
Rate limits for Options are defined based on the Instrument Family level. Refer to the Get instruments endpoint to view Instrument Family information.
Rate limits for a multiple order endpoint and a single order endpoint are also independent, with the exception being when there is only one order sent to a multiple order endpoint, the order will be counted as a single order and adopt the single order rate limit.
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.
- 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.
- 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.
- Account A (master account):
- BTC-USDT-SWAP trade volume = 100 USDT, order count = 10;
- XRP-USDT trade volume = 20 USDT, order count = 15;
- Sub-account ratio = (100+20) / (10 * 1 + 15 * 0.1) = 10.4
- Account B (sub-account):
- BTC-USDT-SWAP trade volume = 200 USDT, order count = 100;
- XRP-USDT trade volume = 20 USDT, order count = 30;
- Sub-account ratio = (200+20) / (100 * 1 + 30 * 0.1) = 2.13
- Account C (sub-account):
- BTC-USDT-SWAP trade volume = 300 USDT, order count = 1000;
- XRP-USDT trade volume = 20 USDT, order count = 45;
- Sub-account ratio = (300+20) / (100 * 1 + 45 * 0.1) = 3.06
- 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
- Rate limit of accounts
- Account A = max(10.4, 3.01) = 10.4 -> 2500 order requests/2s
- Account B = max(2.13, 3.01) = 3.01 -> 1750 order requests/2s
- 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.
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 typeSPOT : SpotMARGIN : MarginSWAP : Perpetual FuturesFUTURES : Expiry FuturesOPTION : 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 typelinear : linear contractinverse : inverse contract Only applicable to FUTURES /SWAP |
state | String | Instrument statuslive 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 typesnormal : normal tradingpre_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",
"fixedBal": "0",
"frozenBal": "158.573",
"imr": "",
"interest": "0",
"isoEq": "0",
"isoLiab": "0",
"isoUpl": "0",
"liab": "0",
"maxLoan": "0",
"mgnRatio": "",
"mmr": "",
"notionalLever": "",
"ordFrozen": "0",
"spotInUseAmt": "",
"spotIsoBal": "0",
"stgyEq": "150",
"twap": "0",
"uTime": "1705449605015",
"upl": "-7.545600000000006",
"uplLiab": "0"
}
],
"imr": "8.57068529",
"isoEq": "0",
"mgnRatio": "143682.59776662575",
"mmr": "0.3428274116",
"notionalUsd": "85.7068529",
"ordFroz": "0",
"totalEq": "55837.43556134779",
"uTime": "1705474164160",
"upl": "-7.543562688000006"
}
],
"msg": ""
}
Response Parameters
Parameters | Types | Description |
---|---|---|
uTime | String | Update time of account information, millisecond format of Unix timestamp, e.g. 1597026383085 |
totalEq | String | The total amount of equity in USD |
isoEq | String | Isolated margin equity in USD Applicable to 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 |
> isoLiab | String | Isolated liabilities of currency Applicable to Multi-currency margin /Portfolio margin |
> mgnRatio | String | Margin ratio of currency The index for measuring the risk of a certain asset in the account. Applicable to Spot and futures mode |
> 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 |
> spotIsoBal | String | Spot isolated balance Applicable to copy trading Applicable to Spot mode /Spot and futures mode |
> imr | String | Initial margin requirement at the currency level Applicable to Spot and futures mode |
> mmr | String | Maintenance margin requirement at the currency level Applicable to Spot and futures mode |
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 |
Get bills details (last 7 days)
Retrieve the bills of the account. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with the most recent first. This endpoint can retrieve data from the last 7 days.
Rate Limit: 5 requests per second
Rate limit rule: UserID
HTTP Request
GET /api/v5/account/bills
Request Example
GET /api/v5/account/bills
GET /api/v5/account/bills?instType=SPOT
import okx.Account as Account
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading:0 , demo trading:1
accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
# Get bills details (last 7 days)
result = accountAPI.get_account_bills()
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | No | Instrument typeSPOT |
ccy | String | No | Bill currency |
type | String | No | Bill type1 : Transfer2 : Trade6 : Margin transfer |
subType | String | No | Bill subtype1 : Buy2 : Sell11 : Transfer in12 : Transfer out236 : Easy convert in237 : Easy convert out |
after | String | No | Pagination of data to return records earlier than the requested bill ID. |
before | String | No | Pagination of data to return records newer than the requested bill ID. |
begin | String | No | Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
end | String | No | Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
limit | String | No | Number of results per request. The maximum is 100 . The default is 100 . |
Response Example
{
"code": "0",
"msg": "",
"data": [{
"bal": "8694.2179403378290202",
"balChg": "0.0219338232210000",
"billId": "623950854533513219",
"ccy": "USDT",
"clOrdId": "",
"execType": "T",
"fee": "-0.000021955779",
"fillFwdPx": "",
"fillIdxPx": "27104.1",
"fillMarkPx": "",
"fillMarkVol": "",
"fillPxUsd": "",
"fillPxVol": "",
"fillTime": "1695033476166",
"from": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"interest": "0",
"mgnMode": "isolated",
"notes": "",
"ordId": "623950854525124608",
"pnl": "0",
"posBal": "0",
"posBalChg": "0",
"px": "27105.9",
"subType": "1",
"sz": "0.021955779",
"tag": "",
"to": "",
"tradeId": "586760148",
"ts": "1695033476167",
"type": "2"
}]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
billId | String | Bill ID |
type | String | Bill type |
subType | String | Bill subtype |
ts | String | The time when the balance complete update, Unix timestamp format in milliseconds, e.g.1597026383085 |
balChg | String | Change in balance amount at the account level |
posBalChg | String | Change in balance amount at the position level |
bal | String | Balance at the account level |
posBal | String | Balance at the position level |
sz | String | Quantity |
px | String | Price which related to subType1 : Buy 2 : Sell |
ccy | String | Account balance currency |
pnl | String | Profit and loss |
fee | String | Fee Negative number represents the user transaction fee charged by the platform. Positive number represents rebate. |
mgnMode | String | Margin modeisolated cross When bills are not generated by position changes, the field returns "" |
instId | String | Instrument ID, e.g. BTC-USDT |
ordId | String | Order ID |
execType | String | Liquidity taker or makerT : takerM : maker |
from | String | The remitting account6 : Funding account18 : Trading accountOnly applicable to transfer . When bill type is not transfer , the field returns "". |
to | String | The beneficiary account6 : Funding account18 : Trading accountOnly applicable to transfer . When bill type is not transfer , the field returns "". |
notes | String | Notes |
interest | String | Interest |
tag | String | Order tag |
fillTime | String | Last filled time |
tradeId | String | Last traded ID |
clOrdId | String | Client Order ID as assigned by the client A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
fillIdxPx | String | Index price at the moment of trade execution For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT. |
fillMarkPx | String | Mark price when filled Applicable to FUTURES/SWAP/OPTIONS, return "" for other instrument types |
fillPxVol | String | Implied volatility when filled Only applicable to options; return "" for other instrument types |
fillPxUsd | String | Options price when filled, in the unit of USD Only applicable to options; return "" for other instrument types |
fillMarkVol | String | Mark volatility when filled Only applicable to options; return "" for other instrument types |
fillFwdPx | String | Forward price when filled Only applicable to options; return "" for other instrument types |
Get bills details (last 3 months)
Retrieve the account’s bills. The bill refers to all transaction records that result in changing the balance of an account. Pagination is supported, and the response is sorted with most recent first. This endpoint can retrieve data from the last 3 months.
Rate Limit: 5 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/account/bills-archive
Request Example
GET /api/v5/account/bills-archive
GET /api/v5/account/bills-archive?instType=SPOT
import okx.Account as Account
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading:0 , demo trading:1
accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
# Get bills details (last 3 months)
result = accountAPI.get_account_bills_archive()
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | No | Instrument typeSPOT |
ccy | String | No | Bill currency |
type | String | No | Bill type1 : Transfer2 : Trade6 : Margin transfer |
subType | String | No | Bill subtype1 : Buy2 : Sell11 : Transfer in12 : Transfer out236 : Easy convert in237 : Easy convert out |
after | String | No | Pagination of data to return records earlier than the requested bill ID. |
before | String | No | Pagination of data to return records newer than the requested bill ID. |
begin | String | No | Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
end | String | No | Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
limit | String | No | Number of results per request. The maximum is 100 . The default is 100 . |
Response Example
{
"code": "0",
"msg": "",
"data": [{
"bal": "8694.2179403378290202",
"balChg": "0.0219338232210000",
"billId": "623950854533513219",
"ccy": "USDT",
"clOrdId": "",
"execType": "T",
"fee": "-0.000021955779",
"fillFwdPx": "",
"fillIdxPx": "27104.1",
"fillMarkPx": "",
"fillMarkVol": "",
"fillPxUsd": "",
"fillPxVol": "",
"fillTime": "1695033476166",
"from": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"interest": "0",
"mgnMode": "isolated",
"notes": "",
"ordId": "623950854525124608",
"pnl": "0",
"posBal": "0",
"posBalChg": "0",
"px": "27105.9",
"subType": "1",
"sz": "0.021955779",
"tag": "",
"to": "",
"tradeId": "586760148",
"ts": "1695033476167",
"type": "2"
}]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
billId | String | Bill ID |
type | String | Bill type |
subType | String | Bill subtype |
ts | String | The time when the balance complete update, Unix timestamp format in milliseconds, e.g.1597026383085 |
balChg | String | Change in balance amount at the account level |
posBalChg | String | Change in balance amount at the position level |
bal | String | Balance at the account level |
posBal | String | Balance at the position level |
sz | String | Quantity |
px | String | Price which related to subType1 : Buy 2 : Sell |
ccy | String | Account balance currency |
pnl | String | Profit and loss |
fee | String | Fee Negative number represents the user transaction fee charged by the platform. Positive number represents rebate. |
mgnMode | String | Margin modeisolated cross When bills are not generated by position changes, the field returns "" |
instId | String | Instrument ID, e.g. BTC-USDT |
ordId | String | Order ID When bill type is not trade , the field returns "" |
execType | String | Liquidity taker or makerT : takerM : maker |
from | String | The remitting account6 : Funding account18 : Trading accountOnly applicable to transfer . When bill type is not transfer , the field returns "". |
to | String | The beneficiary account6 : Funding account18 : Trading accountOnly applicable to transfer . When bill type is not transfer , the field returns "". |
notes | String | Notes |
interest | String | Interest |
tag | String | Order tag |
fillTime | String | Last filled time |
tradeId | String | Last traded ID |
clOrdId | String | Client Order ID as assigned by the client A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
fillIdxPx | String | Index price at the moment of trade execution For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT. |
fillMarkPx | String | Mark price when filled Applicable to FUTURES/SWAP/OPTIONS, return "" for other instrument types |
fillPxVol | String | Implied volatility when filled Only applicable to options; return "" for other instrument types |
fillPxUsd | String | Options price when filled, in the unit of USD Only applicable to options; return "" for other instrument types |
fillMarkVol | String | Mark volatility when filled Only applicable to options; return "" for other instrument types |
fillFwdPx | String | Forward price when filled Only applicable to options; return "" for other instrument types |
Get account configuration
Retrieve current account configuration.
Rate Limit: 5 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/account/config
Request Example
GET /api/v5/account/config
import okx.Account as Account
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading:0 , demo trading:1
accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
# Retrieve current account configuration
result = accountAPI.get_account_config()
print(result)
Request Parameters
none
Response Example
{
"code": "0",
"data": [
{
"acctLv": "3",
"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"
}
],
"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 mode2 : Spot and futures mode3 : Multi-currency margin4 : 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 modelong_short_mode : long/short, only applicable to FUTURES /SWAP net_mode : net |
autoLoan | Boolean | Whether to borrow coins automaticallytrue : borrow coins automaticallyfalse : not borrow coins automatically |
greeksType | String | Current display type of GreeksPA : Greeks in coinsBS : 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 settingsautomatic : Auto transfersautonomy : Manual transfers |
mgnIsoMode | String | Margin isolated margin trading settingsautomatic : Auto transfersquick_margin : Quick Margin Mode (For new accounts, including subaccounts, some defaults will be automatic , and others will be quick_margin ) |
spotOffsetType | String | Risk offset type1 : Spot-Derivatives(USDT) to be offsetted2 : Spot-Derivatives(Coin) to be offsetted3 : Only derivatives to be offsettedOnly applicable to Portfolio margin |
roleType | String | Role type0 : General user1 : Leading trader2 : 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 activated0 : not activate1 : activated |
kycLv | String | Main account KYC level0 : No verification1 : level 1 completed2 : level 2 completed3 : level 3 completedIf 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 tokenread_only : Readtrade : Tradewithdraw : Withdraw |
Get maximum buy/sell amount or open amount
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/account/max-size
Request Example
GET /api/v5/account/max-size?instId=BTC-USDT&tdMode=cash
import okx.Account as Account
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading:0 , demo trading:1
accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
# Get maximum buy/sell amount or open amount
result = accountAPI.get_max_order_size(
instId="BTC-USDT",
tdMode="cash"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Single instrument or multiple instruments (no more than 5) separated with comma, e.g. BTC-USDT,ETH-USDT |
tdMode | String | Yes | Trade modecash |
px | String | No | Price The parameter will be ignored when multiple instruments are specified. |
Response Example
{
"code": "0",
"msg": "",
"data": [{
"ccy": "BTC",
"instId": "BTC-USDT",
"maxBuy": "0.0500695098559788",
"maxSell": "64.4798671570072269"
}]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instId | String | Instrument ID |
ccy | String | Currency used for margin |
maxBuy | String | SPOT : The maximum quantity in base currency that you can buy |
maxSell | String | SPOT : The maximum quantity in quote currency that you can sell |
Get maximum available tradable amount
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/account/max-avail-size
Request Example
# Query maximum available transaction amount for SPOT BTC-USDT
GET /api/v5/account/max-avail-size?instId=BTC-USDT&tdMode=cash
import okx.Account as Account
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading:0 , demo trading:1
accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
# Get maximum available transaction amount for SPOT BTC-USDT
result = accountAPI.get_max_avail_size(
instId="BTC-USDT",
tdMode="cash"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Single instrument or multiple instruments (no more than 5) separated with comma, e.g. BTC-USDT,ETH-USDT |
tdMode | String | Yes | Trade modecash |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"instId": "BTC-USDT",
"availBuy": "100",
"availSell": "1"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instId | String | Instrument ID |
availBuy | String | Amount available to buy |
availSell | String | Amount available to sell |
Get fee rates
Rate Limit: 5 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/account/trade-fee
Request Example
# Query trade fee rate of SPOT BTC-USDT
GET /api/v5/account/trade-fee?instType=SPOT&instId=BTC-USDT
import okx.Account as Account
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading:0 , demo trading:1
accountAPI = Account.AccountAPI(apikey, secretkey, passphrase, False, flag)
# Get trading fee rates of current account
result = accountAPI.get_fee_rates(
instType="SPOT",
instId="BTC-USDT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | Yes | Instrument typeSPOT |
instId | String | No | Instrument ID, e.g. BTC-USDT Applicable to SPOT |
Response Example
{
"code": "0",
"msg": "",
"data": [{
"category": "1", //Deprecated
"delivery": "",
"exercise": "",
"instType": "SPOT",
"level": "lv1",
"maker": "-0.0008",
"makerU": "",
"makerUSDC": "",
"taker": "-0.001",
"takerU": "",
"takerUSDC": "",
"ts": "1608623351857",
"fiat": []
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
level | String | Fee rate Level |
taker | String | For SPOT , it is taker fee rate of the USDT trading pairs. |
maker | String | For SPOT , it is maker fee rate of the USDT trading pairs. |
takerU | String | Taker fee rate of USDT-margined contracts, only applicable to FUTURES /SWAP |
makerU | String | Maker fee rate of USDT-margined contracts, only applicable to FUTURES /SWAP |
delivery | String | Delivery fee rate |
exercise | String | Fee rate for exercising the option |
instType | String | Instrument type |
takerUSDC | String | For SPOT , it is taker fee rate of the USDⓈ&Crypto trading pairs. |
makerUSDC | String | For SPOT , it is maker fee rate of the USDⓈ&Crypto trading pairs. |
ts | String | Data return time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
category | String | Currency category. Note: this parameter is already deprecated |
fiat | Array | Details of fiat fee rate |
> ccy | String | Fiat currency. |
> taker | String | Taker fee rate |
> maker | String | Maker fee rate |
WebSocket
Account channel
Retrieve account information. Data will be pushed when triggered by events such as placing order, canceling order, transaction execution, etc.
It will also be pushed in regular interval according to subscription granularity.
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 | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel nameaccount |
> 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 | Operationsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel nameaccount |
> 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"
}],
"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 | Margin ratio of currency The index for measuring the risk of a certain asset in the account. Applicable to Spot and futures mode |
>> 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 |
>> imr | String | Initial margin requirement at the currency level Applicable to Spot and futures mode |
>> mmr | String | Maintenance margin requirement at the currency level Applicable to Spot and futures mode |
>> smtSyncEq | String | Smark sync equity The default is "0", only applicable to copy trader |
Order Book Trading
Trade
All Trade
API endpoints require authentication.
POST / Place order
You can place an order only if you have sufficient funds.
Rate Limit: 60 requests per 2 seconds
Rate limit rule : UserID + Instrument ID
HTTP Request
POST /api/v5/trade/order
Request Example
place order for SPOT
POST /api/v5/trade/order
body
{
"instId":"BTC-USDT",
"tdMode":"cash",
"clOrdId":"b15",
"side":"buy",
"ordType":"limit",
"px":"2.15",
"sz":"2"
}
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# 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 modecash |
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 sidebuy sell |
ordType | String | Yes | Order type market : Market order limit : Limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order |
sz | String | Yes | Quantity to buy or sell |
px | String | Conditional | Order price. Only applicable to limit ,post_only ,fok ,ioc order. |
tgtCcy | String | No | Whether the target currency uses the quote or base currency.base_ccy : Base currencyquote_ccy : Quote currencyOnly applicable to SPOT Market OrdersDefault is quote_ccy for buy, base_ccy for sell |
banAmend | Boolean | No | Whether to disallow the system from amending the size of the SPOT Market Order. Valid options: true or false . The default value is false .If true , system will not amend and reject the market order if user does not have sufficient funds. Only applicable to SPOT Market Orders |
stpId | String | No | Numerical integers defined by user in the range of 1<= x<= 999999999 |
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 If you fill in this parameter, you should fill in the take-profit order price as well. |
> tpOrdPx | String | Conditional | Take-profit order price If you fill in this parameter, you should fill in the take-profit trigger price as well. If the price is -1, take-profit will be executed at the market price. |
> slTriggerPx | String | Conditional | Stop-loss trigger price If you fill in this parameter, you should fill in the stop-loss order price. |
> slOrdPx | String | Conditional | Stop-loss order price If you fill in this parameter, you should fill in the stop-loss trigger price. If the price is -1, stop-loss will be executed at the market price. |
> tpTriggerPxType | String | No | Take-profit trigger price typelast : last priceThe default is last |
> slTriggerPxType | String | No | Stop-loss trigger price typelast : last priceThe 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 triggered0 : disable, the default value 1 : Enable |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"clOrdId": "oktswap6",
"ordId": "312269865356374016",
"tag": "",
"sCode": "0",
"sMsg": ""
}
],
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
code | String | The result code, 0 means success |
msg | String | The error message, empty if the code is 0 |
data | Array of objects | Array of objects contains the response results |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> tag | String | Order tag |
> sCode | String | The code of the event execution result, 0 means success. |
> sMsg | String | Rejection or success message of event execution. |
inTime | String | Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 The time is recorded after authentication. |
outTime | String | Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
POST / Place multiple orders
Place orders in batches. Maximum 20 orders can be placed per request.
Request parameters should be passed in the form of an array. Orders will be placed in turn
Rate Limit: 300 orders per 2 seconds
Rate limit rule: UserID + Instrument ID
HTTP Request
POST /api/v5/trade/batch-orders
Request Example
# batch place order for SPOT
POST /api/v5/trade/batch-orders
body
[
{
"instId":"BTC-USDT",
"tdMode":"cash",
"clOrdId":"b15",
"side":"buy",
"ordType":"limit",
"px":"2.15",
"sz":"2"
},
{
"instId":"BTC-USDT",
"tdMode":"cash",
"clOrdId":"b16",
"side":"buy",
"ordType":"limit",
"px":"2.15",
"sz":"2"
}
]
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Place multiple orders
place_orders_without_clOrdId = [
{"instId": "BTC-USDT", "tdMode": "cash", "clOrdId": "b15", "side": "buy", "ordType": "limit", "px": "2.15", "sz": "2"},
{"instId": "BTC-USDT", "tdMode": "cash", "clOrdId": "b16", "side": "buy", "ordType": "limit", "px": "2.15", "sz": "2"}
]
result = tradeAPI.place_multiple_orders(place_orders_without_clOrdId)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
tdMode | String | Yes | Trade modecash |
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 sidebuy sell |
ordType | String | Yes | Order type market : Market order limit : Limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order |
sz | String | Yes | Quantity to buy or sell |
px | String | Conditional | Order price. Only applicable to limit ,post_only ,fok ,ioc order. |
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 OrdersDefault is quote_ccy for buy, base_ccy for sell |
banAmend | Boolean | No | Whether to disallow the system from amending the size of the SPOT Market Order. Valid options: true or false . The default value is false .If true , system will not amend and reject the market order if user does not have sufficient funds. Only applicable to SPOT Market Orders |
stpId | String | No | Numerical integers defined by user in the range of 1<= x<= 999999999 |
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 If you fill in this parameter, you should fill in the take-profit order price as well. |
> tpOrdPx | String | Conditional | Take-profit order price If you fill in this parameter, you should fill in the take-profit trigger price as well. If the price is -1, take-profit will be executed at the market price. |
> slTriggerPx | String | Conditional | Stop-loss trigger price If you fill in this parameter, you should fill in the stop-loss order price. |
> slOrdPx | String | Conditional | Stop-loss order price If you fill in this parameter, you should fill in the stop-loss trigger price. If the price is -1, stop-loss will be executed at the market price. |
> tpTriggerPxType | String | No | Take-profit trigger price typelast : last priceThe default is last |
> slTriggerPxType | String | No | Stop-loss trigger price typelast : last priceThe 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 triggered0 : disable, the default value 1 : Enable |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"clOrdId":"oktswap6",
"ordId":"12345689",
"tag":"",
"sCode":"0",
"sMsg":""
},
{
"clOrdId":"oktswap7",
"ordId":"12344",
"tag":"",
"sCode":"0",
"sMsg":""
}
],
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
code | String | The result code, 0 means success |
msg | String | The error message, empty if the code is 0 |
data | Array of objects | Array of objects contains the response results |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> tag | String | Order tag |
> sCode | String | The code of the event execution result, 0 means success. |
> sMsg | String | Rejection or success message of event execution. |
inTime | String | Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 The time is recorded after authentication. |
outTime | String | Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
POST / Cancel order
Cancel an incomplete order.
Rate Limit: 60 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
HTTP Request
POST /api/v5/trade/cancel-order
Request Example
POST /api/v5/trade/cancel-order
body
{
"ordId":"590908157585625111",
"instId":"BTC-USDT"
}
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Cancel order
result = tradeAPI.cancel_order(instId="BTC-USDT", ordId = "590908157585625111")
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
ordId | String | Conditional | Order ID Either ordId or clOrdId is required. If both are passed, ordId will be used. |
clOrdId | String | Conditional | Client Order ID as assigned by the client |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"clOrdId":"oktswap6",
"ordId":"12345689",
"sCode":"0",
"sMsg":""
}
],
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
code | String | The result code, 0 means success |
msg | String | The error message, empty if the code is 0 |
data | Array of objects | Array of objects contains the response results |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> sCode | String | The code of the event execution result, 0 means success. |
> sMsg | String | Rejection message if the request is unsuccessful. |
inTime | String | Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 The time is recorded after authentication. |
outTime | String | Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
POST / Cancel multiple orders
Cancel incomplete orders in batches. Maximum 20 orders can be canceled per request. Request parameters should be passed in the form of an array.
Rate Limit: 300 orders per 2 seconds
Rate limit rule: UserID + Instrument ID
HTTP Request
POST /api/v5/trade/cancel-batch-orders
Request Example
POST /api/v5/trade/cancel-batch-orders
body
[
{
"instId":"BTC-USDT",
"ordId":"590908157585625111"
},
{
"instId":"BTC-USDT",
"ordId":"590908544950571222"
}
]
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Cancel multiple orders by ordId
cancel_orders_with_orderId = [
{"instId": "BTC-USDT", "ordId": "590908157585625111"},
{"instId": "BTC-USDT", "ordId": "590908544950571222"}
]
result = tradeAPI.cancel_multiple_orders(cancel_orders_with_orderId)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
ordId | String | Conditional | Order ID Either ordId or clOrdId is required. If both are passed, ordId will be used. |
clOrdId | String | Conditional | Client Order ID as assigned by the client |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"clOrdId":"oktswap6",
"ordId":"12345689",
"sCode":"0",
"sMsg":""
},
{
"clOrdId":"oktswap7",
"ordId":"12344",
"sCode":"0",
"sMsg":""
}
],
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
code | String | The result code, 0 means success |
msg | String | The error message, empty if the code is 0 |
data | Array of objects | Array of objects contains the response results |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> sCode | String | The code of the event execution result, 0 means success. |
> sMsg | String | Rejection message if the request is unsuccessful. |
inTime | String | Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 The time is recorded after authentication. |
outTime | String | Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
POST / Amend order
Amend an incomplete order.
Rate Limit: 60 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
HTTP Request
POST /api/v5/trade/amend-order
Request Example
POST /api/v5/trade/amend-order
body
{
"ordId":"590909145319051111",
"newSz":"2",
"instId":"BTC-USDT"
}
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Amend order
result = tradeAPI.amend_order(
instId="BTC-USDT",
ordId="590909145319051111",
newSz="2"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID |
cxlOnFail | Boolean | No | Whether the order needs to be automatically canceled when the order amendment fails Valid options: false or true , the default is false . |
ordId | String | Conditional | Order ID Either ordId or clOrdId is required. If both are passed, ordId will be used. |
clOrdId | String | Conditional | Client Order ID as assigned by the client |
reqId | String | No | Client Request ID as assigned by the client for order amendment A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. The response will include the corresponding reqId to help you identify the request if you provide it in the request. |
newSz | String | Conditional | New quantity after amendment. When amending a partially-filled order, the newSz should include the amount that has been filled. |
newPx | String | Conditional | New price after amendment. |
attachAlgoOrds | Array of object | No | TP/SL information attached when placing order |
> attachAlgoId | String | Conditional | The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely. |
> attachAlgoClOrdId | String | Conditional | Client-supplied Algo ID when placing order attaching TP/SL A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
> newTpTriggerPx | String | Conditional | Take-profit trigger price. Either the take profit trigger price or order price is 0, it means that the take profit is deleted. Only applicable to Expiry Futures and Perpetual Futures. |
> newTpOrdPx | String | Conditional | Take-profit order price If the price is -1, take-profit will be executed at the market price. Only applicable to Expiry Futures and Perpetual Futures. |
> newSlTriggerPx | String | Conditional | Stop-loss trigger price Either the stop loss trigger price or order price is 0, it means that the stop loss is deleted. Only applicable to Expiry Futures and Perpetual Futures. |
> newSlOrdPx | String | Conditional | Stop-loss order price If the price is -1, stop-loss will be executed at the market price. Only applicable to Expiry Futures and Perpetual Futures. |
> newTpTriggerPxType | String | Conditional | Take-profit trigger price typelast : last price index : index price mark : mark priceOnly applicable to FUTURES /SWAP If you want to add the take-profit, this parameter is required |
> newSlTriggerPxType | String | Conditional | Stop-loss trigger price typelast : last price index : index price mark : mark priceOnly applicable to FUTURES /SWAP If you want to add the stop-loss, this parameter is required |
> sz | String | Conditional | New size. Only applicable to TP order of split TPs, and it is required for TP order of split TPs |
> amendPxOnTriggerType | String | No | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"clOrdId":"",
"ordId":"12344",
"reqId":"b12344",
"sCode":"0",
"sMsg":""
}
],
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
code | String | The result code, 0 means success |
msg | String | The error message, empty if the code is 0 |
data | Array of objects | Array of objects contains the response results |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> reqId | String | Client Request ID as assigned by the client for order amendment. |
> sCode | String | The code of the event execution result, 0 means success. |
> sMsg | String | Rejection message if the request is unsuccessful. |
inTime | String | Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 The time is recorded after authentication. |
outTime | String | Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
POST / Amend multiple orders
Amend incomplete orders in batches. Maximum 20 orders can be amended per request. Request parameters should be passed in the form of an array.
Rate Limit: 300 orders per 2 seconds
Rate limit rule: UserID + Instrument ID
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 clOrdId is required, if both are passed, ordId will be used. |
clOrdId | String | Conditional | Client Order ID as assigned by the client |
reqId | String | No | Client Request ID as assigned by the client for order amendment A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. The response will include the corresponding reqId to help you identify the request if you provide it in the request. |
newSz | String | Conditional | New quantity after amendment. When amending a partially-filled order, the newSz should include the amount that has been filled. |
newPx | String | Conditional | New price after amendment. |
attachAlgoOrds | Array of object | No | TP/SL information attached when placing order |
> attachAlgoId | String | Conditional | The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely. |
> attachAlgoClOrdId | String | Conditional | Client-supplied Algo ID when placing order attaching TP/SL A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
> newTpTriggerPx | String | Conditional | Take-profit trigger price. Either the take profit trigger price or order price is 0, it means that the take profit is deleted. Only applicable to Expiry Futures and Perpetual Futures. |
> newTpOrdPx | String | Conditional | Take-profit order price If the price is -1, take-profit will be executed at the market price. Only applicable to Expiry Futures and Perpetual Futures. |
> newSlTriggerPx | String | Conditional | Stop-loss trigger price Either the stop loss trigger price or order price is 0, it means that the stop loss is deleted. Only applicable to Expiry Futures and Perpetual Futures. |
> newSlOrdPx | String | Conditional | Stop-loss order price If the price is -1, stop-loss will be executed at the market price. Only applicable to Expiry Futures and Perpetual Futures. |
> newTpTriggerPxType | String | Conditional | Take-profit trigger price typelast : last price index : index price mark : mark priceOnly applicable to FUTURES /SWAP If you want to add the take-profit, this parameter is required |
> newSlTriggerPxType | String | Conditional | Stop-loss trigger price typelast : last price index : index price mark : mark priceOnly applicable to FUTURES /SWAP If you want to add the stop-loss, this parameter is required |
> sz | String | Conditional | New size. Only applicable to TP order of split TPs, and it is required for TP order of split TPs |
> amendPxOnTriggerType | String | No | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"clOrdId":"oktswap6",
"ordId":"12345689",
"reqId":"b12344",
"sCode":"0",
"sMsg":""
},
{
"clOrdId":"oktswap7",
"ordId":"12344",
"reqId":"b12344",
"sCode":"0",
"sMsg":""
}
],
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
code | String | The result code, 0 means success |
msg | String | The error message, empty if the code is 0 |
data | Array of objects | Array of objects contains the response results |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> reqId | String | Client Request ID as assigned by the client for order amendment. |
> sCode | String | The code of the event execution result, 0 means success. |
> sMsg | String | Rejection message if the request is unsuccessful. |
inTime | String | Timestamp at REST gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 The time is recorded after authentication. |
outTime | String | Timestamp at REST gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
GET / Order details
Retrieve order details.
Rate Limit: 60 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
HTTP Request
GET /api/v5/trade/order
Request Example
GET /api/v5/trade/order?ordId=680800019749904384&instId=BTC-USDT
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Retrieve order details by ordId
result = tradeAPI.get_order(
instId="BTC-USDT",
ordId="680800019749904384"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT Only applicable to live instruments |
ordId | String | Conditional | Order ID Either ordId or clOrdId is required, if both are passed, ordId will be used |
clOrdId | String | Conditional | Client Order ID as assigned by the client If the clOrdId is associated with multiple orders, only the latest one will be returned. |
Response Example
{
"code": "0",
"data": [
{
"accFillSz": "0.00192834",
"algoClOrdId": "",
"algoId": "",
"attachAlgoClOrdId": "",
"attachAlgoOrds": [],
"avgPx": "51858",
"cTime": "1708587373361",
"cancelSource": "",
"cancelSourceReason": "",
"category": "normal",
"ccy": "",
"clOrdId": "",
"fee": "-0.00000192834",
"feeCcy": "BTC",
"fillPx": "51858",
"fillSz": "0.00192834",
"fillTime": "1708587373361",
"instId": "BTC-USDT",
"instType": "SPOT",
"isTpLimit": "false",
"lever": "",
"linkedAlgoOrd": {
"algoId": ""
},
"ordId": "680800019749904384",
"ordType": "market",
"pnl": "0",
"posSide": "net",
"px": "",
"pxType": "",
"pxUsd": "",
"pxVol": "",
"quickMgnType": "",
"rebate": "0",
"rebateCcy": "USDT",
"reduceOnly": "false",
"side": "buy",
"slOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "",
"source": "",
"state": "filled",
"stpId": "",
"stpMode": "",
"sz": "100",
"tag": "",
"tdMode": "cash",
"tgtCcy": "quote_ccy",
"tpOrdPx": "",
"tpTriggerPx": "",
"tpTriggerPxType": "",
"tradeId": "744876980",
"uTime": "1708587373362"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument typeSPOT |
instId | String | Instrument ID |
tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currencyOnly applicable to SPOT Market OrdersDefault 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 typemarket : 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 ordermmp : 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 | Return "" if self trade prevention is not applicable |
stpMode | String | Self trade prevention mode Return "" if self trade prevention is not applicable |
lever | String | Leverage, from 0.01 to 125 . Only applicable to MARGIN/FUTURES/SWAP |
attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL. |
tpTriggerPx | String | Take-profit trigger price. |
tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
tpOrdPx | String | Take-profit order price. |
slTriggerPx | String | Stop-loss trigger price. |
slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
slOrdPx | String | Stop-loss order price. |
attachAlgoOrds | Array of object | TP/SL information attached when placing order |
> attachAlgoId | String | The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely. |
> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
> tpTriggerPx | String | Take-profit trigger price. |
> tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
> tpOrdPx | String | Take-profit order price. |
> slTriggerPx | String | Stop-loss trigger price. |
> slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
> slOrdPx | String | Stop-loss order price. |
> sz | String | Size. Only applicable to TP order of split TPs |
> amendPxOnTriggerType | String | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
feeCcy | String | Fee currency |
fee | String | Fee and rebate For spot and margin, it is accumulated fee charged by the platform. It is always negative, e.g. -0.01. For Expiry Futures, Perpetual Futures and Options, it is accumulated fee and rebate |
rebateCcy | String | Rebate currency |
source | String | Order source6 : 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 order25 :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 | Categorynormal twap adl full_liquidation partial_liquidation delivery ddh : Delta dynamic hedge |
reduceOnly | String | Whether the order can only reduce the position size. Valid options: true or false. |
cancelSource | String | Code of the cancellation source. |
cancelSourceReason | String | Reason for the cancellation. |
quickMgnType | String | Quick Margin type, Only applicable to Quick Margin Mode of isolated marginmanual , 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 typeSPOT |
instId | String | No | Instrument ID, e.g. BTC-USDT |
ordType | String | No | Order typemarket : Market order limit : Limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order |
state | String | No | Statelive partially_filled |
after | String | No | Pagination of data to return records earlier than the requested ordId |
before | String | No | Pagination of data to return records newer than the requested ordId |
limit | String | No | Number of results per request. The maximum is 100 . The default is 100 |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"accFillSz": "0",
"avgPx": "",
"cTime": "1618235248028",
"category": "normal",
"ccy": "",
"clOrdId": "",
"fee": "0",
"feeCcy": "BTC",
"fillPx": "",
"fillSz": "0",
"fillTime": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"lever": "5.6",
"ordId": "301835739059335168",
"ordType": "limit",
"pnl": "0",
"posSide": "net",
"px": "59200",
"pxUsd":"",
"pxVol":"",
"pxType":"",
"rebate": "0",
"rebateCcy": "USDT",
"side": "buy",
"attachAlgoClOrdId": "",
"slOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "last",
"attachAlgoOrds": [],
"state": "live",
"stpId": "",
"stpMode": "",
"sz": "1",
"tag": "",
"tgtCcy": "",
"tdMode": "cross",
"source":"",
"tpOrdPx": "",
"tpTriggerPx": "",
"tpTriggerPxType": "last",
"tradeId": "",
"reduceOnly": "false",
"quickMgnType": "",
"algoClOrdId": "",
"algoId": "",
"uTime": "1618235248028"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market OrdersDefault 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 ordermmp : 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 | Statelive 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 priceindex : index pricemark : mark price |
tpOrdPx | String | Take-profit order price. |
slTriggerPx | String | Stop-loss trigger price. |
slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
slOrdPx | String | Stop-loss order price. |
attachAlgoOrds | Array of object | TP/SL information attached when placing order |
> attachAlgoId | String | The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely. |
> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
> tpTriggerPx | String | Take-profit trigger price. |
> tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
> tpOrdPx | String | Take-profit order price. |
> slTriggerPx | String | Stop-loss trigger price. |
> slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
> slOrdPx | String | Stop-loss order price. |
> sz | String | Size. Only applicable to TP order of split TPs |
> amendPxOnTriggerType | String | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
stpId | String | Return "" if self trade prevention is not applicable |
stpMode | String | Self trade prevention mode Return "" if self trade prevention is not applicable |
feeCcy | String | Fee currency |
fee | String | Fee and rebate For spot and margin, it is accumulated fee charged by the platform. It is always negative, e.g. -0.01. For Expiry Futures, Perpetual Futures and Options, it is accumulated fee and rebate |
rebateCcy | String | Rebate currency |
source | String | Order source6 : 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 order25 :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 marginmanual , auto_borrow , auto_repay |
algoClOrdId | String | Client-supplied Algo ID. There will be a value when algo order attaching algoClOrdId is triggered, or it will be "". |
algoId | String | Algo ID. There will be a value when algo order is triggered, or it will be "". |
uTime | String | Update time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
cTime | String | Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
GET / Order history (last 7 days)
Get completed orders which are placed in the last 7 days, including those placed 7 days ago but completed in the last 7 days.
The incomplete orders that have been canceled are only reserved for 2 hours.
Rate Limit: 40 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/orders-history
Request Example
GET /api/v5/trade/orders-history?ordType=post_only,fok,ioc&instType=SPOT
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Get completed SPOT orders which are placed in the last 7 days
# The incomplete orders that have been canceled are only reserved for 2 hours
result = tradeAPI.get_orders_history(
instType="SPOT",
ordType="post_only,fok,ioc"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | yes | Instrument typeSPOT |
instId | String | No | Instrument ID, e.g. BTC-USDT |
ordType | String | No | Order typemarket : market order limit : limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order |
state | String | No | Statecanceled filled mmp_canceled : Order canceled automatically due to Market Maker Protection |
after | String | No | Pagination of data to return records earlier than the requested ordId |
before | String | No | Pagination of data to return records newer than the requested ordId |
begin | String | No | Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
end | String | No | Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
limit | String | No | Number of results per request. The maximum is 100 . The default is 100 |
Response Example
{
"code": "0",
"data": [
{
"accFillSz": "0.00192834",
"algoClOrdId": "",
"algoId": "",
"attachAlgoClOrdId": "",
"attachAlgoOrds": [],
"avgPx": "51858",
"cTime": "1708587373361",
"cancelSource": "",
"cancelSourceReason": "",
"category": "normal",
"ccy": "",
"clOrdId": "",
"fee": "-0.00000192834",
"feeCcy": "BTC",
"fillPx": "51858",
"fillSz": "0.00192834",
"fillTime": "1708587373361",
"instId": "BTC-USDT",
"instType": "SPOT",
"isTpLimit": "false",
"lever": "",
"ordId": "680800019749904384",
"ordType": "market",
"pnl": "0",
"posSide": "",
"px": "",
"pxType": "",
"pxUsd": "",
"pxVol": "",
"quickMgnType": "",
"rebate": "0",
"rebateCcy": "USDT",
"reduceOnly": "false",
"side": "buy",
"slOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "",
"source": "",
"state": "filled",
"stpId": "",
"stpMode": "",
"sz": "100",
"tag": "",
"tdMode": "cash",
"tgtCcy": "quote_ccy",
"tpOrdPx": "",
"tpTriggerPx": "",
"tpTriggerPxType": "",
"tradeId": "744876980",
"uTime": "1708587373362"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market OrdersDefault 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 ordermmp : 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 priceindex : index pricemark : mark price |
tpOrdPx | String | Take-profit order price. |
slTriggerPx | String | Stop-loss trigger price. |
slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
slOrdPx | String | Stop-loss order price. |
attachAlgoOrds | Array of object | TP/SL information attached when placing order |
> attachAlgoId | String | The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely. |
> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
> tpTriggerPx | String | Take-profit trigger price. |
> tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
> tpOrdPx | String | Take-profit order price. |
> slTriggerPx | String | Stop-loss trigger price. |
> slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
> slOrdPx | String | Stop-loss order price. |
> sz | String | Size. Only applicable to TP order of split TPs |
> amendPxOnTriggerType | String | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
stpId | String | Return "" if self trade prevention is not applicable |
stpMode | String | Self trade prevention mode Return "" if self trade prevention is not applicable |
feeCcy | String | Fee currency |
fee | String | Fee and rebate For spot and margin, it is accumulated fee charged by the platform. It is always negative, e.g. -0.01. For Expiry Futures, Perpetual Futures and Options, it is accumulated fee and rebate |
rebateCcy | String | Rebate currency |
source | String | Order source6 : 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 order25 :The normal order triggered by the trailing stop order |
rebate | String | Rebate amount, only applicable to spot and margin, the reward of placing orders from the platform (rebate) given to user who has reached the specified trading level. If there is no rebate, this field is "". |
pnl | String | Profit and loss, Applicable to orders which have a trade and aim to close position. It always is 0 in other conditions |
category | String | Category normal twap adl full_liquidation partial_liquidation delivery ddh : Delta dynamic hedge |
reduceOnly | String | Whether the order can only reduce the position size. Valid options: true or false. |
cancelSource | String | Code of the cancellation source. |
cancelSourceReason | String | Reason for the cancellation. |
algoClOrdId | String | Client-supplied Algo ID. There will be a value when algo order attaching algoClOrdId is triggered, or it will be "". |
algoId | String | Algo ID. There will be a value when algo order is triggered, or it will be "". |
uTime | String | Update time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
cTime | String | Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
Get / Order history (last 3 months)
Retrieve the completed order data of the last 3 months, and the incomplete orders that have been canceled are only reserved for 2 hours.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/orders-history-archive
Request Example
GET /api/v5/trade/orders-history-archive?ordType=post_only,fok,ioc&instType=SPOT
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | yes | Instrument typeSPOT |
instId | String | No | Instrument ID, e.g. BTC-USDT |
ordType | String | No | Order type market : market order limit : limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order |
state | String | No | Statecanceled filled |
category | String | No | Category twap |
after | String | No | Pagination of data to return records earlier than the requested ordId |
before | String | No | Pagination of data to return records newer than the requested ordId |
limit | String | No | Number of results per request. The maximum is 100 ; The default is 100 |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"instType": "SPOT",
"instId": "BTC-USDT",
"ccy": "",
"ordId": "312269865356374016",
"clOrdId": "b1",
"tag": "",
"px": "999",
"sz": "3",
"ordType": "limit",
"side": "buy",
"posSide": "",
"tdMode": "cash",
"accFillSz": "0",
"fillPx": "0",
"tradeId": "0",
"fillSz": "0",
"fillTime": "0",
"state": "filled",
"avgPx": "0",
"lever": "20",
"tpTriggerPx": "",
"tpTriggerPxType": "",
"tpOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "",
"slOrdPx": "",
"feeCcy": "",
"fee": "",
"rebateCcy": "",
"rebate": "",
"tgtCcy":"",
"pnl": "",
"category": "",
"uTime": "1597026383085",
"cTime": "1597026383085"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market OrdersDefault is quote_ccy for buy, base_ccy for sell |
ccy | String | Margin currency |
ordId | String | Order ID |
clOrdId | String | Client Order ID as assigned by the client |
tag | String | Order tag |
px | String | Price |
sz | String | Quantity to buy or sell |
ordType | String | Order type market : market order limit : limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order |
side | String | Order side |
posSide | String | Position side |
tdMode | String | Trade mode |
accFillSz | String | Accumulated fill quantity |
fillPx | String | Last filled price. If none is filled, it will return 0 . |
tradeId | String | Last trade ID |
fillSz | String | Last filled quantity |
fillTime | String | Last filled time |
avgPx | String | Average filled price. If none is filled, it will return "". |
state | String | State canceled filled |
lever | String | Leverage, from 0.01 to 125 |
tpTriggerPx | String | Take-profit trigger price. |
tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
tpOrdPx | String | Take-profit order price. |
slTriggerPx | String | Stop-loss trigger price. |
slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
slOrdPx | String | Stop-loss order price. |
feeCcy | String | Fee currency |
fee | String | Fee |
rebateCcy | String | Rebate currency |
rebate | String | Rebate amount, the reward of placing orders from the platform (rebate) given to user who has reached the specified trading level. If there is no rebate, this field is "". |
pnl | String | Profit and loss |
category | String | Category normal |
uTime | String | Update time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
cTime | String | Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
GET / Transaction details (last 3 days)
Retrieve recently-filled transaction details in the last 3 day.
Rate Limit: 60 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/fills
Request Example
GET /api/v5/trade/fills
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Retrieve recently-filled transaction details
result = tradeAPI.get_fills()
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | No | Instrument typeSPOT |
instId | String | No | Instrument ID, e.g. BTC-USDT |
ordId | String | No | Order ID |
after | String | No | Pagination of data to return records earlier than the requested billId |
before | String | No | Pagination of data to return records newer than the requested billId |
begin | String | No | Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
end | String | No | Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
limit | String | No | Number of results per request. The maximum is 100 ; The default is 100 |
Response Example
{
"code": "0",
"data": [
{
"side": "buy",
"fillSz": "0.00192834",
"fillPx": "51858",
"fillPxVol": "",
"fillFwdPx": "",
"fee": "-0.00000192834",
"fillPnl": "0",
"ordId": "680800019749904384",
"feeRate": "-0.001",
"instType": "SPOT",
"fillPxUsd": "",
"instId": "BTC-USDT",
"clOrdId": "",
"posSide": "net",
"billId": "680800019754098688",
"fillMarkVol": "",
"tag": "",
"fillTime": "1708587373361",
"execType": "T",
"fillIdxPx": "",
"tradeId": "744876980",
"fillMarkPx": "",
"feeCcy": "BTC",
"ts": "1708587373362"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
tradeId | String | Last trade ID |
ordId | String | Order ID |
clOrdId | String | Client Order ID as assigned by the client |
billId | String | Bill ID |
tag | String | Order tag |
fillPx | String | Last filled price |
fillSz | String | Last filled quantity |
fillIdxPx | String | Index price at the moment of trade execution For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT. |
fillPnl | String | Last filled profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions |
fillPxVol | String | Implied volatility when filled Only applicable to options; return "" for other instrument types |
fillPxUsd | String | Options price when filled, in the unit of USD Only applicable to options; return "" for other instrument types |
fillMarkVol | String | Mark volatility when filled Only applicable to options; return "" for other instrument types |
fillFwdPx | String | Forward price when filled Only applicable to options; return "" for other instrument types |
fillMarkPx | String | Mark price when filled Applicable to FUTURES , SWAP , OPTION |
side | String | Order side, buy sell |
posSide | String | Position side long short it returns net innet mode. |
execType | String | Liquidity taker or makerT : takerM : makerNot applicable to system orders such as ADL and liquidation |
feeCcy | String | Trading fee or rebate currency |
fee | String | The amount of trading fee or rebate. The trading fee deduction is negative, such as '-0.01'; the rebate is positive, such as '0.01'. |
ts | String | Data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085 . |
fillTime | String | Trade time which is the same as fillTime for the order channel. |
GET / Transaction details (last 3 months)
Retrieve recently-filled transaction details in the last 3 months.
Rate Limit: 10 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/fills-history
Request Example
GET /api/v5/trade/fills-history
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Retrieve SPOT transaction details in the last 3 months.
result = tradeAPI.get_fills_history(
instType="SPOT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | YES | Instrument typeSPOT |
instId | String | No | Instrument ID, e.g. BTC-USDT |
ordId | String | No | Order ID |
after | String | No | Pagination of data to return records earlier than the requested billId |
before | String | No | Pagination of data to return records newer than the requested billId |
begin | String | No | Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
end | String | No | Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085 |
limit | String | No | Number of results per request. The maximum is 100 ; The default is 100 |
Response Example
{
"code": "0",
"data": [
{
"side": "buy",
"fillSz": "0.00192834",
"fillPx": "51858",
"fillPxVol": "",
"fillFwdPx": "",
"fee": "-0.00000192834",
"fillPnl": "0",
"ordId": "680800019749904384",
"feeRate": "-0.001",
"instType": "SPOT",
"fillPxUsd": "",
"instId": "BTC-USDT",
"clOrdId": "",
"posSide": "net",
"billId": "680800019754098688",
"fillMarkVol": "",
"tag": "",
"fillTime": "1708587373361",
"execType": "T",
"fillIdxPx": "",
"tradeId": "744876980",
"fillMarkPx": "",
"feeCcy": "BTC",
"ts": "1708587373362"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
tradeId | String | Last trade ID |
ordId | String | Order ID |
clOrdId | String | Client Order ID as assigned by the client |
billId | String | Bill ID |
tag | String | Order tag |
fillPx | String | Last filled price |
fillSz | String | Last filled quantity |
fillIdxPx | String | Index price at the moment of trade execution For cross currency spot pairs, it returns baseCcy-USDT index price. For example, for LTC-ETH, this field returns the index price of LTC-USDT. |
fillPnl | String | Last filled profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions |
fillPxVol | String | Implied volatility when filled Only applicable to options; return "" for other instrument types |
fillPxUsd | String | Options price when filled, in the unit of USD Only applicable to options; return "" for other instrument types |
fillMarkVol | String | Mark volatility when filled Only applicable to options; return "" for other instrument types |
fillFwdPx | String | Forward price when filled Only applicable to options; return "" for other instrument types |
fillMarkPx | String | Mark price when filled Applicable to FUTURES , SWAP , OPTION |
side | String | Order sidebuy sell |
posSide | String | Position sidelong short it returns net innet mode. |
execType | String | Liquidity taker or makerT : takerM : makerNot applicable to system orders such as ADL and liquidation |
feeCcy | String | Trading fee or rebate currency |
fee | String | The amount of trading fee or rebate. The trading fee deduction is negative, such as '-0.01'; the rebate is positive, such as '0.01'. |
ts | String | Data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085 . |
fillTime | String | Trade time which is the same as fillTime for the order channel. |
POST / Transaction details (in the past 2 years)
Apply for recently-filled transaction details in the past 2 years except for last 3 months.
Rate Limit: 10 requests per day
Rate limit rule: UserID
Permissions: Read
HTTP Request
POST /api/v5/trade/fills-archive
Request Example
POST /api/v5/trade/fills-archive
body
{
"year":"2023",
"quarter":"Q1"
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
year | String | Yes | 4 digits year |
quarter | String | Yes | Quarter, valid value is Q1 , Q2 , Q3 , Q4 |
Response Example
{
"code": "0",
"data": [
{
"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 download link". 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 / Transaction details (in the past 2 years)
Retrieve recently-filled transaction details in the past 2 years except for last 3 months.
Rate Limit: 10 requests per 2 seconds
Rate limit rule: UserID
Permissions: Read
HTTP Request
GET /api/v5/trade/fills-archive
Request Example
GET /api/v5/trade/fills-archive?year=2023&quarter=Q4
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
year | String | Yes | 4 digits year |
quarter | String | Yes | Quarter, valid value is Q1 , Q2 , Q3 , Q4 |
Response Example
{
"code": "0",
"data": [
{
"fileHref": "http://xxx",
"state": "finished",
"ts": "1646892328000"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
fileHref | String | Download file link |
ts | String | Download link generation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
state | String | Download link status "finished" "ongoing" |
Field descriptions in the decompressed CSV file
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
tradeId | String | Last trade ID |
ordId | String | Order ID |
clOrdId | String | Client Order ID as assigned by the client |
billId | String | Bill ID |
tag | String | Order tag |
fillPx | String | Last filled price |
fillSz | String | Last filled quantity |
side | String | Order side, buy sell |
posSide | String | Position side long short it returns net innet mode. |
execType | String | Liquidity taker or makerT : takerM : makerNot 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 . |
subType | String | Transaction type |
GET / Easy convert currency list
Get list of small convertibles and mainstream currencies. Only applicable to the crypto balance less than $10.
Rate Limit: 1 request per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/easy-convert-currency-list
Request Example
GET /api/v5/trade/easy-convert-currency-list
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Get list of small convertibles and mainstream currencies
result = tradeAPI.get_easy_convert_currency_list()
print(result)
Request Parameters
None
Response Example
{
"code": "0",
"data": [
{
"fromData": [
{
"fromAmt": "6.580712708344864",
"fromCcy": "ADA"
},
{
"fromAmt": "2.9970000013055097",
"fromCcy": "USDC"
}
],
"toCcy": [
"USDT",
"BTC",
"ETH",
"OKB"
]
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
fromData | Array | Currently owned and convertible small currency list |
> fromCcy | String | Type of small payment currency convert from, e.g. BTC |
> fromAmt | String | Amount of small payment currency convert from |
toCcy | Array | Type of mainstream currency convert to, e.g. USDT |
POST / Place easy convert
Convert small currencies to mainstream currencies.
Rate Limit: 1 request per 2 seconds
Rate limit rule: UserID
HTTP Request
POST /api/v5/trade/easy-convert
Request Example
POST /api/v5/trade/easy-convert
body
{
"fromCcy": ["ADA","USDC"], //Seperated by commas
"toCcy": "OKB"
}
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Convert small currencies to mainstream currencies
result = tradeAPI.easy_convert(
fromCcy=["ADA", "USDC"],
toCcy="OKB"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
fromCcy | Array | Yes | Type of small payment currency convert from Maximum 5 currencies can be selected in one order. If there are multiple currencies, separate them with commas. |
toCcy | String | Yes | Type of mainstream currency convert to Only one receiving currency type can be selected in one order and cannot be the same as the small payment currencies. |
Response Example
{
"code": "0",
"data": [
{
"fillFromSz": "6.5807127",
"fillToSz": "0.17171580105126",
"fromCcy": "ADA",
"status": "running",
"toCcy": "OKB",
"uTime": "1661419684687"
},
{
"fillFromSz": "2.997",
"fillToSz": "0.1683755161661844",
"fromCcy": "USDC",
"status": "running",
"toCcy": "OKB",
"uTime": "1661419684687"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
status | String | Current status of easy convert running : Running filled : Filled failed : Failed |
fromCcy | String | Type of small payment currency convert from |
toCcy | String | Type of mainstream currency convert to |
fillFromSz | String | Filled amount of small payment currency convert from |
fillToSz | String | Filled amount of mainstream currency convert to |
uTime | String | Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
GET / Easy convert history
Get the history and status of easy convert trades.
Rate Limit: 1 request per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/easy-convert-history
Request Example
GET /api/v5/trade/easy-convert-history
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Get the history of easy convert trades
result = tradeAPI.get_easy_convert_history()
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
after | String | No | Pagination of data to return records earlier than the requested time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
before | String | No | Pagination of data to return records newer than the requested time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
limit | String | No | Number of results per request. The maximum is 100. The default is 100. |
Response Example
{
"code": "0",
"data": [
{
"fillFromSz": "0.1761712511667539",
"fillToSz": "6.7342205900000000",
"fromCcy": "OKB",
"status": "filled",
"toCcy": "ADA",
"acct": "18",
"uTime": "1661313307979"
},
{
"fillFromSz": "0.1722106121112177",
"fillToSz": "2.9971018300000000",
"fromCcy": "OKB",
"status": "filled",
"toCcy": "USDC",
"acct": "18",
"uTime": "1661313307979"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
fromCcy | String | Type of small payment currency convert from |
fillFromSz | String | Amount of small payment currency convert from |
toCcy | String | Type of mainstream currency convert to |
fillToSz | String | Amount of mainstream currency convert to |
acct | String | 6 : Funding account 18 : Trading account |
status | String | Current status of easy convert running : Running filled : Filled failed : Failed |
uTime | String | Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
POST / Cancel All After
Cancel all pending orders after the countdown timeout. Applicable to all trading symbols through order book (except Spread trading)
Rate Limit: 1 request per second
Rate limit rule: UserID
HTTP Request
POST /api/v5/trade/cancel-all-after
Request Example
POST /api/v5/trade/cancel-all-after
{
"timeOut":"60"
}
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)
# Set cancel all after
result = tradeAPI.cancel_all_after(
timeOut="10"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
timeOut | String | Yes | The countdown for order cancellation, with second as the unit. Range of value can be 0, [10, 120]. Setting timeOut to 0 disables Cancel All After. |
tag | String | No | CAA order tag A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters. |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"triggerTime":"1587971460",
"tag":"",
"ts":"1587971400"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
triggerTime | String | The time the cancellation is triggered. triggerTime=0 means Cancel All After is disabled. |
tag | String | CAA order tag |
ts | String | The time the request is received. |
GET / Account rate limit
Get account rate limit related information.
Only new order requests and amendment order requests will be counted towards this limit. For batch order requests consisting of multiple orders, each order will be counted individually.
For details, please refer to Fill ratio based sub-account rate limit
Rate Limit: 1 request per second
Rate limit rule: UserID
HTTP Requests
GET /api/v5/trade/account-rate-limit
Request Example
# Get the account rate limit
GET /api/v5/trade/account-rate-limit
Request Parameters
None
Response Example
{
"code":"0",
"data":[
{
"accRateLimit":"2000",
"fillRatio":"0.1234",
"mainFillRatio":"0.1234",
"nextAccRateLimit":"2000",
"ts":"123456789000"
}
],
"msg":""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
fillRatio | String | Sub account fill ratio during the monitoring period Applicable for users with trading fee level >= VIP 5 and return "" for others For accounts with no trading volume during the monitoring period, return "0". For accounts with trading volume but no order count due to our counting logic, return "9999". |
mainFillRatio | String | Master account aggregated fill ratio during the monitoring period Applicable for users with trading fee level >= VIP 5 and return "" for others For accounts with no trading volume during the monitoring period, return "0" |
accRateLimit | String | Current sub-account rate limit per two seconds |
nextAccRateLimit | String | Expected sub-account rate limit (per two seconds) in the next period Applicable for users with trading fee level >= VIP 5 and return "" for others |
ts | String | Data update time For users with trading fee level >= VIP 5, the data will be generated at 08:00 am (UTC) For users with trading fee level < VIP 5, return the current timestamp |
WS / Order channel
Retrieve order information. Data will not be pushed when first subscribed. Data will only be pushed when there are order updates.
URL Path
/ws/v5/private (required login)
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "orders",
"instType": "ANY"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel nameorders |
> instType | String | Yes | Instrument typeANY |
> instId | String | No | Instrument ID |
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "orders",
"instType": "ANY"
},
"connId": "a4d3ae55"
}
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "orders",
"instType": "ANY"
},
"connId": "a4d3ae55"
}
Failure Response Example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"orders\", \"instType\" : \"FUTURES\"}]}",
"connId": "a4d3ae55"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel name |
> instType | String | Yes | Instrument typeANY |
> instId | String | No | Instrument ID |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
Push Data Example
{
"arg": {
"channel": "orders",
"instType": "ANY",
"uid": "614488474791936"
},
"data": [
{
"accFillSz": "0.001",
"algoClOrdId": "",
"algoId": "",
"amendResult": "",
"amendSource": "",
"avgPx": "31527.1",
"cancelSource": "",
"category": "normal",
"ccy": "",
"clOrdId": "",
"code": "0",
"cTime": "1654084334977",
"execType": "M",
"fee": "-0.02522168",
"feeCcy": "USDT",
"fillFee": "-0.02522168",
"fillFeeCcy": "USDT",
"fillNotionalUsd": "31.50818374",
"fillPx": "31527.1",
"fillSz": "0.001",
"fillPnl": "0.01",
"fillTime": "1654084353263",
"fillPxVol": "",
"fillPxUsd": "",
"fillMarkVol": "",
"fillFwdPx": "",
"fillMarkPx": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"lever": "0",
"msg": "",
"notionalUsd": "31.50818374",
"ordId": "452197707845865472",
"ordType": "limit",
"pnl": "0",
"posSide": "",
"px": "31527.1",
"pxUsd":"",
"pxVol":"",
"pxType":"",
"quickMgnType": "",
"rebate": "0",
"rebateCcy": "BTC",
"reduceOnly": "false",
"reqId": "",
"side": "sell",
"attachAlgoClOrdId": "",
"slOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "last",
"source": "",
"state": "filled",
"stpId": "",
"stpMode": "",
"sz": "0.001",
"tag": "",
"tdMode": "cash",
"tgtCcy": "",
"tpOrdPx": "",
"tpTriggerPx": "",
"tpTriggerPxType": "last",
"attachAlgoOrds": [],
"tradeId": "242589207",
"lastPx": "38892.2",
"uTime": "1654084353264"
}
]
}
Push data parameters
Parameter | Type | Description |
---|---|---|
arg | Object | Successfully subscribed channel |
> channel | String | Channel name |
> uid | String | User Identifier |
> instType | String | Instrument type |
> instFamily | String | Instrument family |
> instId | String | Instrument ID |
data | Array | Subscribed data |
> instType | String | Instrument type |
> instId | String | Instrument ID |
> tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market orders. Default is quote_ccy for buy, base_ccy for sell |
> ccy | String | Margin currency Only applicable to cross MARGIN orders in 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 | The original order quantity, SPOT /MARGIN , in the unit of currency; FUTURES /SWAP /OPTION , in the unit of contract |
> notionalUsd | String | Estimated national value in USD of order |
> ordType | String | Order type market : market order limit : limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order optimal_limit_ioc : Market order with immediate-or-cancel order (applicable only to Expiry Futures and Perpetual Futures)mmp : Market Maker Protection (only applicable to Option in Portfolio Margin mode)mmp_and_post_only : Market Maker Protection and Post-only order(only applicable to Option in Portfolio Margin mode). op_fok : Simple options (fok) |
> side | String | Order side, buy sell |
> posSide | String | Position side net long or short Only applicable to FUTURES /SWAP |
> tdMode | String | Trade mode, cross : cross isolated : isolated cash : cash |
> fillPx | String | Last filled price |
> tradeId | String | Last trade ID |
> fillSz | String | Last filled quantity The unit is base_ccy for SPOT and MARGIN, e.g. BTC-USDT, the unit is BTC; For market orders, the unit both is base_ccy when the tgtCcy is base_ccy or quote_ccy ;The unit is contract for FUTURES /SWAP /OPTION |
> fillPnl | String | Last filled profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions |
> fillTime | String | Last filled time |
> fillFee | String | last filled fee amount or rebate amount: Negative number represents the user transaction fee charged by the platform; Positive number represents rebate |
> fillFeeCcy | String | last filled fee currency or rebate currency. It is fee currency when fillFee is less than 0; It is rebate currency when fillFee>=0. |
> fillPxVol | String | Implied volatility when filled Only applicable to options; return "" for other instrument types |
> fillPxUsd | String | Options price when filled, in the unit of USD Only applicable to options; return "" for other instrument types |
> fillMarkVol | String | Mark volatility when filled Only applicable to options; return "" for other instrument types |
> fillFwdPx | String | Forward price when filled Only applicable to options; return "" for other instrument types |
> fillMarkPx | String | Mark price when filled Applicable to FUTURES , SWAP , OPTION |
> execType | String | Liquidity taker or maker of the last filled, T: taker M: maker |
> accFillSz | String | Accumulated fill quantity The unit is base_ccy for SPOT and MARGIN, e.g. BTC-USDT, the unit is BTC; For market orders, the unit both is base_ccy when the tgtCcy is base_ccy or quote_ccy ;The unit is contract for FUTURES /SWAP /OPTION |
> fillNotionalUsd | String | Filled notional value in USD of order |
> avgPx | String | Average filled price. If none is filled, it will return 0 . |
> state | String | Order state canceled live partially_filled filled mmp_canceled |
> lever | String | Leverage, from 0.01 to 125 . Only applicable to MARGIN/FUTURES/SWAP |
> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL. |
> tpTriggerPx | String | Take-profit trigger price, it |
> tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
> tpOrdPx | String | Take-profit order price, it |
> slTriggerPx | String | Stop-loss trigger price, it |
> slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
> slOrdPx | String | Stop-loss order price, it |
> attachAlgoOrds | Array of object | TP/SL information attached when placing order |
>> attachAlgoId | String | The order ID of attached TP/SL order. It will not be posted to algoId when placing TP/SL order after the general order is filled completely. |
>> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
>> tpTriggerPx | String | Take-profit trigger price. |
>> tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
>> tpOrdPx | String | Take-profit order price. |
>> slTriggerPx | String | Stop-loss trigger price. |
>> slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
>> slOrdPx | String | Stop-loss order price. |
>> sz | String | Size. Only applicable to TP order of split TPs |
>> amendPxOnTriggerType | String | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
> stpId | String | Return "" if self trade prevention is not applicable |
> stpMode | String | Self trade prevention mode Return "" if self trade prevention is not applicable |
> feeCcy | String | Fee currency SPOT /MARGIN : If you buy, you will receive base currency ; if you sell, you will receive quote currency .FUTURES /SWAP /OPTION What is charged is the margin |
> fee | String | Fee and rebate For spot and margin, it is accumulated fee charged by the platform. It is always negative, e.g. -0.01. For Expiry Futures, Perpetual Futures and Options, it is accumulated fee and rebate |
> rebateCcy | String | Rebate currency, if there is no rebate, this field is "". |
> rebate | String | Rebate accumulated amount, only applicable to spot and margin, the reward of placing orders from the platform (rebate) given to user who has reached the specified trading level. If there is no rebate, this field is "". |
> pnl | String | Profit and loss, applicable to orders which have a trade and aim to close position. It always is 0 in other conditions. For liquidation under cross margin mode, it will include liquidation penalties. |
> source | String | Order source6 : 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 order25 :The normal order triggered by the trailing stop order |
> cancelSource | String | Source of the order cancellation. Valid values and the corresponding meanings are: 0 : Order canceled by system1 : Order canceled by user2 : Order canceled: Pre reduce-only order canceled, due to insufficient margin in user position3 : Order canceled: Risk cancellation was triggered. Pending order was canceled due to insufficient margin ratio and forced-liquidation risk.4 : Order canceled: Borrowings of crypto reached hard cap, order was canceled by system.6 : Order canceled: ADL order cancellation was triggered. Pending order was canceled due to a low margin ratio and forced-liquidation risk. 7 : Order canceled: Futures contract delivery. 9 : Order canceled: Insufficient balance after funding fees deducted. 13 : Order canceled: FOK order was canceled due to incompletely filled.14 : Order canceled: IOC order was partially canceled due to incompletely filled.15 : Order canceled: The order price is beyond the limit17 : Order canceled: Close order was canceled, due to the position was already closed at market price.20 : Cancel all after triggered21 : Order canceled: The TP/SL order was canceled because the position had been closed22 , 23 : Order canceled: Reduce-only orders only allow reducing your current position. System has already canceled this order.27 : Order canceled: Price limit verification failed because the price difference between counterparties exceeds 5% 31 : The post-only order will take liquidity in taker orders 32 : Self trade prevention 33 : The order exceeds the maximum number of order matches per taker order |
> amendSource | String | Source of the order amendation. 1 : Order amended by user2 : Order amended by user, but the order quantity is overriden by system due to reduce-only3 : New order placed by user, but the order quantity is overriden by system due to reduce-only4 : Order amended by system due to other pending orders5 : Order modification due to changes in options px, pxVol, or pxUsd as a result of following variations. For example, when iv = 60, usd and px are anchored at iv = 60, the changes in usd or px lead to modification. |
> category | String | Category normal twap adl full_liquidation partial_liquidation delivery ddh : Delta dynamic hedge |
> uTime | String | Update time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
> cTime | String | Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
> reqId | String | Client Request ID as assigned by the client for order amendment. "" will be returned if there is no order amendment. |
> amendResult | String | The result of amending the order -1 : failure 0 : success 1 : Automatic cancel (amendment request returned success but amendment subsequently failed then automatically canceled by the system) 2 : Automatic amendation successfully, only applicable to pxVol and pxUsd orders of Option.When amending the order through API and cxlOnFail is set to true in the order amendment request but the amendment is rejected, "" is returned. When amending the order through API, the order amendment acknowledgement returns success and the amendment subsequently failed, -1 will be returned if cxlOnFail is set to false , 1 will be returned if cxlOnFail is set to true . When amending the order through Web/APP and the amendment failed, -1 will be returned. |
> reduceOnly | String | Whether the order can only reduce the position size. Valid options: true or false . |
> quickMgnType | String | Quick Margin type, Only applicable to Quick Margin Mode of isolated marginmanual , auto_borrow , auto_repay |
> algoClOrdId | String | Client-supplied Algo ID. There will be a value when algo order attaching algoClOrdId is triggered, or it will be "". |
> algoId | String | Algo ID. There will be a value when algo order is triggered, or it will be "". |
> lastPx | String | Last price |
> code | String | Error Code, the default is 0 |
> msg | String | Error Message, The default is "" |
WS / Place order
You can place an order only if you have sufficient funds.
URL Path
/ws/v5/private (required login)
Rate Limit: 60 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
Request Example
{
"id": "1512",
"op": "order",
"args": [
{
"side": "buy",
"instId": "BTC-USDT",
"tdMode": "cash",
"ordType": "market",
"sz": "100"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
id | String | Yes | Unique identifier of the message Provided by client. It will be returned in response message for identifying the corresponding request. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
op | String | Yes | Operationorder |
args | Array | Yes | Request parameters |
> instId | String | Yes | Instrument ID, e.g. BTC-USDT |
> tdMode | String | Yes | Trade modecash |
> 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 sidebuy sell |
> ordType | String | Yes | Order typemarket : market orderlimit : limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order |
> sz | String | Yes | Quantity to buy or sell. |
> px | String | Conditional | Order price. Only applicable to limit ,post_only ,fok ,ioc ,mmp ,mmp_and_post_only order. |
> tgtCcy | String | No | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market OrdersDefault is quote_ccy for buy, base_ccy for sell |
> banAmend | Boolean | No | Whether to disallow the system from amending the size of the SPOT Market Order. Valid options: true or false . The default value is false .If true , system will not amend and reject the market order if user does not have sufficient funds. Only applicable to SPOT Market Orders |
> stpId | String | No | Numerical integers defined by user in the range of 1<= x<= 999999999 |
> stpMode | String | No | Self trade prevention mode. Default to cancel maker cancel_maker ,cancel_taker , cancel_both Cancel both does not support FOK. |
expTime | String | No | Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085 |
Successful Response Example
{
"id": "1512",
"op": "order",
"data": [
{
"clOrdId": "",
"ordId": "12345689",
"tag": "",
"sCode": "0",
"sMsg": ""
}
],
"code": "0",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Failure Response Example
{
"id": "1512",
"op": "order",
"data": [
{
"clOrdId": "",
"ordId": "",
"tag": "",
"sCode": "5XXXX",
"sMsg": "not exist"
}
],
"code": "1",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When Format Error
{
"id": "1512",
"op": "order",
"data": [],
"code": "60013",
"msg": "Invalid args",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
id | String | Unique identifier of the message |
op | String | Operation |
code | String | Error Code |
msg | String | Error message |
data | Array | Data |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> tag | String | Order tag |
> sCode | String | Order status code, 0 means success |
> sMsg | String | Rejection or success message of event execution. |
inTime | String | Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 |
outTime | String | Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
WS / Place multiple orders
Place orders in a batch. Maximum 20 orders can be placed per request
URL Path
/ws/v5/private (required login)
Rate Limit: 300 orders per 2 seconds
Rate limit rule: UserID + Instrument ID
Request Example
{
"id": "1513",
"op": "batch-orders",
"args": [
{
"side": "buy",
"instId": "BTC-USDT",
"tdMode": "cash",
"ordType": "market",
"sz": "100"
},
{
"side": "buy",
"instId": "LTC-USDT",
"tdMode": "cash",
"ordType": "market",
"sz": "1"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
id | String | Yes | Unique identifier of the message Provided by client. It will be returned in response message for identifying the corresponding request. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
op | String | Yes | Operationbatch-orders |
args | Array | Yes | Request Parameters |
> instId | String | Yes | Instrument ID, e.g. BTC-USDT |
> tdMode | String | Yes | Trade modecash |
> 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 sidebuy sell |
> ordType | String | Yes | Order typemarket : market order limit : limit order post_only : Post-only order fok : Fill-or-kill order ioc : Immediate-or-cancel order |
> sz | String | Yes | Quantity to buy or sell. |
> px | String | Conditional | Order price. Only applicable to limit ,post_only ,fok ,ioc ,mmp ,mmp_and_post_only order. |
> tgtCcy | String | No | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market OrdersDefault is quote_ccy for buy, base_ccy for sell |
> banAmend | Boolean | No | Whether to disallow the system from amending the size of the SPOT Market Order. Valid options: true or false . The default value is false .If true , system will not amend and reject the market order if user does not have sufficient funds. Only applicable to SPOT Market Orders |
> stpId | String | No | Numerical integers defined by user in the range of 1<= x<= 999999999 |
> stpMode | String | No | Self trade prevention mode. Default to cancel maker cancel_maker ,cancel_taker , cancel_both Cancel both does not support FOK. |
expTime | String | No | Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085 |
Response Example When All Succeed
{
"id": "1513",
"op": "batch-orders",
"data": [
{
"clOrdId": "",
"ordId": "12345689",
"tag": "",
"sCode": "0",
"sMsg": ""
},
{
"clOrdId": "",
"ordId": "12344",
"tag": "",
"sCode": "0",
"sMsg": ""
}
],
"code": "0",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When Partially Successful
{
"id": "1513",
"op": "batch-orders",
"data": [
{
"clOrdId": "",
"ordId": "12345689",
"tag": "",
"sCode": "0",
"sMsg": ""
},
{
"clOrdId": "",
"ordId": "",
"tag": "",
"sCode": "5XXXX",
"sMsg": "Insufficient margin"
}
],
"code": "2",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When All Failed
{
"id": "1513",
"op": "batch-orders",
"data": [
{
"clOrdId": "oktswap6",
"ordId": "",
"tag": "",
"sCode": "5XXXX",
"sMsg": "Insufficient margin"
},
{
"clOrdId": "oktswap7",
"ordId": "",
"tag": "",
"sCode": "5XXXX",
"sMsg": "Insufficient margin"
}
],
"code": "1",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When Format Error
{
"id": "1513",
"op": "batch-orders",
"data": [],
"code": "60013",
"msg": "Invalid args",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
id | String | Unique identifier of the message |
op | String | Operation |
code | String | Error Code |
msg | String | Error message |
data | Array | Data |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> tag | String | Order tag |
> sCode | String | Order status code, 0 means success |
> sMsg | String | Rejection or success message of event execution. |
inTime | String | Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 |
outTime | String | Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
WS / Cancel order
Cancel an incomplete order
URL Path
/ws/v5/private (required login)
Rate Limit: 60 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
Request Example
{
"id": "1514",
"op": "cancel-order",
"args": [
{
"instId": "BTC-USDT",
"ordId": "2510789768709120"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
id | String | Yes | Unique identifier of the message Provided by client. It will be returned in response message for identifying the corresponding request. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
op | String | Yes | Operationcancel-order |
args | Array | Yes | Request Parameters |
> instId | String | Yes | Instrument ID |
> ordId | String | Conditional | Order ID Either ordId or clOrdId is required, if both are passed, ordId will be used |
> clOrdId | String | Conditional | Client Order ID as assigned by the client A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
Successful Response Example
{
"id": "1514",
"op": "cancel-order",
"data": [
{
"clOrdId": "",
"ordId": "2510789768709120",
"sCode": "0",
"sMsg": ""
}
],
"code": "0",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Failure Response Example
{
"id": "1514",
"op": "cancel-order",
"data": [
{
"clOrdId": "",
"ordId": "2510789768709120",
"sCode": "5XXXX",
"sMsg": "Order not exist"
}
],
"code": "1",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When Format Error
{
"id": "1514",
"op": "cancel-order",
"data": [],
"code": "60013",
"msg": "Invalid args",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
id | String | Unique identifier of the message |
op | String | Operation |
code | String | Error Code |
msg | String | Error message |
data | Array | Data |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> sCode | String | Order status code, 0 means success |
> sMsg | String | Order status message |
inTime | String | Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 |
outTime | String | Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
WS / Cancel multiple orders
Cancel incomplete orders in batches. Maximum 20 orders can be canceled per request.
URL Path
/ws/v5/private (required login)
Rate Limit: 300 orders per 2 seconds
Rate limit rule: UserID + Instrument ID
Request Example
{
"id": "1515",
"op": "batch-cancel-orders",
"args": [
{
"instId": "BTC-USDT",
"ordId": "2517748157541376"
},
{
"instId": "LTC-USDT",
"ordId": "2517748155771904"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
id | String | Yes | Unique identifier of the message Provided by client. It will be returned in response message for identifying the corresponding request. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
op | String | Yes | Operationbatch-cancel-orders |
args | Array | Yes | Request Parameters |
> instId | String | Yes | Instrument ID |
> ordId | String | Conditional | Order ID Either ordId or clOrdId is required, if both are passed, ordId will be used |
> clOrdId | String | Conditional | Client Order ID as assigned by the client A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
Response Example When All Succeed
{
"id": "1515",
"op": "batch-cancel-orders",
"data": [
{
"clOrdId": "oktswap6",
"ordId": "2517748157541376",
"sCode": "0",
"sMsg": ""
},
{
"clOrdId": "oktswap7",
"ordId": "2517748155771904",
"sCode": "0",
"sMsg": ""
}
],
"code": "0",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When partially successfully
{
"id": "1515",
"op": "batch-cancel-orders",
"data": [
{
"clOrdId": "oktswap6",
"ordId": "2517748157541376",
"sCode": "0",
"sMsg": ""
},
{
"clOrdId": "oktswap7",
"ordId": "2517748155771904",
"sCode": "5XXXX",
"sMsg": "order not exist"
}
],
"code": "2",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When All Failed
{
"id": "1515",
"op": "batch-cancel-orders",
"data": [
{
"clOrdId": "oktswap6",
"ordId": "2517748157541376",
"sCode": "5XXXX",
"sMsg": "order not exist"
},
{
"clOrdId": "oktswap7",
"ordId": "2517748155771904",
"sCode": "5XXXX",
"sMsg": "order not exist"
}
],
"code": "1",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When Format Error
{
"id": "1515",
"op": "batch-cancel-orders",
"data": [],
"code": "60013",
"msg": "Invalid args",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
id | String | Unique identifier of the message |
op | String | Operation |
code | String | Error Code |
msg | String | Error message |
data | Array | Data |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> sCode | String | Order status code, 0 means success |
> sMsg | String | Order status message |
inTime | String | Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 |
outTime | String | Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
WS / Amend order
Amend an incomplete order.
URL Path
/ws/v5/private (required login)
Rate Limit: 60 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
Request Example
{
"id": "1512",
"op": "amend-order",
"args": [
{
"instId": "BTC-USDT",
"ordId": "2510789768709120",
"newSz": "2"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
id | String | Yes | Unique identifier of the message Provided by client. It will be returned in response message for identifying the corresponding request. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
op | String | Yes | Operationamend-order |
args | Array | Yes | Request Parameters |
> instId | String | Yes | Instrument ID |
> cxlOnFail | Boolean | No | Whether the order needs to be automatically canceled when the order amendment fails Valid options: false or true, the default is false. |
> ordId | String | Conditional | Order ID Either ordId or clOrdId is required, if both are passed, ordId will be used. |
> clOrdId | String | Conditional | Client Order ID as assigned by the client |
> reqId | String | No | Client Request ID as assigned by the client for order amendment A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
> newSz | String | Conditional | New quantity after amendment. Either newSz or newPx is required. When amending a partially-filled order, the newSz should include the amount that has been filled. |
> newPx | String | Conditional | New price after amendment. |
expTime | String | No | Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085 |
Successful Response Example
{
"id": "1512",
"op": "amend-order",
"data": [
{
"clOrdId": "",
"ordId": "2510789768709120",
"reqId": "b12344",
"sCode": "0",
"sMsg": ""
}
],
"code": "0",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Failure Response Example
{
"id": "1512",
"op": "amend-order",
"data": [
{
"clOrdId": "",
"ordId": "2510789768709120",
"reqId": "b12344",
"sCode": "5XXXX",
"sMsg": "order not exist"
}
],
"code": "1",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When Format Error
{
"id": "1512",
"op": "amend-order",
"data": [],
"code": "60013",
"msg": "Invalid args",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
id | String | Unique identifier of the message |
op | String | Operation |
code | String | Error Code |
msg | String | Error message |
data | Array | Data |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> reqId | String | Client Request ID as assigned by the client for order amendment |
> sCode | String | Order status code, 0 means success |
> sMsg | String | Order status message |
inTime | String | Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 |
outTime | String | Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
WS / Amend multiple orders
Amend incomplete orders in batches. Maximum 20 orders can be amended per request.
URL Path
/ws/v5/private (required login)
Rate Limit: 300 orders per 2 seconds
Rate limit rule: UserID + Instrument ID
Request Example
{
"id": "1513",
"op": "batch-amend-orders",
"args": [
{
"instId": "BTC-USDT",
"ordId": "12345689",
"newSz": "2"
},
{
"instId": "BTC-USDT",
"ordId": "12344",
"newSz": "2"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
id | String | Yes | Unique identifier of the message Provided by client. It will be returned in response message for identifying the corresponding request. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
op | String | Yes | Operationbatch-amend-orders |
args | Array | Yes | Request Parameters |
> instId | String | Yes | Instrument ID |
> cxlOnFail | Boolean | No | Whether the order needs to be automatically canceled when the order amendment fails Valid options: false or true , the default is false . |
> ordId | String | Conditional | Order ID Either ordId or clOrdId is required, if both are passed, ordId will be used. |
> clOrdId | String | Conditional | Client Order ID as assigned by the client |
> reqId | String | No | Client Request ID as assigned by the client for order amendment A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
> newSz | String | Conditional | New quantity after amendment. Either newSz or newPx is required. When amending a partially-filled order, the newSz should include the amount that has been filled. |
> newPx | String | Conditional | New price after amendment. |
expTime | String | No | Request effective deadline. Unix timestamp format in milliseconds, e.g. 1597026383085 |
Response Example When All Succeed
{
"id": "1513",
"op": "batch-amend-orders",
"data": [
{
"clOrdId": "oktswap6",
"ordId": "12345689",
"reqId": "b12344",
"sCode": "0",
"sMsg": ""
},
{
"clOrdId": "oktswap7",
"ordId": "12344",
"reqId": "b12344",
"sCode": "0",
"sMsg": ""
}
],
"code": "0",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When All Failed
{
"id": "1513",
"op": "batch-amend-orders",
"data": [
{
"clOrdId": "",
"ordId": "12345689",
"reqId": "b12344",
"sCode": "5XXXX",
"sMsg": "order not exist"
},
{
"clOrdId": "oktswap7",
"ordId": "",
"reqId": "b12344",
"sCode": "5XXXX",
"sMsg": "order not exist"
}
],
"code": "1",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When Partially Successful
{
"id": "1513",
"op": "batch-amend-orders",
"data": [
{
"clOrdId": "",
"ordId": "12345689",
"reqId": "b12344",
"sCode": "0",
"sMsg": ""
},
{
"clOrdId": "oktswap7",
"ordId": "",
"reqId": "b12344",
"sCode": "5XXXX",
"sMsg": "order not exist"
}
],
"code": "2",
"msg": "",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Example When Format Error
{
"id": "1513",
"op": "batch-amend-orders",
"data": [],
"code": "60013",
"msg": "Invalid args",
"inTime": "1695190491421339",
"outTime": "1695190491423240"
}
Response Parameters
Parameter | Type | Description |
---|---|---|
id | String | Unique identifier of the message |
op | String | Operation |
code | String | Error Code |
msg | String | Error message |
data | Array | Data |
> ordId | String | Order ID |
> clOrdId | String | Client Order ID as assigned by the client |
> reqId | String | Client Request ID as assigned by the client for order amendment If the user provides reqId in the request, the corresponding reqId will be returned |
> sCode | String | Order status code, 0 means success |
> sMsg | String | Order status message |
inTime | String | Timestamp at Websocket gateway when the request is received, Unix timestamp format in microseconds, e.g. 1597026383085123 |
outTime | String | Timestamp at Websocket gateway when the response is sent, Unix timestamp format in microseconds, e.g. 1597026383085123 |
Algo Trading
POST / Place algo order
The algo order includes trigger
order, oco
order, conditional
order and trailing order.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
HTTP Request
POST /api/v5/trade/order-algo
Request Example
# Place Take Profit / Stop Loss Order
POST /api/v5/trade/order-algo
body
{
"instId":"BTC-USDT",
"tdMode":"cash",
"side":"buy",
"ordType":"conditional",
"sz":"2",
"tpTriggerPx":"15",
"tpOrdPx":"18"
}
# Place Trigger Order
POST /api/v5/trade/order-algo
body
{
"instId": "BTC-USDT",
"tdMode": "cash",
"side": "buy",
"ordType": "trigger",
"sz": "10",
"triggerPx": "100",
"orderPx": "-1"
}
# Place Trailing Stop Order
POST /api/v5/trade/order-algo
body
{
"instId": "BTC-USDT",
"tdMode": "cash",
"side": "buy",
"ordType": "move_order_stop",
"sz": "10",
"callbackRatio": "0.05"
}
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# One-way stop order
result = tradeAPI.place_algo_order(
instId="BTC-USDT",
tdMode="cash",
side="buy",
ordType="conditional",
sz="2",
tpTriggerPx="15",
tpOrdPx="18"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
tdMode | String | Yes | Trade modecash |
side | String | Yes | Order sidebuy sell |
ordType | String | Yes | Order typeconditional : One-way stop orderoco : One-cancels-the-other ordertrigger : Trigger ordermove_order_stop : Trailing order |
sz | String | Yes | Quantity to buy or sell |
tag | String | No | Order tag A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters. |
tgtCcy | String | No | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currencyOnly applicable to SPOT traded with Market buy conditional orderDefault is quote_ccy for buy, base_ccy for sell |
algoClOrdId | String | No | Client-supplied Algo ID A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
Take Profit / Stop Loss Order
learn more about Take Profit / Stop Loss Order
Parameter | Type | Required | Description |
---|---|---|---|
tpTriggerPx | String | No | Take-profit trigger price If you fill in this parameter, you should fill in the take-profit order price as well. |
tpTriggerPxType | String | No | Take-profit trigger price typelast : last priceThe default is last |
tpOrdPx | String | No | Take-profit order price If you fill in this parameter, you should fill in the take-profit trigger price as well. If the price is -1 , take-profit will be executed at the market price. |
slTriggerPx | String | No | Stop-loss trigger price If you fill in this parameter, you should fill in the stop-loss order price. |
slTriggerPxType | String | No | Stop-loss trigger price typelast : last priceThe default is last |
slOrdPx | String | No | Stop-loss order price If you fill in this parameter, you should fill in the stop-loss trigger price. If the price is -1 , stop-loss will be executed at the market price. |
Trigger Order
learn more about Trigger Order
Parameter | Type | Required | Description |
---|---|---|---|
triggerPx | String | Yes | Trigger price |
orderPx | String | Yes | Order Price If the price is -1 , the order will be executed at the market price. |
triggerPxType | String | No | Trigger price typelast : last priceThe default is last |
Trailing Stop Order
learn more about Trailing Stop Order
Parameter | Type | Required | Description |
---|---|---|---|
callbackRatio | String | Conditional | Callback price ratio, e.g. 0.01 represents 1% Either callbackRatio or callbackSpread is allowed to be passed. |
callbackSpread | String | Conditional | Callback price variance |
activePx | String | No | Active price The system will only start tracking the market and calculating your trigger price after the activation price is reached. If you don’t set a price, your order will be activated as soon as it’s placed. |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"algoId": "12345689",
"clOrdId": "",
"algoClOrdId": "",
"sCode": "0",
"sMsg": ""
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
algoId | String | Algo ID |
clOrdId | String | |
algoClOrdId | String | Client-supplied Algo ID |
sCode | String | The code of the event execution result, 0 means success. |
sMsg | String | Rejection message if the request is unsuccessful. |
POST / Cancel algo order
Cancel unfilled algo orders. A maximum of 10 orders can be canceled per request. Request parameters should be passed in the form of an array.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID + instrumentID
HTTP Request
POST /api/v5/trade/cancel-algos
Request Example
POST /api/v5/trade/cancel-algos
body
[
{
"algoId":"198273485",
"instId":"BTC-USDT"
},
{
"algoId":"198273485",
"instId":"BTC-USDT"
}
]
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
algoId | String | Yes | Algo ID |
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"algoId":"1234",
"sCode":"0",
"sMsg":""
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
algoId | String | Order ID |
sCode | String | The code of the event execution result, 0 means success. |
sMsg | String | Rejection message if the request is unsuccessful. |
POST / Cancel advance algo order
This endpoint will be offline soon, please use Cancel algo order
Cancel unfilled algo orders (including Trailing Stop order). A maximum of 10 orders can be canceled per request. Request parameters should be passed in the form of an array.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
HTTP Request
POST /api/v5/trade/cancel-advance-algos
Request Example
POST /api/v5/trade/cancel-advance-algos
body
[
{
"algoId":"590920768125665111",
"instId":"BTC-USDT"
},
{
"algoId":"590920799650058222",
"instId":"BTC-USDT"
}
]
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Cancel unfilled algo orders (including Iceberg order, TWAP order, Trailing Stop order)
algo_orders_advance = [
{"instId": "BTC-USDT", "algoId": "590920768125665111"},
{"instId": "BTC-USDT", "algoId": "590920799650058222"}
]
result = tradeAPI.cancel_advance_algos(algo_orders_advance)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
algoId | String | Yes | Algo ID |
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"algoId":"1234",
"sCode":"0",
"sMsg":""
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
algoId | String | Order ID |
sCode | String | The code of the event execution result, 0 means success. |
sMsg | String | Rejection message if the request is unsuccessful. |
POST / Amend algo order
Amend unfilled algo orders (Support stop order only, not including Move_order_stop order, Trigger order, Iceberg order, TWAP order, Trailing Stop order).
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID + Instrument ID
HTTP Request
POST /api/v5/trade/amend-algos
Request Example
POST /api/v5/trade/amend-algos
body
{
"algoId":"2510789768709120",
"newSz":"2",
"instId":"BTC-USDT-SWAP"
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID |
algoId | String | Conditional | Algo ID Either algoId or algoClOrdId is required. If both are passed, algoId will be used. |
algoClOrdId | String | Conditional | Client-supplied Algo ID Either algoId or algoClOrdId is required. If both are passed, algoId will be used. |
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 . |
reqId | String | Conditional | 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. |
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. |
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 typelast : last price index : index price mark : mark price |
newSlTriggerPxType | String | Conditional | Stop-loss trigger price typelast : last price index : index price mark : mark price |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"algoClOrdId":"algo_01",
"algoId":"2510789768709120",
"reqId":"po103ux",
"sCode":"0",
"sMsg":""
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
algoId | String | Algo ID |
algoClOrdId | String | Client-supplied Algo ID |
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. |
GET / Algo order details
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/order-algo
Request Example
GET /api/v5/trade/order-algo?algoId=681187161907138560
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
algoId | String | Conditional | Algo ID Either algoId or algoClOrdId is required.If both are passed, algoId will be used. |
algoClOrdId | String | Conditional | Client-supplied Algo ID A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
Response Example
{
"code": "0",
"data": [
{
"activePx": "",
"actualPx": "",
"actualSide": "",
"actualSz": "",
"algoClOrdId": "",
"algoId": "681187161907138560",
"amendPxOnTriggerType": "",
"attachAlgoOrds": [],
"cTime": "1708679675244",
"uTime": "1708679675245",
"callbackRatio": "0.05",
"callbackSpread": "",
"ccy": "",
"clOrdId": "",
"closeFraction": "",
"failCode": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"last": "50962.7",
"lever": "",
"linkedOrd": {
"ordId": ""
},
"moveTriggerPx": "53423.160",
"ordId": "",
"ordIdList": [],
"ordPx": "",
"ordType": "move_order_stop",
"posSide": "net",
"pxLimit": "",
"pxSpread": "",
"pxVar": "",
"quickMgnType": "",
"reduceOnly": "false",
"side": "buy",
"slOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "",
"state": "live",
"sz": "10",
"szLimit": "",
"tag": "",
"tdMode": "cash",
"tgtCcy": "",
"timeInterval": "",
"tpOrdPx": "",
"tpTriggerPx": "",
"tpTriggerPxType": "",
"triggerPx": "",
"triggerPxType": "",
"triggerTime": ""
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
ccy | String | Margin currency Only applicable to cross MARGIN orders in Spot and futures mode . |
ordId | String | Latest order ID. It will be deprecated soon |
ordIdList | String | Order ID list. There will be multiple order IDs when there is TP/SL splitting order. |
algoId | String | Algo ID |
clOrdId | String | Client Order ID as assigned by the client |
sz | String | Quantity to buy or sell |
closeFraction | String | Fraction of position to be closed when the algo order is triggered |
ordType | String | Order type |
side | String | Order side |
posSide | String | Position side |
tdMode | String | Trade mode |
tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market OrdersDefault is quote_ccy for buy, base_ccy for sell |
state | String | State live pause partially_effective effective canceled order_failed partially_failed |
lever | String | Leverage, from 0.01 to 125 . Only applicable to MARGIN/FUTURES/SWAP |
tpTriggerPx | String | Take-profit trigger price. |
tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
tpOrdPx | String | Take-profit order price. |
slTriggerPx | String | Stop-loss trigger price. |
slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
slOrdPx | String | Stop-loss order price. |
triggerPx | String | trigger price. |
triggerPxType | String | trigger price type. last : last priceindex : index pricemark : mark price |
ordPx | String | Order price |
actualSz | String | Actual order quantity |
actualPx | String | Actual order price |
tag | String | Order tag |
actualSide | String | Actual trigger side, tp : take profit sl : stop lossOnly applicable to oco order and conditional order |
triggerTime | String | Trigger time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
pxVar | String | Price ratio Only applicable to iceberg order or twap order |
pxSpread | String | Price variance Only applicable to iceberg order or twap order |
szLimit | String | Average amount Only applicable to iceberg order or twap order |
pxLimit | String | Price Limit Only applicable to iceberg order or twap order |
timeInterval | String | Time interval Only applicable to twap order |
callbackRatio | String | Callback price ratio Only applicable to move_order_stop order |
callbackSpread | String | Callback price variance Only applicable to move_order_stop order |
activePx | String | Active price Only applicable to move_order_stop order |
moveTriggerPx | String | Trigger price Only applicable to move_order_stop order |
reduceOnly | String | Whether the order can only reduce the position size. Valid options: true or false. |
quickMgnType | String | Quick Margin type, Only applicable to Quick Margin Mode of isolated marginmanual , auto_borrow , auto_repay |
last | String | Last filled price while placing |
failCode | String | It represents that the reason that algo order fails to trigger. It is "" when the state is effective /canceled . There will be value when the state is order_failed , e.g. 51008;Only applicable to Stop Order, Trailing Stop Order, Trigger order. |
algoClOrdId | String | Client-supplied Algo ID |
amendPxOnTriggerType | String | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
attachAlgoOrds | Array of object | Attached SL/TP orders info Applicable to Spot and futures mode/Multi-currency margin/Portfolio margin |
> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
> tpTriggerPx | String | Take-profit trigger price If you fill in this parameter, you should fill in the take-profit order price as well. |
> tpTriggerPxType | String | Take-profit trigger price typelast : last priceindex : index pricemark : mark price |
> tpOrdPx | String | Take-profit order price If you fill in this parameter, you should fill in the take-profit trigger price as well. If the price is -1 , take-profit will be executed at the market price. |
> slTriggerPx | String | Stop-loss trigger price If you fill in this parameter, you should fill in the stop-loss order price. |
> slTriggerPxType | String | Stop-loss trigger price typelast : last priceindex : index pricemark : mark price |
> slOrdPx | String | Stop-loss order price If you fill in this parameter, you should fill in the stop-loss trigger price. If the price is -1 , stop-loss will be executed at the market price. |
linkedOrd | Object | Linked TP order detail, only applicable to TP limit order of one-cancels-the-other order(oco) |
> ordId | String | Order ID |
cTime | String | Creation time Unix timestamp format in milliseconds, e.g. 1597026383085 |
uTime | String | Order updated time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
GET / Algo order list
Retrieve a list of untriggered Algo orders under the current account.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/orders-algo-pending
Request Example
GET /api/v5/trade/orders-algo-pending?ordType=conditional
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Retrieve a list of untriggered one-way stop orders
result = tradeAPI.order_algos_list(
ordType="conditional"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
ordType | String | Yes | Order typeconditional : One-way stop orderoco : One-cancels-the-other order trigger : Trigger order move_order_stop : Trailing order |
algoId | String | No | Algo ID |
algoClOrdId | String | No | Client-supplied Algo ID A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
instType | String | No | Instrument typeSPOT |
instId | String | No | Instrument ID, e.g. BTC-USDT |
after | String | No | Pagination of data to return records earlier than the requested algoId . |
before | String | No | Pagination of data to return records newer than the requested algoId . |
limit | String | No | Number of results per request. The maximum is 100 . The default is 100 |
Response Example
{
"code": "0",
"data": [
{
"activePx": "",
"actualPx": "",
"actualSide": "buy",
"actualSz": "0",
"algoClOrdId": "",
"algoId": "681096944655273984",
"amendPxOnTriggerType": "",
"attachAlgoOrds": [],
"cTime": "1708658165774",
"callbackRatio": "",
"callbackSpread": "",
"ccy": "",
"clOrdId": "",
"closeFraction": "",
"failCode": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"last": "51014.6",
"lever": "",
"moveTriggerPx": "",
"ordId": "",
"ordIdList": [],
"ordPx": "-1",
"ordType": "trigger",
"posSide": "net",
"pxLimit": "",
"pxSpread": "",
"pxVar": "",
"quickMgnType": "",
"reduceOnly": "false",
"side": "buy",
"slOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "",
"state": "live",
"sz": "10",
"szLimit": "",
"tag": "",
"tdMode": "cash",
"tgtCcy": "",
"timeInterval": "",
"tpOrdPx": "",
"tpTriggerPx": "",
"tpTriggerPxType": "",
"triggerPx": "100",
"triggerPxType": "last",
"triggerTime": "0"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
ccy | String | Margin currency Only applicable to cross MARGIN orders in Spot and futures mode . |
ordId | String | Latest order ID |
ordIdList | String | Order ID list. There will be multiple order IDs when there is TP/SL splitting order. |
algoId | String | Algo ID |
clOrdId | String | Client Order ID as assigned by the client |
sz | String | Quantity to buy or sell |
closeFraction | String | Fraction of position to be closed when the algo order is triggered |
ordType | String | Order type |
side | String | Order side |
posSide | String | Position side |
tdMode | String | Trade mode |
tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT traded with Market order |
state | String | State,live pause |
lever | String | Leverage, from 0.01 to 125 . Only applicable to MARGIN/FUTURES/SWAP |
tpTriggerPx | String | Take-profit trigger price |
tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
tpOrdPx | String | Take-profit order price |
slTriggerPx | String | Stop-loss trigger price |
slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
slOrdPx | String | Stop-loss order price |
triggerPx | String | Trigger price |
triggerPxType | String | Trigger price typelast : last priceindex : index pricemark : mark price |
ordPx | String | Order price |
actualSz | String | Actual order quantity |
tag | String | Order tag |
actualPx | String | Actual order price |
actualSide | String | Actual trigger sidetp : take profit sl : stop lossOnly applicable to oco order and conditional order |
triggerTime | String | Trigger time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
pxVar | String | Price ratio Only applicable to iceberg order or twap order |
pxSpread | String | Price variance Only applicable to iceberg order or twap order |
szLimit | String | Average amount Only applicable to iceberg order or twap order |
pxLimit | String | Price Limit Only applicable to iceberg order or twap order |
timeInterval | String | Time interval Only applicable to twap order |
callbackRatio | String | Callback price ratio Only applicable to move_order_stop order |
callbackSpread | String | Callback price variance Only applicable to move_order_stop order |
activePx | String | Active price Only applicable to move_order_stop order |
moveTriggerPx | String | Trigger price Only applicable to move_order_stop order |
reduceOnly | String | Whether the order can only reduce the position size. Valid options: true or false. |
quickMgnType | String | Quick Margin type, Only applicable to Quick Margin Mode of isolated marginmanual , auto_borrow , auto_repay |
last | String | Last filled price while placing |
failCode | String | It represents that the reason that algo order fails to trigger. There will be value when the state is order_failed , e.g. 51008;For this endpoint, it always is "". |
algoClOrdId | String | Client-supplied Algo ID |
amendPxOnTriggerType | String | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
attachAlgoOrds | Array of object | Attached SL/TP orders info Applicable to Spot and futures mode/Multi-currency margin/Portfolio margin |
> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
> tpTriggerPx | String | Take-profit trigger price If you fill in this parameter, you should fill in the take-profit order price as well. |
> tpTriggerPxType | String | Take-profit trigger price typelast : last priceindex : index pricemark : mark priceThe default is last |
> tpOrdPx | String | Take-profit order price If you fill in this parameter, you should fill in the take-profit trigger price as well. If the price is -1 , take-profit will be executed at the market price. |
> slTriggerPx | String | Stop-loss trigger price If you fill in this parameter, you should fill in the stop-loss order price. |
> slTriggerPxType | String | Stop-loss trigger price typelast : last priceindex : index pricemark : mark price The default is last |
> slOrdPx | String | Stop-loss order price If you fill in this parameter, you should fill in the stop-loss trigger price. If the price is -1 , stop-loss will be executed at the market price. |
cTime | String | Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
GET / Algo order history
Retrieve a list of all algo orders under the current account in the last 3 months.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: UserID
HTTP Request
GET /api/v5/trade/orders-algo-history
Request Example
GET /api/v5/trade/orders-algo-history?algoId=681096944655273984&ordType=trigger
import okx.Trade as Trade
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
tradeAPI = Trade.TradeAPI(apikey, secretkey, passphrase, False, flag)
# Retrieve a list of all one-way stop algo orders
result = tradeAPI.order_algos_history(
state="effective",
ordType="conditional"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
ordType | String | Yes | Order typeconditional : One-way stop orderoco : One-cancels-the-other order trigger : Trigger order move_order_stop : Trailing order |
state | String | Conditional | Stateeffective canceled order_failed Either state or algoId is required |
algoId | String | Conditional | Algo ID Either state or algoId is required. |
instType | String | No | Instrument typeSPOT |
instId | String | No | Instrument ID, e.g. BTC-USDT |
after | String | No | Pagination of data to return records earlier than the requested algoId |
before | String | No | Pagination of data to return records new than the requested algoId |
limit | String | No | Number of results per request. The maximum is 100 . The default is 100 |
Response Example
{
"code": "0",
"data": [
{
"activePx": "",
"actualPx": "",
"actualSide": "buy",
"actualSz": "0",
"algoClOrdId": "",
"algoId": "681096944655273984",
"amendPxOnTriggerType": "",
"attachAlgoOrds": [],
"cTime": "1708658165774",
"callbackRatio": "",
"callbackSpread": "",
"ccy": "",
"clOrdId": "",
"closeFraction": "",
"failCode": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"last": "51014.6",
"lever": "",
"moveTriggerPx": "",
"ordId": "",
"ordIdList": [],
"ordPx": "-1",
"ordType": "trigger",
"posSide": "net",
"pxLimit": "",
"pxSpread": "",
"pxVar": "",
"quickMgnType": "",
"reduceOnly": "false",
"side": "buy",
"slOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "",
"state": "canceled",
"sz": "10",
"szLimit": "",
"tag": "",
"tdMode": "cash",
"tgtCcy": "",
"timeInterval": "",
"tpOrdPx": "",
"tpTriggerPx": "",
"tpTriggerPxType": "",
"triggerPx": "100",
"triggerPxType": "last",
"triggerTime": ""
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
ccy | String | Margin currency Only applicable to cross MARGIN orders in Spot and futures mode . |
ordId | String | Latest order ID |
ordIdList | String | Order ID list. There will be multiple order IDs when there is TP/SL splitting order. |
algoId | String | Algo ID |
clOrdId | String | Client Order ID as assigned by the client |
sz | String | Quantity to buy or sell |
closeFraction | String | Fraction of position to be closed when the algo order is triggered |
ordType | String | Order type |
side | String | Order side |
posSide | String | Position side |
tdMode | String | Trade mode |
tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market OrdersDefault is quote_ccy for buy, base_ccy for sell |
state | String | Stateeffective canceled order_failed partially_failed |
lever | String | Leverage, from 0.01 to 125 . Only applicable to MARGIN/FUTURES/SWAP |
tpTriggerPx | String | Take-profit trigger price. |
tpTriggerPxType | String | Take-profit trigger price type. last : last priceindex : index pricemark : mark price |
tpOrdPx | String | Take-profit order price. |
slTriggerPx | String | Stop-loss trigger price. |
slTriggerPxType | String | Stop-loss trigger price type. last : last priceindex : index pricemark : mark price |
slOrdPx | String | Stop-loss order price. |
triggerPx | String | trigger price. |
triggerPxType | String | trigger price type. last : last priceindex : index pricemark : mark price |
ordPx | String | Order price |
actualSz | String | Actual order quantity |
actualPx | String | Actual order price |
tag | String | Order tag |
actualSide | String | Actual trigger side, tp : take profit sl : stop lossOnly applicable to oco order and conditional order |
triggerTime | String | Trigger time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
pxVar | String | Price ratio Only applicable to iceberg order or twap order |
pxSpread | String | Price variance Only applicable to iceberg order or twap order |
szLimit | String | Average amount Only applicable to iceberg order or twap order |
pxLimit | String | Price Limit Only applicable to iceberg order or twap order |
timeInterval | String | Time interval Only applicable to twap order |
callbackRatio | String | Callback price ratio Only applicable to move_order_stop order |
callbackSpread | String | Callback price variance Only applicable to move_order_stop order |
activePx | String | Active price Only applicable to move_order_stop order |
moveTriggerPx | String | Trigger price Only applicable to move_order_stop order |
reduceOnly | String | Whether the order can only reduce the position size. Valid options: true or false. |
quickMgnType | String | Quick Margin type, Only applicable to Quick Margin Mode of isolated marginmanual , auto_borrow , auto_repay |
last | String | Last filled price while placing |
failCode | String | It represents that the reason that algo order fails to trigger. It is "" when the state is effective /canceled . There will be value when the state is order_failed , e.g. 51008;Only applicable to Stop Order, Trailing Stop Order, Trigger order. |
algoClOrdId | String | Client Algo Order ID as assigned by the client. |
amendPxOnTriggerType | String | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
attachAlgoOrds | Array of object | Attached SL/TP orders info Applicable to Spot and futures mode/Multi-currency margin/Portfolio margin |
> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
> tpTriggerPx | String | Take-profit trigger price If you fill in this parameter, you should fill in the take-profit order price as well. |
> tpTriggerPxType | String | Take-profit trigger price typelast : last priceindex : index pricemark : mark priceThe default is last |
> tpOrdPx | String | Take-profit order price If you fill in this parameter, you should fill in the take-profit trigger price as well. If the price is -1 , take-profit will be executed at the market price. |
> slTriggerPx | String | Stop-loss trigger price If you fill in this parameter, you should fill in the stop-loss order price. |
> slTriggerPxType | String | Stop-loss trigger price typelast : last priceindex : index pricemark : mark price The default is last |
> slOrdPx | String | Stop-loss order price If you fill in this parameter, you should fill in the stop-loss trigger price. If the price is -1 , stop-loss will be executed at the market price. |
cTime | String | Creation time Unix timestamp format in milliseconds, e.g. 1597026383085 |
WS / Algo orders channel
Retrieve algo orders (includes trigger
order, oco
order, conditional
order). Data will not be pushed when first subscribed. Data will only be pushed when there are order updates.
URL Path
/ws/v5/business (required login)
Request Example : single
{
"op": "subscribe",
"args": [
{
"channel": "orders-algo",
"instType": "ANY"
}
]
}
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "orders-algo",
"instType": "ANY"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel nameorders-algo |
> instType | String | Yes | Instrument typeANY |
> instId | String | No | Instrument ID |
Successful Response Example : single
{
"event": "subscribe",
"arg": {
"channel": "orders-algo",
"instType": "ANY"
},
"connId": "a4d3ae55"
}
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "orders-algo",
"instType": "ANY"
},
"connId": "a4d3ae55"
}
Failure Response Example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"orders-algo\", \"instType\" : \"FUTURES\"}]}",
"connId": "a4d3ae55"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel name |
> instType | String | Yes | Instrument typeANY |
> instId | String | No | Instrument ID |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
Push Data Example: single
{
"arg": {
"channel": "orders-algo",
"uid": "77982378738415879",
"instType": "ANY"
},
"data": [{
"actualPx": "0",
"actualSide": "",
"actualSz": "0",
"algoClOrdId": "",
"algoId": "581878926302093312",
"attachAlgoOrds": [],
"amendResult": "",
"cTime": "1685002746818",
"ccy": "",
"clOrdId": "",
"closeFraction": "",
"failCode": "",
"instId": "BTC-USDC",
"instType": "SPOT",
"last": "26174.8",
"lever": "0",
"notionalUsd": "11.0",
"ordId": "",
"ordIdList": [],
"ordPx": "",
"ordType": "conditional",
"posSide": "",
"quickMgnType": "",
"reduceOnly": "false",
"reqId": "",
"side": "buy",
"slOrdPx": "",
"slTriggerPx": "",
"slTriggerPxType": "",
"state": "live",
"sz": "11",
"tag": "",
"tdMode": "cross",
"tgtCcy": "quote_ccy",
"tpOrdPx": "-1",
"tpTriggerPx": "1",
"tpTriggerPxType": "last",
"triggerPx": "",
"triggerTime": "",
"amendPxOnTriggerType": "0"
}]
}
Response parameters when data is pushed.
Parameter | Type | Description |
---|---|---|
arg | Object | Successfully subscribed channel |
> channel | String | Channel name |
> uid | String | User Identifier |
> instType | String | Instrument type |
> instFamily | String | Instrument family |
> instId | String | Instrument ID |
data | Array | Subscribed data |
> instType | String | Instrument type |
> instId | String | Instrument ID |
> ccy | String | Margin currency Only applicable to cross MARGIN orders in Spot and futures mode . |
> ordId | String | Latest order ID, the order ID associated with the algo order. |
> ordIdList | String | Order ID list. There will be multiple order IDs when there is TP/SL splitting order. |
> algoId | String | Algo ID |
> clOrdId | String | Client Order ID as assigned by the client |
> sz | String | Quantity to buy or sell.SPOT /MARGIN : in the unit of currency. FUTURES /SWAP /OPTION : in the unit of contract. |
> ordType | String | Order typeconditional : One-way stop order oco : One-cancels-the-other order trigger : Trigger order |
> side | String | Order sidebuy sell |
> posSide | String | Position sidenet long or short Only applicable to FUTURES /SWAP |
> tdMode | String | Trade modecross : crossisolated : isolatedcash : cash |
> tgtCcy | String | Order quantity unit setting for sz base_ccy : Base currency ,quote_ccy : Quote currency Only applicable to SPOT Market OrdersDefault is quote_ccy for buy, base_ccy for sell |
> lever | String | Leverage, from 0.01 to 125 . Only applicable to MARGIN/FUTURES/SWAP |
> state | String | Order statuslive : to be effective effective : effective canceled : canceled order_failed : order failedpartially_failed : partially failed |
> tpTriggerPx | String | Take-profit trigger price. |
> tpTriggerPxType | String | Take-profit trigger price typelast : last priceindex : index pricemark : mark price |
> tpOrdPx | String | Take-profit order price. |
> slTriggerPx | String | Stop-loss trigger price. |
> slTriggerPxType | String | Stop-loss trigger price typelast : last priceindex : index pricemark : mark price |
> slOrdPx | String | Stop-loss order price. |
> triggerPx | String | Trigger price |
> triggerPxType | String | Trigger price type. last : last priceindex : index pricemark : mark price |
> ordPx | String | Order price |
> last | String | Last filled price while placing |
> actualSz | String | Actual order quantity |
> actualPx | String | Actual order price |
> notionalUsd | String | Estimated national value in USD of order |
> tag | String | Order tag |
> actualSide | String | Actual trigger side Only applicable to oco order and conditional order |
> triggerTime | String | Trigger time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
> reduceOnly | String | Whether the order can only reduce the position size. Valid options: true or false . |
> failCode | String | It represents that the reason that algo order fails to trigger. It is "" when the state is effective /canceled . There will be value when the state is order_failed , e.g. 51008;Only applicable to Stop Order, Trailing Stop Order, Trigger order. |
> algoClOrdId | String | Client Algo Order ID as assigned by the client. |
> cTime | String | Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
> reqId | String | Client Request ID as assigned by the client for order amendment. "" will be returned if there is no order amendment. |
> amendResult | String | The result of amending the order-1 : failure 0 : success |
> amendPxOnTriggerType | String | Whether to enable Cost-price SL. Only applicable to SL order of split TPs. 0 : disable, the default value 1 : Enable |
> attachAlgoOrds | Array of object | Attached SL/TP orders info Applicable to Spot and futures mode/Multi-currency margin/Portfolio margin |
>> attachAlgoClOrdId | String | Client-supplied Algo ID when placing order attaching TP/SL. A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. It will be posted to algoClOrdId when placing TP/SL order once the general order is filled completely. |
>> tpTriggerPx | String | Take-profit trigger price If you fill in this parameter, you should fill in the take-profit order price as well. |
>> tpTriggerPxType | String | Take-profit trigger price typelast : last priceindex : index pricemark : mark priceThe default is last |
>> tpOrdPx | String | Take-profit order price If you fill in this parameter, you should fill in the take-profit trigger price as well. If the price is -1 , take-profit will be executed at the market price. |
>> slTriggerPx | String | Stop-loss trigger price If you fill in this parameter, you should fill in the stop-loss order price. |
>> slTriggerPxType | String | Stop-loss trigger price typelast : last priceindex : index pricemark : mark price The default is last |
>> slOrdPx | String | Stop-loss order price If you fill in this parameter, you should fill in the stop-loss trigger price. If the price is -1 , stop-loss will be executed at the market price. |
Market Data
The API endpoints of Market Data
do not require authentication.
GET / Tickers
Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/tickers
Request Example
GET /api/v5/market/tickers?instType=SPOT
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours
result = marketDataAPI.get_tickers(
instType="SPOT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | Yes | Instrument typeSPOT |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"instType": "SPOT",
"instId": "BTC-USDT",
"last": "51230",
"lastSz": "0.18531491",
"askPx": "51229.4",
"askSz": "2.1683067",
"bidPx": "51229.3",
"bidSz": "0.28249897",
"open24h": "51635.7",
"high24h": "52080",
"low24h": "50936",
"volCcy24h": "539658490.410419122",
"vol24h": "10476.2229261",
"ts": "1708669508505",
"sodUtc0": "51290.1",
"sodUtc8": "51602.4"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
last | String | Last traded price |
lastSz | String | Last traded size |
askPx | String | Best ask price |
askSz | String | Best ask size |
bidPx | String | Best bid price |
bidSz | String | Best bid size |
open24h | String | Open price in the past 24 hours |
high24h | String | Highest price in the past 24 hours |
low24h | String | Lowest price in the past 24 hours |
volCcy24h | String | 24h trading volume If it is SPOT , the value is the quantity in quote currency. |
vol24h | String | 24h trading volume If it is SPOT , the value is the quantity in base currency. |
sodUtc0 | String | Open price in the UTC 0 |
sodUtc8 | String | Open price in the UTC 8 |
ts | String | Ticker data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
GET / Ticker
Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/ticker
Request Example
GET /api/v5/market/ticker?instId=BTC-USDT
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours
result = marketDataAPI.get_ticker(
instId="BTC-USDT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"instType": "SPOT",
"instId": "BTC-USDT",
"last": "51240",
"lastSz": "0.49011124",
"askPx": "51240",
"askSz": "0.64278176",
"bidPx": "51239.9",
"bidSz": "1.68139044",
"open24h": "51695.6",
"high24h": "52080",
"low24h": "50936",
"volCcy24h": "539533972.680195094",
"vol24h": "10474.12353007",
"ts": "1708669925904",
"sodUtc0": "51290.1",
"sodUtc8": "51602.4"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID |
last | String | Last traded price |
lastSz | String | Last traded size |
askPx | String | Best ask price |
askSz | String | Best ask size |
bidPx | String | Best bid price |
bidSz | String | Best bid size |
open24h | String | Open price in the past 24 hours |
high24h | String | Highest price in the past 24 hours |
low24h | String | Lowest price in the past 24 hours |
volCcy24h | String | 24h trading volume If it is SPOT , the value is the quantity in quote currency. |
vol24h | String | 24h trading volume If it is SPOT , the value is the quantity in base currency. |
sodUtc0 | String | Open price in the UTC 0 |
sodUtc8 | String | Open price in the UTC 8 |
ts | String | Ticker data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085 . |
GET / Order book
Retrieve order book of the instrument.
Rate Limit: 40 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/books
Request Example
GET /api/v5/market/books?instId=BTC-USDT
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve order book of the instrument
result = marketDataAPI.get_orderbook(
instId="BTC-USDT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
sz | String | No | Order book depth per side. Maximum 400, e.g. 400 bids + 400 asks Default returns to 1 depth data |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"asks": [
[
"41006.8",
"0.60038921",
"0",
"1"
]
],
"bids": [
[
"41006.3",
"0.30178218",
"0",
"2"
]
],
"ts": "1629966436396"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
asks | Array | Order book on sell side |
bids | Array | Order book on buy side |
ts | String | Order book generation time |
GET / Candlesticks
Retrieve the candlestick charts. This endpoint can retrieve the latest 1,440 data entries. Charts are returned in groups based on the requested bar.
Rate Limit: 40 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/candles
Request Example
GET /api/v5/market/candles?instId=BTC-USDT
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve the candlestick charts
result = marketDataAPI.get_candlesticks(
instId="BTC-USDT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
bar | String | No | Bar size, the default is 1m e.g. [1m/3m/5m/15m/30m/1H/2H/4H] Hong Kong time opening price k-line: [6H/12H/1D/2D/3D/1W/1M/3M] UTC time opening price k-line: [/6Hutc/12Hutc/1Dutc/2Dutc/3Dutc/1Wutc/1Mutc/3Mutc] |
after | String | No | Pagination of data to return records earlier than the requested ts |
before | String | No | Pagination of data to return records newer than the requested ts . The latest data will be returned when using before individually |
limit | String | No | Number of results per request. The maximum is 300 . The default is 100 . |
Response Example
{
"code":"0",
"msg":"",
"data":[
[
"1597026383085",
"3.721",
"3.743",
"3.677",
"3.708",
"8422410",
"22698348.04828491",
"12698348.04828491",
"0"
],
[
"1597026383085",
"3.731",
"3.799",
"3.494",
"3.72",
"24912403",
"67632347.24399722",
"37632347.24399722",
"1"
]
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
ts | String | Opening time of the candlestick, Unix timestamp format in milliseconds, e.g. 1597026383085 |
o | String | Open price |
h | String | highest price |
l | String | Lowest price |
c | String | Close price |
vol | String | Trading volume If it is SPOT , the value is the quantity in base currency. |
volCcy | String | Trading volume If it is SPOT , the value is the quantity in quote currency. |
volCcyQuote | String | Trading volume, the value is the quantity in quote currency e.g. The unit is USDT for BTC-USDT |
confirm | String | The state of candlesticks.0 : K line is uncompleted1 : K line is completed |
GET / Candlesticks history
Retrieve history candlestick charts from recent years(It is last 3 months supported for 1s candlestick).
Rate Limit: 20 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/history-candles
Request Example
GET /api/v5/market/history-candles?instId=BTC-USDT
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve history candlestick charts from recent years
result = marketDataAPI.get_history_candlesticks(
instId="BTC-USDT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
after | String | No | Pagination of data to return records earlier than the requested ts |
before | String | No | Pagination of data to return records newer than the requested ts . The latest data will be returned when using before individually |
bar | String | No | Bar size, the default is 1m e.g. [1s/1m/3m/5m/15m/30m/1H/2H/4H] Hong Kong time opening price k-line: [6H/12H/1D/2D/3D/1W/1M/3M] UTC time opening price k-line: [6Hutc/12Hutc/1Dutc/2Dutc/3Dutc/1Wutc/1Mutc/3Mutc] |
limit | String | No | Number of results per request. The maximum is 100 . The default is 100 . |
Response Example
{
"code":"0",
"msg":"",
"data":[
[
"1597026383085",
"3.721",
"3.743",
"3.677",
"3.708",
"8422410",
"22698348.04828491",
"12698348.04828491",
"1"
],
[
"1597026383085",
"3.731",
"3.799",
"3.494",
"3.72",
"24912403",
"67632347.24399722",
"37632347.24399722",
"1"
]
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
ts | String | Opening time of the candlestick, Unix timestamp format in milliseconds, e.g. 1597026383085 |
o | String | Open price |
h | String | Highest price |
l | String | Lowest price |
c | String | Close price |
vol | String | Trading volume If it is SPOT , the value is the quantity in base currency. |
volCcy | String | Trading volume If it is SPOT , the value is the quantity in quote currency. |
volCcyQuote | String | Trading volume, the value is the quantity in quote currency e.g. The unit is USDT for BTC-USDT |
confirm | String | The state of candlesticks.0 : K line is uncompleted1 : K line is completed |
GET / Trades
Retrieve the recent transactions of an instrument.
Rate Limit: 100 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/trades
Request Example
GET /api/v5/market/trades?instId=BTC-USDT
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve the recent transactions of an instrument
result = marketDataAPI.get_trades(
instId="BTC-USDT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
limit | String | No | Number of results per request. The maximum is 500 ; The default is 100 |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"instId": "BTC-USDT",
"side": "sell",
"sz": "0.00001",
"px": "29963.2",
"tradeId": "242720720",
"ts": "1654161646974"
},
{
"instId": "BTC-USDT",
"side": "sell",
"sz": "0.00001",
"px": "29964.1",
"tradeId": "242720719",
"ts": "1654161641568"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instId | String | Instrument ID |
tradeId | String | Trade ID |
px | String | Trade price |
sz | String | Trade quantity For spot trading, the unit is base currency |
side | String | Trade side buy sell |
ts | String | Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085 . |
GET / Trades history
Retrieve the recent transactions of an instrument from the last 3 months with pagination.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/history-trades
Request Example
GET /api/v5/market/history-trades?instId=BTC-USDT
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve the recent transactions of an instrument from the last 3 months with pagination
result = marketDataAPI.get_history_trades(
instId="BTC-USD-SWAP"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instId | String | Yes | Instrument ID, e.g. BTC-USDT |
type | String | No | Pagination Type 1 : tradeId 2 : timestampThe default is 1 |
after | String | No | Pagination of data to return records earlier than the requested tradeId or ts. |
before | String | No | Pagination of data to return records newer than the requested tradeId. Do not support timestamp for pagination. The latest data will be returned when using before individually |
limit | String | No | Number of results per request. The maximum and default both are 100 |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"instId": "BTC-USDT",
"side": "sell",
"sz": "0.00001",
"px": "29963.2",
"tradeId": "242720720",
"ts": "1654161646974"
},
{
"instId": "BTC-USDT",
"side": "sell",
"sz": "0.00001",
"px": "29964.1",
"tradeId": "242720719",
"ts": "1654161641568"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instId | String | Instrument ID |
tradeId | String | Trade ID |
px | String | Trade price |
sz | String | Trade quantity |
side | String | Trade side buy sell |
ts | String | Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085 . |
GET / 24H total volume
The 24-hour trading volume is calculated on a rolling basis.
Rate Limit: 2 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/platform-24-volume
Request Example
GET /api/v5/market/platform-24-volume
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve 24 total volume
result = marketDataAPI.get_volume()
print(result)
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"volCny": "230900886396766",
"volUsd": "34462818865189",
"ts": "1657856040389"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
volUsd | String | 24-hour total trading volume from the order book trading in "USD" |
volCny | String | 24-hour total trading volume from the order book trading in "CNY" |
ts | String | Data return time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
WS / Tickers channel
Retrieve the last traded price, bid price, ask price and 24-hour trading volume of instruments.
The fastest rate is 1 update/100ms. There will be no update if the event is not triggered. The events which can trigger update: trade, the change on best ask/bid.
URL Path
/ws/v5/public
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "tickers",
"instId": "BTC-USDT"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel nametickers |
> instId | String | Yes | Instrument ID |
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "tickers",
"instId": "BTC-USDT"
},
"connId": "a4d3ae55"
}
Failure Response Example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"tickers\", \"instId\" : \"LTC-USD-200327\"}]}",
"connId": "a4d3ae55"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel name |
> instId | String | Yes | Instrument ID |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
Push Data Example
{
"arg": {
"channel": "tickers",
"instId": "BTC-USDT"
},
"data": [
{
"instType": "SPOT",
"instId": "BTC-USDT",
"last": "9999.99",
"lastSz": "0.1",
"askPx": "9999.99",
"askSz": "11",
"bidPx": "8888.88",
"bidSz": "5",
"open24h": "9000",
"high24h": "10000",
"low24h": "8888.88",
"volCcy24h": "2222",
"vol24h": "2222",
"sodUtc0": "2222",
"sodUtc8": "2222",
"ts": "1597026383085"
}
]
}
Push data parameters
Parameter | Type | Description |
---|---|---|
arg | Object | Successfully subscribed channel |
> channel | String | Channel name |
> instId | String | Instrument ID |
data | Array | Subscribed data |
> instType | String | Instrument type |
> instId | String | Instrument ID |
> last | String | Last traded price |
> lastSz | String | Last traded size |
> askPx | String | Best ask price |
> askSz | String | Best ask size |
> bidPx | String | Best bid price |
> bidSz | String | Best bid size |
> open24h | String | Open price in the past 24 hours |
> high24h | String | Highest price in the past 24 hours |
> low24h | String | Lowest price in the past 24 hours |
> volCcy24h | String | 24h trading volume If it is SPOT , the value is the quantity in quote currency. |
> vol24h | String | 24h trading volume If it is SPOT , the value is the quantity in base currency. |
> sodUtc0 | String | Open price in the UTC 0 |
> sodUtc8 | String | Open price in the UTC 8 |
> ts | String | Ticker data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
WS / Candlesticks channel
Retrieve the candlesticks data of an instrument. the push frequency is the fastest interval 1 second push the data.
URL Path
/ws/v5/business
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "candle1D",
"instId": "BTC-USDT"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel namecandle3M candle1M candle1W candle1D candle2D candle3D candle5D candle12H candle6H candle4H candle2H candle1H candle30m candle15m candle5m candle3m candle1m candle1s candle3Mutc candle1Mutc candle1Wutc candle1Dutc candle2Dutc candle3Dutc candle5Dutc candle12Hutc candle6Hutc |
> instId | String | Yes | Instrument ID |
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "candle1D",
"instId": "BTC-USDT"
},
"connId": "a4d3ae55"
}
Failure Response Example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"candle1D\", \"instId\" : \"BTC-USD-191227\"}]}",
"connId": "a4d3ae55"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | yes | channel name |
> instId | String | Yes | Instrument ID |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
Push Data Example
{
"arg": {
"channel": "candle1D",
"instId": "BTC-USDT"
},
"data": [
[
"1597026383085",
"8533.02",
"8553.74",
"8527.17",
"8548.26",
"45247",
"529.5858061",
"5529.5858061",
"0"
]
]
}
Push data parameters
Parameter | Type | Description |
---|---|---|
arg | Object | Successfully subscribed channel |
> channel | String | Channel name |
> instId | String | Instrument ID |
data | Array | Subscribed data |
> ts | String | Opening time of the candlestick, Unix timestamp format in milliseconds, e.g. 1597026383085 |
> o | String | Open price |
> h | String | highest price |
> l | String | Lowest price |
> c | String | Close price |
> vol | String | Trading volume If it is SPOT , the value is the quantity in base currency. |
> volCcy | String | Trading volume If it is SPOT , the value is the quantity in quote currency. |
> volCcyQuote | String | Trading volume, the value is the quantity in quote currency e.g. The unit is USDT for BTC-USDT |
> confirm | String | The state of candlesticks0 : K line is uncompleted1 : K line is completed |
WS / Trades channel
Retrieve the recent trades data. Data will be pushed whenever there is a trade. Every update may aggregate multiple trades.
The message is sent only once per taker order, per filled price. The count field is used to represent the number of aggregated matches.
URL Path
/ws/v5/public
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "trades",
"instId": "BTC-USDT"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel nametrades |
> instId | String | Yes | Instrument ID |
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "trades",
"instId": "BTC-USDT"
},
"connId": "a4d3ae55"
}
Failure Response Example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"trades\", \"instId\" : \"BTC-USD-191227\"}]}",
"connId": "a4d3ae55"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel name |
> instId | String | Yes | Instrument ID |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
Push Data Example
{
"arg": {
"channel": "trades",
"instId": "BTC-USDT"
},
"data": [
{
"instId": "BTC-USDT",
"tradeId": "130639474",
"px": "42219.9",
"sz": "0.12060306",
"side": "buy",
"ts": "1630048897897",
"count": "3"
}
]
}
Push data parameters
Parameter | Type | Description |
---|---|---|
arg | Object | Successfully subscribed channel |
> channel | String | Channel name |
> instId | String | Instrument ID |
data | Array | Subscribed data |
> instId | String | Instrument ID, e.g. BTC-USDT |
> tradeId | String | The last trade ID in the trades aggregation |
> px | String | Trade price |
> sz | String | Trade size |
> side | String | Trade directionbuy sell |
> ts | String | Filled time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
> count | String | The count of trades aggregated |
WS / All trades channel
Retrieve the recent trades data. Data will be pushed whenever there is a trade. Every update contain only one trade.
URL Path
/ws/v5/business
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "trades-all",
"instId": "BTC-USDT"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel nametrades-all |
> instId | String | Yes | Instrument ID |
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "trades-all",
"instId": "BTC-USDT"
},
"connId": "a4d3ae55"
}
Failure Response Example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"trades-all\", \"instId\" : \"BTC-USD-191227\"}]}",
"connId": "a4d3ae55"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel name |
> instId | String | Yes | Instrument ID |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
Push Data Example
{
"arg": {
"channel": "trades-all",
"instId": "BTC-USDT"
},
"data": [
{
"instId": "BTC-USDT",
"tradeId": "130639474",
"px": "42219.9",
"sz": "0.12060306",
"side": "buy",
"ts": "1630048897897"
}
]
}
Push data parameters
Parameter | Type | Description |
---|---|---|
arg | Object | Successfully subscribed channel |
> channel | String | Channel name |
> instId | String | Instrument ID |
data | Array | Subscribed data |
> instId | String | Instrument ID, e.g. BTC-USDT |
> tradeId | String | Trade ID |
> px | String | Trade price |
> sz | String | Trade size |
> side | String | Trade directionbuy sell |
> ts | String | Filled time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
WS / Order book channel
Retrieve order book data.
Use books
for 400 depth levels, books5
for 5 depth levels, bbo-tbt
tick-by-tick 1 depth level, books50-l2-tbt
tick-by-tick 50 depth levels, and books-l2-tbt
for tick-by-tick 400 depth levels.
books
: 400 depth levels will be pushed in the initial full snapshot. Incremental data will be pushed every 100 ms for the changes in the order book during that period of time.books5
: 5 depth levels snapshot will be pushed every time. Snapshot data will be pushed every 100 ms when there are changes in the 5 depth levels snapshot.bbo-tbt
: 1 depth level snapshot will be pushed every time. Snapshot data will be pushed every 10 ms when there are changes in the 1 depth level snapshot.books-l2-tbt
: 400 depth levels will be pushed in the initial full snapshot. Incremental data will be pushed every 10 ms for the changes in the order book during that period of time.books50-l2-tbt
: 50 depth levels will be pushed in the initial full snapshot. Incremental data will be pushed every 10 ms for the changes in the order book during that period of time.- The push sequence for order book channels within the same connection and trading symbols is fixed as: bbo-tbt -> books-l2-tbt -> books50-l2-tbt -> books -> books5.
- Users can not simultaneously subscribe to
books-l2-tbt
andbooks50-l2-tbt/books
channels for the same trading symbol.- For more details, please refer to the changelog 2024-07-17
Identity verification refers to Login
URL Path
/ws/v5/public
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "books",
"instId": "BTC-USDT"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel namebooks books5 books50-l2-tbt books-l2-tbt |
> instId | String | Yes | Instrument ID |
Response Example
{
"event": "subscribe",
"arg": {
"channel": "books",
"instId": "BTC-USDT"
},
"connId": "a4d3ae55"
}
Failure example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"books\", \"instId\" : \"BTC-USD-191227\"}]}",
"connId": "a4d3ae55"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel name |
> instId | String | Yes | Instrument ID |
msg | String | No | Error message |
code | String | No | Error code |
connId | String | Yes | WebSocket connection ID |
Push Data Example: Full Snapshot
{
"arg": {
"channel": "books",
"instId": "BTC-USDT"
},
"action": "snapshot",
"data": [
{
"asks": [
["8476.98", "415", "0", "13"],
["8477", "7", "0", "2"],
["8477.34", "85", "0", "1"],
["8477.56", "1", "0", "1"],
["8505.84", "8", "0", "1"],
["8506.37", "85", "0", "1"],
["8506.49", "2", "0", "1"],
["8506.96", "100", "0", "2"]
],
"bids": [
["8476.97", "256", "0", "12"],
["8475.55", "101", "0", "1"],
["8475.54", "100", "0", "1"],
["8475.3", "1", "0", "1"],
["8447.32", "6", "0", "1"],
["8447.02", "246", "0", "1"],
["8446.83", "24", "0", "1"],
["8446", "95", "0", "3"]
],
"ts": "1597026383085",
"checksum": -855196043,
"prevSeqId": -1,
"seqId": 123456
}
]
}
Push Data Example: Incremental Data
{
"arg": {
"channel": "books",
"instId": "BTC-USDT"
},
"action": "update",
"data": [
{
"asks": [
["8476.98", "415", "0", "13"],
["8477", "7", "0", "2"],
["8477.34", "85", "0", "1"],
["8477.56", "1", "0", "1"],
["8505.84", "8", "0", "1"],
["8506.37", "85", "0", "1"],
["8506.49", "2", "0", "1"],
["8506.96", "100", "0", "2"]
],
"bids": [
["8476.97", "256", "0", "12"],
["8475.55", "101", "0", "1"],
["8475.54", "100", "0", "1"],
["8475.3", "1", "0", "1"],
["8447.32", "6", "0", "1"],
["8447.02", "246", "0", "1"],
["8446.83", "24", "0", "1"],
["8446", "95", "0", "3"]
],
"ts": "1597026383085",
"checksum": -855196043,
"prevSeqId": 123456,
"seqId": 123457
}
]
}
Push data parameters
Parameter | Type | Description |
---|---|---|
arg | Object | Successfully subscribed channel |
> channel | String | Channel name |
> instId | String | Instrument ID |
action | String | Push data action, incremental data or full snapshot. snapshot : full update : incremental |
data | Array | Subscribed data |
> asks | Array | Order book on sell side |
> bids | Array | Order book on buy side |
> ts | String | Order book generation time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
> checksum | Integer | Checksum, implementation details below |
> prevSeqId | Integer | Sequence ID of the last sent message. Only applicable to books , books-l2-tbt , books50-l2-tbt |
> seqId | Integer | Sequence ID of the current message, implementation details below |
Sequence ID
seqId
is the sequence ID of the market data published. The set of sequence ID received by users is the same if users are connecting to the same channel through multiple websocket connections. Each instId
has an unique set of sequence ID. Users can use prevSeqId
and seqId
to build the message sequencing for incremental order book updates. Generally the value of seqId is larger than prevSeqId. The prevSeqId
in the new message matches with seqId
of the previous message. The smallest possible sequence ID value is 0, except in snapshot messages where the prevSeqId is always -1.
Exceptions:
1. If there are no updates to the depth for an extended period, OKX will send a message with 'asks': [], 'bids': []
to inform users that the connection is still active. seqId
is the same as the last sent message and prevSeqId
equals to seqId
.
2. The sequence number may be reset due to maintenance, and in this case, users will receive an incremental message with seqId
smaller than prevSeqId
. However, subsequent messages will follow the regular sequencing rule.
Example
- Snapshot message: prevSeqId = -1, seqId = 10
- Incremental message 1 (normal update): prevSeqId = 10, seqId = 15
- Incremental message 2 (no update): prevSeqId = 15, seqId = 15
- Incremental message 3 (sequence reset): prevSeqId = 15, seqId = 3
- Incremental message 4 (normal update): prevSeqId = 3, seqId = 5
Checksum
This mechanism can assist users in checking the accuracy of depth data.
Merging incremental data into full data
After subscribing to the incremental load push (such as books
400 levels) of Order Book Channel, users first receive the initial full load of market depth. After the incremental load is subsequently received, update the local full load.
- If there is the same price, compare the size. If the size is 0, delete this depth data. If the size changes, replace the original data.
- If there is no same price, sort by price (bid in descending order, ask in ascending order), and insert the depth information into the full load.
Calculate Checksum
Use the first 25 bids and asks in the full load to form a string (where a colon connects the price and size in an ask or a bid), and then calculate the CRC32 value (32-bit signed integer).
Calculate Checksum
1. More than 25 levels of bid and ask
A full load of market depth (only 2 levels of data are shown here, while 25 levels of data should actually be intercepted):
{
"bids": [
["3366.1", "7", "0", "3"],
["3366", "6", "3", "4"]
],
"asks": [
["3366.8", "9", "10", "3"],
["3368", "8", "3", "4"]
]
}
Check string:
"3366.1:7:3366.8:9:3366:6:3368:8"
2. Less than 25 levels of bid or ask
A full load of market depth:
{
"bids": [
["3366.1", "7", "0", "3"]
],
"asks": [
["3366.8", "9", "10", "3"],
["3368", "8", "3", "4"],
["3372", "8", "3", "4"]
]
}
Check string:
"3366.1:7:3366.8:9:3368:8:3372:8"
- When the bid and ask depth data exceeds 25 levels, each of them will intercept 25 levels of data, and the string to be checked is queued in a way that the bid and ask depth data are alternately arranged.
Such as:bid[price:size]
:ask[price:size]
:bid[price:size]
:ask[price:size]
... - When the bid or ask depth data is less than 25 levels, the missing depth data will be ignored.
Such as:bid[price:size]
:ask[price:size]
:asks[price:size]
:asks[price:size]
...
Push Data Example of bbo-tbt channel
{
"arg": {
"channel": "bbo-tbt",
"instId": "BCH-USDT-SWAP"
},
"data": [
{
"asks": [
[
"111.06","55154","0","2"
]
],
"bids": [
[
"111.05","57745","0","2"
]
],
"ts": "1670324386802",
"seqId": 363996337
}
]
}
Push Data Example of books5 channel
{
"arg": {
"channel": "books5",
"instId": "BCH-USDT-SWAP"
},
"data": [
{
"asks": [
["111.06","55154","0","2"],
["111.07","53276","0","2"],
["111.08","72435","0","2"],
["111.09","70312","0","2"],
["111.1","67272","0","2"]],
"bids": [
["111.05","57745","0","2"],
["111.04","57109","0","2"],
["111.03","69563","0","2"],
["111.02","71248","0","2"],
["111.01","65090","0","2"]],
"instId": "BCH-USDT-SWAP",
"ts": "1670324386802",
"seqId": 363996337
}
]
}
Public Data
The API endpoints of Public Data
do not require authentication.
REST API
Get instruments
Retrieve a list of instruments with open contracts.
Rate Limit: 20 requests per 2 seconds
Rate limit rule: IP + instrumentType
HTTP Request
GET /api/v5/public/instruments
Request Example
GET /api/v5/public/instruments?instType=SPOT
import okx.PublicData as PublicData
flag = "0" # Production trading: 0, Demo trading: 1
publicDataAPI = PublicData.PublicAPI(flag=flag)
# Retrieve a list of instruments with open contracts
result = publicDataAPI.get_instruments(
instType="SPOT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
instType | String | Yes | Instrument typeSPOT |
instId | String | No | Instrument ID |
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"alias": "",
"baseCcy": "BTC",
"category": "1",
"ctMult": "",
"ctType": "",
"ctVal": "",
"ctValCcy": "",
"expTime": "",
"instFamily": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"lever": "10",
"listTime": "1606468572000",
"lotSz": "0.00000001",
"maxIcebergSz": "9999999999.0000000000000000",
"maxLmtAmt": "1000000",
"maxLmtSz": "9999999999",
"maxMktAmt": "1000000",
"maxMktSz": "",
"maxStopSz": "",
"maxTriggerSz": "9999999999.0000000000000000",
"maxTwapSz": "9999999999.0000000000000000",
"minSz": "0.00001",
"optType": "",
"quoteCcy": "USDT",
"settleCcy": "",
"state": "live",
"stk": "",
"tickSz": "0.1",
"uly": ""
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
instType | String | Instrument type |
instId | String | Instrument ID, e.g. BTC-USDT |
uly | String | Underlying, e.g. BTC-USD Only applicable to FUTURES /SWAP /OPTION |
instFamily | String | Instrument family, e.g. BTC-USD Only applicable to FUTURES /SWAP /OPTION |
category | String | Currency category. Note: this parameter is already deprecated |
baseCcy | String | Base currency, e.g. BTC inBTC-USDT Only applicable to SPOT /MARGIN |
quoteCcy | String | Quote currency, e.g. USDT in BTC-USDT Only applicable to SPOT /MARGIN |
settleCcy | String | Settlement and margin currency, e.g. BTC Only applicable to FUTURES /SWAP /OPTION |
ctVal | String | Contract value Only applicable to FUTURES /SWAP /OPTION |
ctMult | String | Contract multiplier Only applicable to FUTURES /SWAP /OPTION |
ctValCcy | String | Contract value currency Only applicable to FUTURES /SWAP /OPTION |
optType | String | Option type, C : Call P : put Only applicable to OPTION |
stk | String | Strike price Only applicable to OPTION |
listTime | String | Listing time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
expTime | String | Expiry time Applicable to SPOT /MARGIN /FUTURES /SWAP /OPTION . For FUTURES /OPTION , it is natural delivery/exercise time. It is the instrument offline time when there is SPOT/MARGIN/FUTURES/SWAP/ manual offline. Update once change. |
lever | String | Max Leverage, Not applicable to SPOT , OPTION |
tickSz | String | Tick size, e.g. 0.0001 For Option, it is minimum tickSz among tick band, please use "Get option tick bands" if you want get option tickBands. |
lotSz | String | Lot size If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
minSz | String | Minimum order size If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
ctType | String | Contract typelinear : linear contractinverse : inverse contract Only applicable to FUTURES /SWAP |
alias | String | Aliasthis_week next_week this_month next_month quarter next_quarter Only applicable to FUTURES Not recommended for use, users are encouraged to rely on the expTime field to determine the delivery time of the contract |
state | String | Instrument statuslive suspend preopen . e.g. There will be preopen before the Futures and Options new contracts state is live.test : Test pairs, can't be traded |
maxLmtSz | String | The maximum order quantity of a single limit order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
maxMktSz | String | The maximum order quantity of a single market order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in USDT . |
maxLmtAmt | String | Max USD amount for a single limit order |
maxMktAmt | String | Max USD amount for a single market order Only applicable to SPOT /MARGIN |
maxTwapSz | String | The maximum order quantity of a single TWAP order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
maxIcebergSz | String | The maximum order quantity of a single iceBerg order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
maxTriggerSz | String | The maximum order quantity of a single trigger order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
maxStopSz | String | The maximum order quantity of a single stop market order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in USDT . |
Get system time
Retrieve API server time.
Rate Limit: 10 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/public/time
Request Example
GET /api/v5/public/time
import okx.PublicData as PublicData
flag = "0" # Production trading: 0, Demo trading: 1
publicDataAPI = PublicData.PublicAPI(flag=flag)
# Retrieve API server time
result = publicDataAPI.get_system_time()
print(result)
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"ts":"1597026383085"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
ts | String | System time, Unix timestamp format in milliseconds, e.g. 1597026383085 |
Get oracle
Get the crypto price of signing using Open Oracle smart contract.
Rate Limit: 1 request per 5 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/open-oracle
Request Example
GET /api/v5/market/open-oracle
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Get the crypto price of signing using Open Oracle smart contract
result = marketDataAPI.get_oracle()
print(result)
Response Example
{
"code":"0",
"msg":"",
"data":[
{
"messages":[
"0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000616d3b1400000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000e70528b800000000000000000000000000000000000000000000000000000000000000006707269636573000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034254430000000000000000000000000000000000000000000000000000000000"
],
"prices":{
"BTC":"62014"
},
"signatures":[
"0xf18330e59eaf42373c2c40f1f9e24113ba21d4ed734dd3ed3bc1d12290fa74ba5623fca1113c5d245a1202dc065e333615b90f810f12132ce4a1ecacb8c6b24a000000000000000000000000000000000000000000000000000000000000001b"
],
"timestamp":"1634548500"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
messages | String | ABI-encoded values [kind, timestamp, key, value], where kind equals 'prices', timestamp is the time when price was obtained, key is the asset ticker (e.g. btc) and value is the asset price. |
prices | String | Readable asset prices |
signatures | String | Ethereum-compatible ECDSA signatures for each message |
timestamp | String | Time of latest datapoint, Unix timestamp, e.g. 1597026387 |
Get exchange rate
This interface provides the average exchange rate data for 2 weeks
Rate Limit: 1 request per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/exchange-rate
Request Example
GET /api/v5/market/exchange-rate
import okx.MarketData as MarketData
flag = "0" # Production trading:0 , demo trading:1
marketDataAPI = MarketData.MarketAPI(flag=flag)
# Retrieve average exchange rate data for 2 weeks
result = marketDataAPI.get_exchange_rate()
print(result)
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"usdCny": "7.162"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
usdCny | String | Exchange rate |
Get economic calendar data
Get the macro-economic calendar data within 3 months. Historical data from 3 months ago is only available to users with trading fee tier VIP1 and above.
Rate Limit: 1 request per 5 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/public/economic-calendar
Request Example
GET /api/v5/public/economic-calendar
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
region | string | No | Country, region or entity afghanistan , albania , algeria , andorra , angola , antigua_and_barbuda , argentina , armenia , aruba , australia , austria , azerbaijan , bahamas , bahrain , bangladesh , barbados , belarus , belgium , belize , benin , bermuda , bhutan , bolivia , bosnia_and_herzegovina , botswana , brazil , brunei , bulgaria , burkina_faso , burundi , cambodia , cameroon , canada , cape_verde , cayman_islands , central_african_republic , chad , chile , china , colombia , comoros , congo , costa_rica , croatia , cuba , cyprus , czech_republic , denmark , djibouti , dominica , dominican_republic , east_timor , ecuador , egypt , el_salvador , equatorial_guinea , eritrea , estonia , ethiopia , euro_area , european_union , faroe_islands , fiji , finland , france , g20 , g7 , gabon , gambia , georgia , germany , ghana , greece , greenland , grenada , guatemala , guinea , guinea_bissau , guyana , hungary , haiti , honduras , hong_kong , hungary , imf , indonesia , iceland , india , indonesia , iran , iraq , ireland , isle_of_man , israel , italy , ivory_coast , jamaica , japan , jordan , kazakhstan , kenya , kiribati , kosovo , kuwait , kyrgyzstan , laos , latvia , lebanon , lesotho , liberia , libya , liechtenstein , lithuania , luxembourg , macau , macedonia , madagascar , malawi , malaysia , maldives , mali , malta , mauritania , mauritius , mexico , micronesia , moldova , monaco , mongolia , montenegro , morocco , mozambique , myanmar , namibia , nepal , netherlands , new_caledonia , new_zealand , nicaragua , niger , nigeria , north_korea , northern_mariana_islands , norway , opec , oman , pakistan , palau , palestine , panama , papua_new_guinea , paraguay , peru , philippines , poland , portugal , puerto_rico , qatar , russia , republic_of_the_congo , romania , russia , rwanda , slovakia , samoa , san_marino , sao_tome_and_principe , saudi_arabia , senegal , serbia , seychelles , sierra_leone , singapore , slovakia , slovenia , solomon_islands , somalia , south_africa , south_korea , south_sudan , spain , sri_lanka , st_kitts_and_nevis , st_lucia , sudan , suriname , swaziland , sweden , switzerland , syria , taiwan , tajikistan , tanzania , thailand , togo , tonga , trinidad_and_tobago , tunisia , turkey , turkmenistan , uganda , ukraine , united_arab_emirates , united_kingdom , united_states , uruguay , uzbekistan , vanuatu , venezuela , vietnam , world , yemen , zambia , zimbabwe |
importance | string | No | Level of importance 1 : low 2 : medium 3 : high |
before | String | No | Pagination of data to return records newer than the requested ts based on the date parameter. Unix timestamp format in milliseconds. |
after | String | No | Pagination of data to return records earlier than the requested ts based on the date parameter. Unix timestamp format in milliseconds. The default is the timestamp of the request moment. |
limit | String | No | Number of results per request. The maximum is 100. The default is 100. |
Response Example
{
"code": "0",
"data": [
{
"actual": "7.8%",
"calendarId": "330631",
"category": "Harmonised Inflation Rate YoY",
"ccy": "",
"date": "1700121600000",
"dateSpan": "0",
"event": "Harmonised Inflation Rate YoY",
"forecast": "7.8%",
"importance": "1",
"prevInitial": "",
"previous": "9%",
"refDate": "1698710400000",
"region": "Slovakia",
"uTime": "1700121605007",
"unit": "%"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
calendarId | string | Calendar ID |
date | string | Estimated release time of the value of actual field, millisecond format of Unix timestamp, e.g. 1597026383085 |
region | string | Country, region or entity |
category | string | Category name |
event | string | Event name |
refDate | string | Date for which the datapoint refers to |
actual | string | The actual value of this event |
previous | string | Latest actual value of the previous period The value will be revised if revision is applicable |
forecast | string | Average forecast among a representative group of economists |
dateSpan | string | 0 : The time of the event is known1 : we only know the date of the event, the exact time of the event is unknown. |
importance | string | Level of importance 1 : low 2 : medium 3 : high |
uTime | string | Update time of this record, millisecond format of Unix timestamp, e.g. 1597026383085 |
prevInitial | string | The initial value of the previous period Only applicable when revision happens |
ccy | string | Currency of the data |
unit | string | Unit of the data |
WebSocket
Instruments channel
URL Path
/ws/v5/public
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "instruments",
"instType": "SPOT"
}
]
}
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel nameinstruments |
> instType | String | Yes | Instrument typeSPOT |
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "instruments",
"instType": "SPOT"
},
"connId": "a4d3ae55"
}
Failure Response Example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"instruments\", \"instType\" : \"FUTURES\"}]}",
"connId": "a4d3ae55"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel name |
> instType | String | Yes | Instrument typeSPOT |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
Push Data Example
{
"arg": {
"channel": "instruments",
"instType": "SPOT"
},
"data": [
{
"alias": "",
"baseCcy": "BTC",
"category": "1",
"ctMult": "",
"ctType": "",
"ctVal": "",
"ctValCcy": "",
"expTime": "",
"instFamily": "",
"instId": "BTC-USDT",
"instType": "SPOT",
"lever": "10",
"listTime": "1606468572000",
"lotSz": "0.00000001",
"maxIcebergSz": "9999999999.0000000000000000",
"maxLmtAmt": "1000000",
"maxLmtSz": "9999999999",
"maxMktAmt": "1000000",
"maxMktSz": "",
"maxStopSz": "",
"maxTriggerSz": "9999999999.0000000000000000",
"maxTwapSz": "9999999999.0000000000000000",
"minSz": "0.00001",
"optType": "",
"quoteCcy": "USDT",
"settleCcy": "",
"state": "live",
"stk": "",
"tickSz": "0.1",
"uly": ""
}
]
}
Push data parameters
Parameter | Type | Description |
---|---|---|
arg | Object | Subscribed channel |
> channel | String | Channel name |
> instType | String | Instrument type |
data | Array | Subscribed data |
> instType | String | Instrument type |
> instId | String | Instrument ID, e.g. BTC-UST |
> uly | String | Underlying, e.g. BTC-USD Only applicable to FUTURES /SWAP /OPTION |
> instFamily | String | Instrument family, e.g. BTC-USD Only applicable to FUTURES /SWAP /OPTION |
> category | String | Currency category. Note: this parameter is already deprecated |
> baseCcy | String | Base currency, e.g. BTC in BTC-USDT Only applicable to SPOT /MARGIN |
> quoteCcy | String | Quote currency, e.g. USDT in BTC-USDT Only applicable to SPOT /MARGIN |
> settleCcy | String | Settlement and margin currency, e.g. BTC Only applicable to FUTURES /SWAP /OPTION |
> ctVal | String | Contract value |
> ctMult | String | Contract multiplier |
> ctValCcy | String | Contract value currency |
> optType | String | Option typeC : CallP : PutOnly applicable to OPTION |
> stk | String | Strike price Only applicable to OPTION |
> listTime | String | Listing time Only applicable to FUTURES /SWAP /OPTION |
> expTime | String | Expiry time Applicable to SPOT /MARGIN /FUTURES /SWAP /OPTION . For FUTURES /OPTION , it is the delivery/exercise time. It can also be the delisting time of the trading instrument. Update once change. |
> lever | String | Max Leverage Not applicable to SPOT /OPTION , used to distinguish between MARGIN and SPOT . |
> tickSz | String | Tick size, e.g. 0.0001 For Option, it is minimum tickSz among tick band. |
> lotSz | String | Lot size If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency |
> minSz | String | Minimum order size If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency |
> ctType | String | Contract typelinear : linear contractinverse : inverse contractOnly applicable to FUTURES /SWAP |
> alias | String | Aliasthis_week next_week this_month next_month quarter next_quarter Only applicable to FUTURES Not recommended for use, users are encouraged to rely on the expTime field to determine the delivery time of the contract |
> state | String | Instrument statuslive suspend expired preopen . e.g. There will be preopen before the Futures and Options new contracts state is live. test : Test pairs, can't be traded |
> maxLmtSz | String | The maximum order quantity of a single limit order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
> maxMktSz | String | The maximum order quantity of a single market order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in USDT . |
> maxTwapSz | String | The maximum order quantity of a single TWAP order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
> maxIcebergSz | String | The maximum order quantity of a single iceBerg order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
> maxTriggerSz | String | The maximum order quantity of a single trigger order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in base currency . |
> maxStopSz | String | The maximum order quantity of a single stop market order. If it is a derivatives contract, the value is the number of contracts. If it is SPOT /MARGIN , the value is the quantity in USDT . |
Economic calendar channel
Retrieve the most up-to-date economic calendar data. This endpoint is only applicable to VIP 1 and above users in the trading fee tier.
URL Path
/ws/v5/business (required login)
Request Example
{
"op": "subscribe",
"args": [
{
"channel": "economic-calendar"
}
]
}
Request parameters
Parameter | Type | Required | Description |
---|---|---|---|
op | String | Yes | Operationsubscribe unsubscribe |
args | Array | Yes | List of subscribed channels |
> channel | String | Yes | Channel nameeconomic-calendar |
Successful Response Example
{
"event": "subscribe",
"arg": {
"channel": "economic-calendar"
}
}
Failure Response Example
{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"mark-price\", \"instId\" : \"LTC-USD-190628\"}]}"
}
Response parameters
Parameter | Type | Required | Description |
---|---|---|---|
event | String | Yes | Eventsubscribe unsubscribe error |
arg | Object | No | Subscribed channel |
> channel | String | Yes | Channel name |
code | String | No | Error code |
msg | String | No | Error message |
connId | String | Yes | WebSocket connection ID |
Push Data Example
{
"arg": {
"channel": "economic-calendar"
},
"data": [
{
"calendarId": "319275",
"date": "1597026383085",
"region": "United States",
"category": "Manufacturing PMI",
"event": "S&P Global Manufacturing PMI Final",
"refDate": "1597026383085",
"actual": "49.2",
"previous": "47.3",
"forecast": "49.3",
"importance": "2",
"prevInitial": "",
"ccy": "",
"unit": "",
"ts": "1698648096590"
}
]
}
Push data parameters
Parameter | Type | Description |
---|---|---|
arg | Object | Successfully subscribed channel |
> channel | String | Channel name |
data | Array | Subscribed data |
> event | string | Event name |
> region | string | Country, region or entity |
> category | string | Category name |
> actual | string | The actual value of this event |
> previous | string | Latest actual value of the previous period The value will be revised if revision is applicable |
> forecast | string | Average forecast among a representative group of economists |
> prevInitial | string | The initial value of the previous period Only applicable when revision happens |
> date | string | Estimated release time of the value of actual field, millisecond format of Unix timestamp, e.g. 1597026383085 |
> refDate | string | Date for which the datapoint refers to |
> calendarId | string | Calendar ID |
> unit | string | Unit of the data |
> ccy | string | Currency of the data |
> importance | string | Level of importance1 : low 2 : medium 3 : high |
> ts | string | The time of the latest update |
Funding Account
The API endpoints of Funding Account
require authentication.
REST API
Get currencies
Retrieve a list of all currencies available which are related to the current account's KYC entity.
Rate Limit: 6 requests per second
Rate limit rule: UserID
HTTP Request
GET /api/v5/asset/currencies
Request Example
GET /api/v5/asset/currencies
import okx.Funding as Funding
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "0" # Production trading: 0, Demo trading: 1
fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
# Get currencies
result = fundingAPI.get_currencies()
print(result)
Request Parameters
Parameters | Types | Required | Description |
---|---|---|---|
ccy | String | No | Single currency or multiple currencies separated with comma, e.g. BTC or BTC,ETH . |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"canDep": true,
"canInternal": true,
"canWd": true,
"ccy": "BTC",
"chain": "BTC-Bitcoin",
"depQuotaFixed": "",
"depQuoteDailyLayer2": "",
"logoLink": "https://static.coinall.ltd/cdn/oksupport/asset/currency/icon/btc.png",
"mainNet": true,
"maxFee": "0.0004",
"maxFeeForCtAddr": "0.0004",
"maxWd": "500",
"minDep": "0.00005",
"minDepArrivalConfirm": "1",
"minFee": "0.0002",
"minFeeForCtAddr": "0.0002",
"minWd": "0.001",
"minWdUnlockConfirm": "3",
"name": "Bitcoin",
"needTag": false,
"usedDepQuotaFixed": "",
"usedWdQuota": "0",
"wdQuota": "200",
"wdTickSz": "8"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
ccy | String | Currency, e.g. BTC |
name | String | Name of currency. There is no related name when it is not shown. |
logoLink | String | The logo link of currency |
chain | String | Chain name, e.g. USDT-ERC20 , USDT-TRC20 |
canDep | Boolean | The availability to deposit from chain false : not available true : available |
canWd | Boolean | The availability to withdraw to chain false : not available true : available |
canInternal | Boolean | The availability to internal transfer false : not available true : available |
minDep | String | The minimum deposit amount of currency in a single transaction |
minWd | String | The minimum on-chain withdrawal amount of currency in a single transaction |
maxWd | String | The maximum amount of currency on-chain withdrawal in a single transaction |
wdTickSz | String | The withdrawal precision, indicating the number of digits after the decimal point. The withdrawal fee precision kept the same as withdrawal precision. The accuracy of internal transfer withdrawal is 8 decimal places. |
wdQuota | String | The withdrawal limit in the past 24 hours (including on-chain withdrawal and internal transfer ), unit in USD |
usedWdQuota | String | The amount of currency withdrawal used in the past 24 hours, unit in USD |
minFee | String | The minimum withdrawal fee for normal address Apply to on-chain withdrawal |
maxFee | String | The maximum withdrawal fee for normal address Apply to on-chain withdrawal |
minFeeForCtAddr | String | The minimum withdrawal fee for contract address Apply to on-chain withdrawal |
maxFeeForCtAddr | String | The maximum withdrawal fee for contract address Apply to on-chain withdrawal |
mainNet | Boolean | If current chain is main net, then it will return true , otherwise it will return false |
needTag | Boolean | Whether tag/memo information is required for withdrawal, e.g. EOS will return true |
minDepArrivalConfirm | String | The minimum number of blockchain confirmations to acknowledge fund deposit. The account is credited after that, but the deposit can not be withdrawn |
minWdUnlockConfirm | String | The minimum number of blockchain confirmations required for withdrawal of a deposit |
depQuotaFixed | String | The fixed deposit limit, unit in USD Return empty string if there is no deposit limit |
usedDepQuotaFixed | String | The used amount of fixed deposit quota, unit in USD Return empty string if there is no deposit limit |
depQuoteDailyLayer2 | String | The layer2 network daily deposit limit |
Get balance
Retrieve the funding account balances of all the assets and the amount that is available or on hold.
Rate Limit: 6 requests per second
Rate limit rule: UserID
HTTP Request
GET /api/v5/asset/balances
Request Example
GET /api/v5/asset/balances
import okx.Funding as Funding
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "0" # Production trading: 0, Demo trading: 1
fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
# Get balane
result = fundingAPI.get_balances()
print(result)
Request Parameters
Parameters | Types | Required | Description |
---|---|---|---|
ccy | String | No | Single currency or multiple currencies (no more than 20) separated with comma, e.g. BTC or BTC,ETH . |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"availBal": "37.11827078",
"bal": "37.11827078",
"ccy": "ETH",
"frozenBal": "0"
}
]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
ccy | String | Currency |
bal | String | Balance |
frozenBal | String | Frozen balance |
availBal | String | Available balance |
Get non-tradable assets
Rate Limit: 6 requests per second
Rate limit rule: UserID
HTTP Request
GET /api/v5/asset/non-tradable-assets
Request Example
GET /api/v5/asset/non-tradable-assets
import okx.Funding as Funding
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
result = fundingAPI.get_non_tradable_assets()
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": [
{
"bal": "989.84719571",
"canWd": true,
"ccy": "CELT",
"chain": "CELT-OKTC",
"ctAddr": "f403fb",
"fee": "2",
"logoLink": "https://static.coinall.ltd/cdn/assets/imgs/221/460DA8A592400393.png",
"minWd": "0.1",
"name": "",
"needTag": false,
"wdAll": false,
"wdTickSz": "8"
},
{
"bal": "0.001",
"canWd": true,
"ccy": "MEME",
"chain": "MEME-ERC20",
"ctAddr": "09b760",
"fee": "5",
"logoLink": "https://static.coinall.ltd/cdn/assets/imgs/207/2E664E470103C613.png",
"minWd": "0.001",
"name": "MEME Inu",
"needTag": false,
"wdAll": false,
"wdTickSz": "8"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
ccy | String | Currency, e.g. CELT |
name | String | Chinese name of currency. There is no related name when it is not shown. |
logoLink | String | Logo link of currency |
bal | String | Withdrawable balance |
canWd | Boolean | Availability to withdraw to chain. false : not available true : available |
chain | String | Chain for withdrawal |
minWd | String | Minimum withdrawal amount of currency in a single transaction |
wdAll | Boolean | Whether all assets in this currency must be withdrawn at one time |
fee | String | Fixed withdrawal fee, unit in USDT . Withdrawal fee precision is 8 digits after the decimal point. |
ctAddr | String | Last 6 digits of contract address |
wdTickSz | String | Withdrawal precision, indicating the number of digits after the decimal point |
needTag | Boolean | Whether tag/memo information is required for withdrawal |
Get account asset valuation
View account asset valuation
Rate Limit: 1 request per second
Rate limit rule: UserID
HTTP Request
GET /api/v5/asset/asset-valuation
Request Example
GET /api/v5/asset/asset-valuation
import okx.Funding as Funding
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "0" # Production trading: 0, Demo trading: 1
fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
# Get account asset valuation
result = fundingAPI.get_asset_valuation()
print(result)
Request Parameters
Parameters | Types | Required | Description |
---|---|---|---|
ccy | String | No | Asset valuation calculation unit BTC, USDT USD, CNY, JP, KRW, RUB, EUR VND, IDR, INR, PHP, THB, TRY AUD, SGD, ARS, SAR, AED, IQD The default is the valuation in BTC. |
Response Example
{
"code": "0",
"data": [
{
"details": {
"classic": "124.6",
"earn": "1122.73",
"funding": "0.09",
"trading": "2544.28"
},
"totalBal": "3790.09",
"ts": "1637566660769"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
totalBal | String | Valuation of total account assets |
ts | String | Unix timestamp format in milliseconds, e.g.1597026383085 |
details | Object | Asset valuation details for each account |
> funding | String | Funding account |
> trading | String | Trading account |
> classic | String | [Deprecated] Classic account |
> earn | String | Earn account |
Funds transfer
Only API keys with Trade
privilege can call this endpoint.
This endpoint supports the transfer of funds between your funding account and trading account, and from the master account to sub-accounts.
Sub-account can transfer out to master account by default. Need to call Set permission of transfer out to grant privilege first if you want sub-account transferring to another sub-account (sub-accounts need to belong to same master account.)
Rate Limit: 2 requests per second
Rate limit rule: UserID + Currency
HTTP Request
POST /api/v5/asset/transfer
Request Example
# Transfer 1.5 USDT from funding account to Trading account when current account is master-account
POST /api/v5/asset/transfer
body
{
"ccy":"USDT",
"amt":"1.5",
"from":"6",
"to":"18"
}
# Transfer 1.5 USDT from funding account to subAccount when current account is master-account
POST /api/v5/asset/transfer
body
{
"ccy":"USDT",
"type":"1",
"amt":"1.5",
"from":"6",
"to":"6",
"subAcct":"mini"
}
# Transfer 1.5 USDT from funding account to subAccount when current account is sub-account
POST /api/v5/asset/transfer
body
{
"ccy":"USDT",
"type":"4",
"amt":"1.5",
"from":"6",
"to":"6",
"subAcct":"mini"
}
import okx.Funding as Funding
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "0" # Production trading: 0, Demo trading: 1
fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
# Funds transfer
result = fundingAPI.funds_transfer(
ccy="USDT",
amt="1.5",
from_="6",
to="18"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
type | String | No | Transfer type0 : transfer within account1 : master account to sub-account (Only applicable to API Key from master account)2 : sub-account to master account (Only applicable to API Key from master account)3 : sub-account to master account (Only applicable to APIKey from sub-account)4 : sub-account to sub-account (Only applicable to APIKey from sub-account, and target account needs to be another sub-account which belongs to same master account. Sub-account directly transfer out permission is disabled by default, set permission please refer to Set permission of transfer out)The default is 0 .If you want to make transfer between sub-accounts by master account API key, refer to Master accounts manage the transfers between sub-accounts |
ccy | String | Yes | Transfer currency, e.g. USDT |
amt | String | Yes | Amount to be transferred |
from | String | Yes | The remitting account6 : Funding account18 : Trading account |
to | String | Yes | The beneficiary account6 : Funding account18 : Trading account |
subAcct | String | Conditional | Name of the sub-account When type is 1 /2 /4 , this parameter is required. |
loanTrans | Boolean | No | Whether or not borrowed coins can be transferred out under Multi-currency margin and Portfolio margin true : borrowed coins can be transferred outfalse : borrowed coins cannot be transferred outthe default is false |
omitPosRisk | String | No | Ignore position risk Default is false Applicable to Portfolio margin |
clientId | String | No | Client-supplied ID A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
Response Example
{
"code": "0",
"msg": "",
"data": [
{
"transId": "754147",
"ccy": "USDT",
"clientId": "",
"from": "6",
"amt": "0.1",
"to": "18"
}
]
}
Response Parameters
Response Example
Parameter | Type | Description |
---|---|---|
transId | String | Transfer ID |
clientId | String | Client-supplied ID |
ccy | String | Currency |
from | String | The remitting account |
amt | String | Transfer amount |
to | String | The beneficiary account |
Get funds transfer state
Retrieve the transfer state data of the last 2 weeks.
Rate Limit: 10 request per second
Rate limit rule: UserID
HTTP Request
GET /api/v5/asset/transfer-state
Request Example
GET /api/v5/asset/transfer-state?transId=1&type=1
import okx.Funding as Funding
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "1" # Production trading: 0, Demo trading: 1
fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
# Get funds transfer state
result = fundingAPI.transfer_state(
transId="248424899",
type="0"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
transId | String | Conditional | Transfer ID Either transId or clientId is required. If both are passed, transId will be used. |
clientId | String | Conditional | Client-supplied ID A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
type | String | No | Transfer type0 : transfer within account 1 : master account to sub-account (Only applicable to API Key from master account) 2 : sub-account to master account (Only applicable to API Key from master account)3 : sub-account to master account (Only applicable to APIKey from sub-account)4 : sub-account to sub-account (Only applicable to APIKey from sub-account, and target account needs to be another sub-account which belongs to same master account)The default is 0 |
Response Example
{
"code": "0",
"data": [
{
"amt": "1.5",
"ccy": "USDT",
"clientId": "",
"from": "18",
"instId": "", //deprecated
"state": "success",
"subAcct": "test",
"to": "6",
"toInstId": "", //deprecated
"transId": "1",
"type": "1"
}
],
"msg": ""
}
Response Parameters
Parameter | Type | Description |
---|---|---|
transId | String | Transfer ID |
clientId | String | Client-supplied ID |
ccy | String | Currency, e.g. USDT |
amt | String | Amount to be transferred |
type | String | Transfer type0 : transfer within account1 : master account to sub-account (Only applicable to API Key from master account) 2 : sub-account to master account (Only applicable to APIKey from master account)3 : sub-account to master account (Only applicable to APIKey from sub-account)4 : sub-account to sub-account (Only applicable to APIKey from sub-account, and target account needs to be another sub-account which belongs to same master account) |
from | String | The remitting account6 : Funding account18 : Trading account |
to | String | The beneficiary account6 : Funding account18 : Trading account |
subAcct | String | Name of the sub-account |
instId | String | deprecated |
toInstId | String | deprecated |
state | String | Transfer statesuccess pending failed |
Asset bills details
Query the billing record in the past month.
Rate Limit: 6 Requests per second
Rate limit rule: UserID
HTTP Request
GET /api/v5/asset/bills
Request Example
GET /api/v5/asset/bills
import okx.Funding as Funding
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "0" # Production trading: 0, Demo trading: 1
fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
# Get asset bills details
result = fundingAPI.get_bills()
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
ccy | String | No | Currency |
type | String | No | Bill type1 : Deposit2 : Withdrawal13 : Canceled withdrawal20 : Transfer to sub account (for master account)21 : Transfer from sub account (for master account)22 : Transfer out from sub to master account (for sub-account)23 : Transfer in from master to sub account (for sub-account)28 : Manually claimed Airdrop47 : System reversal48 : Event Reward49 : Event Giveaway61 : (Convert) Exchange between crypto69 : Distribute rebate card72 : Token received73 : Token given away74 : Token refunded75 : Subscription to savings76 : Redemption to savings77 : Jumpstart distribute78 : Jumpstart lock up80 : DEFI/Staking purchase82 : DEFI/Staking redemption83 : Staking yield84 : Violation fee116 : (Fiat) Place an order117 : (Fiat) Fulfill an order118 : (Fiat) Cancel an order124 : Jumpstart unlocking130 : Transferred from Trading account131 : Transferred to Trading account135 : Cross chain exchange136 : ETH 2.0 staking system account increase ETH (for on-chain operation)137 : ETH 2.0 Subscription138 : ETH 2.0 Swapping139 : ETH 2.0 Earnings146 : Customer feedback150 : Affiliate commission151 : Referral reward152 : Broker reward160 : Dual Investment subscribe161 : Dual Investment collection162 : Dual Investment profit163 : Dual Investment refund172 : Sub-affiliate commission173 : Fee rebate (by trading fee)174 : Jumpstart Pay175 : Locked collateral176 : Loan177 : Added collateral178 : Returned collateral179 : Repayment180 : Unlocked collateral181 : Airdrop payment185 : (Broker) Convert reward187 : (Broker) Convert transfer189 : Mystery box bonus195 : Untradable asset withdrawal196 : Untradable asset withdrawal revoked197 : Untradable asset deposit198 : Untradable asset collection reduce199 : Untradable asset collection increase200 : Buy202 : Price Lock Subscribe203 : Price Lock Collection204 : Price Lock Profit205 : Price Lock Refund207 : Dual Investment Lite Subscribe208 : Dual Investment Lite Collection209 : Dual Investment Lite Profit210 : Dual Investment Lite Refund212 : (Flexible loan) Multi-collateral loan collateral locked214 : (Flexible loan) Collateral returned to users216 : (Flexible loan) Loan transfer into user's funding account218 : (Flexible loan) Multi-collateral loan repaid220 : Delisted crypto221 : Blockchain's withdrawal fee222 : Withdrawal fee refund223 : SWAP lead trading profit share225 : Shark Fin subscribe226 : Shark Fin collection227 : Shark Fin profit228 : Shark Fin refund229 : Airdrop233 : Broker rebate compensation240 : Snowball subscribe241 : Snowball refund242 : Snowball profit243 : Snowball trading failed249 : Seagull subscribe250 : Seagull collection251 : Seagull profit252 : Seagull refund263 : Strategy bots profit share265 : Signal revenue266 : SPOT lead trading profit share270 : DCD broker transfer271 : DCD broker rebate272 : (Convert) Buy Crypto/Fiat273 : (Convert) Sell Crypto/Fiat284 : (Custody) Transfer out trading sub-account285 : (Custody) Transfer in trading sub-account286 : (Custody) Transfer out custody funding account287 : (Custody) Transfer in custody funding account288 : (Custody) Fund delegation 289 : (Custody) Fund undelegation299 : Affiliate recommendation commission300 : Fee discount rebate303 : Snowball market maker transfer304 : Simple Earn Fixed order submission305 : Simple Earn Fixed order redemption306 : Simple Earn Fixed principal distribution307 : Simple Earn Fixed interest distribution (early termination compensation)308 : Simple Earn Fixed interest distribution309 : Simple Earn Fixed interest distribution (extension compensation) 311 : Crypto dust auto-transfer in |
clientId | String | No | Client-supplied ID for transfer or withdrawal A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters. |
after | String | No | Pagination of data to return records earlier than the requested ts , Unix timestamp format in milliseconds, e.g. 1597026383085 |
before | String | No | Pagination of data to return records newer than the requested ts , Unix timestamp format in milliseconds, e.g. 1597026383085 |
limit | String | No | Number of results per request. The maximum is 100 . The default is 100 . |
Response Example
{
"code": "0",
"msg": "",
"data": [{
"billId": "12344",
"ccy": "BTC",
"clientId": "",
"balChg": "2",
"bal": "12",
"type": "1",
"ts": "1597026383085"
}]
}
Response Parameters
Parameter | Type | Description |
---|---|---|
billId | String | Bill ID |
ccy | String | Account balance currency |
clientId | String | Client-supplied ID for transfer or withdrawal |
balChg | String | Change in balance at the account level |
bal | String | Balance at the account level |
type | String | Bill type |
ts | String | Creation time, Unix timestamp format in milliseconds, e.g.1597026383085 |
Get deposit address
Retrieve the deposit addresses of currencies, including previously-used addresses.
Rate Limit: 6 requests per second
Rate limit rule: UserID
HTTP Request
GET /api/v5/asset/deposit-address
Request Example
GET /api/v5/asset/deposit-address?ccy=BTC
import okx.Funding as Funding
# API initialization
apikey = "YOUR_API_KEY"
secretkey = "YOUR_SECRET_KEY"
passphrase = "YOUR_PASSPHRASE"
flag = "0" # Production trading: 0, Demo trading: 1
fundingAPI = Funding.FundingAPI(apikey, secretkey, passphrase, False, flag)
# Get deposit address
result = fundingAPI.get_deposit_address(
ccy="USDT"
)
print(result)
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
ccy | String | Yes | Currency, e.g. BTC |
Response Example
{
"code": "0",
"data": [
{
"chain": "BTC-Bitcoin",
"ctAddr": "",
"ccy": "BTC",
"to": "6",
"addr": "39XNxK1Ryqgg3Bsyn6HzoqV4Xji25pNkv6",
"verifiedName":"John Corner",
"selected": true
},
{