INTRODUCTION


Welcome to the OKEx API. Please note that v3 is the current version of this document. Please check this document periodically for latest updates.

OKEx offers powerful APIs for you to integrate into your applications. They are divided into three categories: account, trading, and market trends.

The account and trading APIs require authentication with an API key and allows you to:

  • place and cancel orders
  • see order status and account info

The market data API is publicly accessible and provides market data such as:

  • historical price of trading pairs

After registering an account on OKEx, you can create API keys with different permissions to allow you to separate privileges for your API keys where one API key can trade while another can withdraw.

Getting Access

To access the API, create an API key via this link. API instructions and settings are all included in this document.

Endpoints Configurations

OKEx offers offers both REST and WebSocket APIs. Either can be used for viewing market data, trading, or withdrawals. Refer to the SDK for details

REST API

REST, or Representational State Transfer, is one of the most popular architectural methods for creating web services, as its framework is clear, standardized, user-friendly, and scalable. It also has the following advantages:

  • Under the RESTful framework, each URL represents a type of resource
  • The representational state of this resource is transferred between the client and server
  • Representational State Transfer (REST) is realized with client requesting server via four HTTP request method. We strongly recommend you to use REST APIs to perform trades and make withdrawals
WebSocket API

WebSocket is a new HTML5 protocol. It achieves full-duplex data transmission between the client and the server, allowing data to transmit effectively in both directions. With one simple handshake, the connection between the client and the server is established, and the server can push information to the client according to business rules. WebSocket has the following advantages:

  • The WebSocket request header for data transmission between client and server is only approximately 2 bytes;
  • Either the client or server can initiate a data transmission;
  • Significant network and server resources are saved without needing to create and delete connections repeatedly. We strongly recommend you to use WebSocket API to obtain market data.
Contact

Please feel free to join our API community on Telegram (https://t.me/OKExAPI), where we will help answer your questions and you can share your experiences with other users.

For WeChat, please remark: API + Name + OKEx Account ID, to the API support group.

API Summary

Market overview and general information.

Matching Engine

Matching Engine

This section explains the matching engine based on the following:

  • Fill Price
  • Order Life Cycle
  • Token Trading Price Limit Rules
  • Futures Trading Price Limit Rules

Filled Price

OKEx’s matching engine executes orders according to price on a first-come, first-serve basis.

Example: 3 orders are placed in the order book respectively: a) 9900USDT for 1BTC, b) 10100USDT for 2BTC, and c) 9900USDT for 1.5BTC. They will be matched first based on price then based on placement time, which is b > a > c.

Orders are matched and executed at the maker price, not at taker price.

Example: User A placed an order to buy 1BTC at 10000USDT, and then user B placed an order to sell 1BTC at 8000USDT. Since the order created by user A was placed into the order book first, user A will be the maker in this transaction and the fill price will be 10000USDT for 1BTC.

Order Life Cycle

Orders are sent to the matching engine with the state unfilled. If the order fully executes against another order, it is considered filled. If the order is partially filled, it stays in the order matching queue waiting to be executed. If an open order is cancelled, its status will be changed to cancelled. All cancelled or filled orders will be removed from the matching queue.

Token Trading Price Limit Rules

A Fill-or-kill feature is available to prevent execution errors which may lead to unnecessary loss when placing orders.

Should an order be filled, regardless of its fill quantity, at a price that is more or less than 5% from the best bid & offer price by the time it executed in the order book, the order would be cancelled entirely. Otherwise, the order would be matched and executed as expected.

Example: A user placed a market order to buy 100BTC in XRP/BTC. The best offer price at the time was 0.00012. If the order had fully executed in the market, the market price would be driven up to 0.0002. Based on the calculation (0.0002-0.00012)/0.00012=66.7%>5%), the potential fill price would deviate greater than 30% from the current best offer. Therefore, the market order would be cancelled in its entirety.

Futures Trading Price Limit Rules

OKEx employs a set of price limit rules to set the mark price to protect traders from unnecessary liquidation triggered by deliberate market manipulation. Without this system only a small amount of funds with a high leverage can trigger considerable price volatility. However, the mark price must be constructed carefully to maintain a vibrant futures market. For the sake of better risk management, we cannot disclose the full details of how the mark price is set. OKEx considers a dozen of parameters when adjusting the risk management model, including trading volume, open interest, deviation index and more. However, some rules of the model shall be made transparent to demonstrate how it works.

These rules apply to all futures contracts.

1) For the first 10 minutes after a new contract is listed, the ceiling price limit = spot index price (1+5%) while the floor price limit = spot index price (1-5%).

2) If a contract is listed for more than 10 minutes, the ceiling limit = avg. premium (or discount) in the last 10 min + spot index price (1+3%). The floor limit = avg. premium (or discount) in the last 10 min + spot index price (1-3%). Premium (or discount) = contract price - spot index price.

3) If the price is lower than 0 or higher than 25% from the most deviated spot index price, the lowest price = spot price * (1 - 25%).

The rules stated above apply to all positions, whether it is opening or closing. If a long position is to be opened or short position to be closed, the price limit will apply when the price of limit order is higher than the ceiling price. If a short position is to be opened or long position to be closed, the price limit will apply when the price of the limit order is lower than the floor price.

Fees

Fees

This sections explains the fee details for the following:

  • Trading Fees
  • Deposit/Withdrawal Fees

Trading Fees

To encourage more order placement and liquidity, OKEx adopts a maker-taker fee schedule, where the maker fee is lower than the taker fee.

The fee schedule is volume-based. To qualify for a tier, you need to meet the minimum trading volume required, calculated on the average trading volume in the past 30 days. The higher the tier you are in, the lower the fees. In addition to the tiered fee schedule, the market maker program specifically rewards traders who intend to provide consistent liquidity and competitive bid-ask spread.

Please see here for details (https://www.okex.com/pages/products/fees.html)

Deposit/Withdrawal Fees

OKEx does not charge any withdrawal or deposit fees. Also, mining fees are not required for any transfers between OKCoin and OKEx, and the transfers between the two platforms are instant. However, mining fees will be levied by miners for any withdrawals out of OKCoin and OKEx.

Server Location

OKEx's database and servers are based in Hong Kong. To reduce API latency, we suggest choosing an ISP with stable connection to servers located in Hong Kong.

Requests

Requests

This section explains the requests details based on the following:

  • Introduction
  • Errors
  • Success

Introduction

REST API provides access to account management, market data, and trading.

REST API Terminal URL https://www.okex.com/

OKEx also offers WebSocket API for streaming data. Subscribe to the WebSocket and you can get market data pushed in real-time.

All requests are HTTPS-based. The contentType in the request header should be set as application/json

Errors

Unless otherwise stated, errors from bad requests will respond with HTTP 4xx status codes. The body returned will also contain information about the error.

Your HTTP library should be configured to provide message bodies for non-2xx requests so that you can read the message field from the body.

Common Error Codes
400 Bad Request — Invalid request format
401 Unauthorized — Invalid API Key
403 Forbidden — You do not have access to the requested resource
404 Not Found
500 Internal Server Error — We had a problem with our server

Success

A successful response is indicated by HTTP status code 200 and may optionally contain a body. If the response has a body it will be included under each resource below.

Pagination

1、Pagination

OKEx uses cursor pagination for some REST requests which return arrays. The cursor pagination allows for fetching results before and after the current page and is well suited for real-time data. The endpoints like /trades, /fills, /orders, return the latest 100 records by default. To retrieve more results, subsequent requests should specify the direction to paginate based on the data previously returned.

The cursors before and after are available via headers OK-BEFORE and OK-AFTER. Your requests should use these cursor values when making requests for pages after the initial request.

Example: GET /api/spot/v3/orders?before=2&limit=30

Parameters
Parameter Type Required Description
after String Yes Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String Yes Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String Yes Number of results per request. The maximum is 100; the default is 100

The before cursor refers to the first item in a results page and the after cursor references the last item in a set of results.

The response will contain an OK-BEFORE header which will return the cursor ID, which can be used in your next request for the page before the current one. The page before is a newer page and not one that happened before chronologically. The response will also contain an OK-AFTER header which will return the cursor ID, which can be used in your next request for the page after this one. The page after is an older page and not one that happened after this one chronologically.

For example,

  1. GET/api/futures/v3/orders/BTC-USD-190628?state=2 (The latest 100 transactions of contract of BTC-USD-190628 will be returned)

  2. GET/api/futures/v3/orders/BTC-USD-190628?state=2&limit=20 (The latest 20 transactions of contract of BTC-USD-190628 will be returned)

  3. GET/api/futures/v3/orders/BTC-USD-190628?state=2&after=2512669605501952&limit=20 (The 20 transaction data filled earlier than the contract ‘order_id=2512669605501952’ will be returned, without the order 2512669605501952)

  4. GET/api/futures/v3/orders/BTC-USD-190628?state=2&=before2512669605501952&limit=20 (The 20 transaction data filled later than the contract ‘order_id=2512669605501952’ will be returned, with the order 512669605501952 not included)

Rules

This section explains the standard specifications for the following:

  • Timestamps
  • Numbers
  • IDs

Timestamps

Unless otherwise specified, all timestamps from the API are returned in ISO 8601 with milliseconds. Make sure you can parse the ISO 8601 format with the example below. Most modern languages and libraries will handle this without issues.

Example

2014-11-06T10:34:47.123Z

Numbers

Decimal numbers are returned as "Strings" to preserve full precision across systems. It is recommended that the numbers are converted to “Strings” to avoid truncation and precision losses.

Integer numbers (such as trade ID and sequences) are unquoted.

IDs

Identifiers are UUID unless otherwise specified. When making a request which requires a UUID, both forms (with or without dashes) are accepted.

132fb6ae-456b-4654-b4e0-d681ac05cea1 or 132fb6ae456b4654b4e0d681ac05cea1

Endpoints

This section explains the endpoint details:

  • Public Endpoints
  • Private Endpoints

Public Endpoints

Public APIs are available for acquiring market data and information. Reqeusts to public endpoints do not require any authentications.

Private Endpoints

Private endpoints are used to manage your account and orders. Every request to private endpoints must be signed with a valid authentication scheme using your API key. You can generate API keys here.

Rate Limits

This section explains the rate limit details for the following:

  • REST API
  • WebSocket

To prevent abuse, OKEx imposes rate limits on incoming requests. When a rate limit is exceeded, a status of 429: Too Many Requests will be returned.

REST API

User ID is used for rate limiting if your requests are made via a valid API Key. If your requests are made via the public API, the the public IP will used for rate limiting.

The rate limit is specified in the documentation for each endpoint. If not specified, the limit is 6 times per second.

WebSocket

The WebSocket throttles the number of incoming messages to 50 commands per second.

Authentication

This section explains the authentication details:

  • Generating an API Key
  • Making Requests
  • Signing Messages
  • Timestamps
  • Getting Server Time

Generating an API Key

Before being able to sign any requests, you must create an API key on OKEx. Upon creating a key you will have 3 pieces of information which you must remember:

API Key

Secret

Passphrase

The API Key and Secret will be randomly generated and provided by OKEx; the Passphrase will be provided by you to further secure your API access. OKEx stores the salted hash of your passphrase for authentication, but cannot recover the passphrase if you lose it.

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 timestamp of your request.

OK-ACCESS-PASSPHRASE The passphrase you specified when creating the API key.

All request bodies should have content type application/json and must be valid JSON.

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 Secret
  • sign the prehash string with the Secret using the HMAC SHA256
  • encode the signature in the base64 format

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

The timestamp value is the same as the OK-ACCESS-TIMESTAMP header with nanometer precision.

The request method should be UPPER CASE, i.e. GET and POST.

The requestPath is the path of requesting an endpoint.

Example: /orders?before=2&limit=30

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

Example: {"product_id":"BTC-USD-0309","order_id":"377454671037440"}

The Secretkey is generated when you create an API Key.

Example: 22582BD0CFF14C41EDBF1AB98506286D

public enum ContentTypeEnum {

    APPLICATION_JSON("application/json"),
    APPLICATION_JSON_UTF8("application/json; charset=UTF-8"),
    // The server does not support types
    APPLICATION_FORM("application/x-www-form-urlencoded; charset=UTF-8"),;


    private String contentType;

    ContentTypeEnum(String contentType) {
        this.contentType = contentType;
    }

    public String contentType() {
        return contentType;
    }
}


public enum HttpHeadersEnum {

    OK_ACCESS_KEY("OK-ACCESS-KEY"),
    OK_ACCESS_SIGN("OK-ACCESS-SIGN"),
    OK_ACCESS_TIMESTAMP("OK-ACCESS-TIMESTAMP"),
    OK_ACCESS_PASSPHRASE("OK-ACCESS-PASSPHRASE"),

    OK_FROM("OK-FROM"),
    OK_TO("OK-TO"),
    OK_LIMIT("OK-LIMIT"),;

    private String header;

    HttpHeadersEnum(String header) {
        this.header = header;
    }

    public String header() {
        return header;
    }
}

import com.okcoin.commons.okex.open.api.config.APIConfiguration;
import com.okcoin.commons.okex.open.api.constant.APIConstants;
import com.okcoin.commons.okex.open.api.enums.ContentTypeEnum;
import com.okcoin.commons.okex.open.api.enums.HttpHeadersEnum;
import com.okcoin.commons.okex.open.api.exception.APIException;
import com.okcoin.commons.okex.open.api.utils.DateUtils;
import com.okcoin.commons.okex.open.api.utils.HmacSHA256Base64Utils;
import okhttp3.*;
import okio.Buffer;

public class APIHttpClient {

    private APIConfiguration config;
    private APICredentials credentials;

    public APIHttpClient(APIConfiguration config, APICredentials credentials) {
        this.config = config;
        this.credentials = credentials;
    }

    public OkHttpClient client() {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        clientBuilder.connectTimeout(this.config.getConnectTimeout(), TimeUnit.SECONDS);
        clientBuilder.readTimeout(this.config.getReadTimeout(), TimeUnit.SECONDS);
        clientBuilder.writeTimeout(this.config.getWriteTimeout(), TimeUnit.SECONDS);
        clientBuilder.retryOnConnectionFailure(this.config.isRetryOnConnectionFailure());
        clientBuilder.addInterceptor((Interceptor.Chain chain) -> {
            Request.Builder requestBuilder = chain.request().newBuilder();
            String timestamp = DateUtils.getUnixTime();
            requestBuilder.headers(headers(chain.request(), timestamp));
            Request request = requestBuilder.build();
            if (this.config.isPrint()) {
                printRequest(request, timestamp);
            }
            return chain.proceed(request);
        });
        return clientBuilder.build();
    }

    private Headers headers(Request request, String timestamp) {
        Headers.Builder builder = new Headers.Builder();
        builder.add(APIConstants.ACCEPT, ContentTypeEnum.APPLICATION_JSON.contentType());
        builder.add(APIConstants.CONTENT_TYPE, ContentTypeEnum.APPLICATION_JSON_UTF8.contentType());
        builder.add(APIConstants.COOKIE, getCookie());
        if (StringUtils.isNotEmpty(this.credentials.getSecretKey())) {
            builder.add(HttpHeadersEnum.OK_ACCESS_KEY.header(), this.credentials.getApiKey());
            builder.add(HttpHeadersEnum.OK_ACCESS_SIGN.header(), sign(request, timestamp));
            builder.add(HttpHeadersEnum.OK_ACCESS_TIMESTAMP.header(), timestamp);
            builder.add(HttpHeadersEnum.OK_ACCESS_PASSPHRASE.header(), this.credentials.getPassphrase());
        }
        return builder.build();
    }

    private String getCookie() {
        StringBuilder cookie = new StringBuilder();
        cookie.append(APIConstants.LOCALE).append(this.config.getI18n().i18n());
        return cookie.toString();
    }

    private String sign(Request request, String timestamp) {
        String sign;
        try {
            sign = HmacSHA256Base64Utils.sign(timestamp, method(request), requestPath(request),
                    queryString(request), body(request), this.credentials.getSecretKey());
        } catch (IOException e) {
            throw new APIException("Request get body io exception.", e);
        } catch (CloneNotSupportedException e) {
            throw new APIException("Hmac SHA256 Base64 Signature clone not supported exception.", e);
        } catch (InvalidKeyException e) {
            throw new APIException("Hmac SHA256 Base64 Signature invalid key exception.", e);
        }
        return sign;
    }

    private String url(Request request) {
        return request.url().toString();
    }

    private String method(Request request) {
        return request.method().toUpperCase();
    }

    private String requestPath(Request request) {
        String url = url(request);
        url = url.replace(this.config.getEndpoint(), APIConstants.EMPTY);
        String requestPath = url;
        if (requestPath.contains(APIConstants.QUESTION)) {
            requestPath = requestPath.subString(0, url.lastIndexOf(APIConstants.QUESTION));
        }
        if(this.config.getEndpoint().endsWith(APIConstants.SLASH)){
            requestPath = APIConstants.SLASH + requestPath;
        }
        return requestPath;
    }

    private String queryString(Request request) {
        String url = url(request);
        String queryString = APIConstants.EMPTY;
        if (url.contains(APIConstants.QUESTION)) {
            queryString = url.subString(url.lastIndexOf(APIConstants.QUESTION) + 1);
        }
        return queryString;
    }

    private String body(Request request) throws IOException {
        RequestBody requestBody = request.body();
        String body = APIConstants.EMPTY;
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            body = buffer.readString(APIConstants.UTF_8);
        }
        return body;
    }
}



import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;

import java.util.List;

interface FuturesMarketAPI {

    @GET("/api/futures/v3/products/{instrument_id}/candles")
    Call<JSONArray> getProductCandles(@Path("instrument_id") String productId, @Query("start") String start, @Query("end") String end, @Query("granularity") String granularity);

}

import com.alibaba.fastjson.JSONArray;
import com.okcoin.commons.okex.open.api.bean.futures.result.*;
import com.okcoin.commons.okex.open.api.client.APIClient;
import com.okcoin.commons.okex.open.api.config.APIConfiguration;
import com.okcoin.commons.okex.open.api.service.futures.FuturesMarketAPIService;



public class FuturesMarketAPIServiceImpl implements FuturesMarketAPIService {

    private APIClient client;
    private FuturesMarketAPI api;

    public FuturesMarketAPIServiceImpl(APIConfiguration config) {
        this.client = new APIClient(config);
        this.api = client.createService(FuturesMarketAPI.class);
    }

    @Override
    public JSONArray getProductCandles(String productId, long start, long end, long granularity) {
        return this.client.executeSync(this.api.getProductCandles(productId, String.valueOf(start), String.valueOf(end), String.valueOf(granularity)));
    }

}

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

public class APIClient {

    /**
     * Synchronous send request
     */
    public <T> T executeSync(Call<T> call) {
        try {
            Response<T> response = call.execute();
            if (this.config.isPrint()) {
                printResponse(response);
            }
            int status = response.code();
            String message = new StringBuilder().append(response.code()).append(" / ").append(response.message()).toString();
            if (response.isSuccessful()) {
                return response.body();
            } else if (APIConstants.resultStatusArray.contains(status)) {
                HttpResult result = JSON.parseObject(new String(response.errorBody().bytes()), HttpResult.class);
                result.setStatusCode(status);
                throw new APIException(result.message());
            } else {
                throw new APIException(message);
            }
        } catch (IOException e) {
            throw new APIException("APIClient executeSync exception.", e);
        }
    }

}

public class FuturesAPIBaseTests extends BaseTests {

    public APIConfiguration config() {
        APIConfiguration config = new APIConfiguration();

        config.setEndpoint("https://www.okex.com/");
        config.setApiKey("");
        config.setSecretKey("");

        config.setPassphrase("");
        config.setPrint(true);
        config.setI18n(I18nEnum.ENGLISH);

        return config;
    }

    String productId = "BTC-USD-180928";
}



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.okcoin.commons.okex.open.api.bean.futures.result.*;
import com.okcoin.commons.okex.open.api.service.futures.FuturesMarketAPIService;
import com.okcoin.commons.okex.open.api.service.futures.impl.FuturesMarketAPIServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class FuturesMarketAPITests extends FuturesAPIBaseTests {

    private FuturesMarketAPIService marketAPIService;

    @Before
    public void before() {
        config = config();
        marketAPIService = new FuturesMarketAPIServiceImpl(config);
    }

    @Test
    public void testGetProductCandles() {
        long start = System.currentTimeMillis();
        long end = System.currentTimeMillis() + 2000L;
        JSONArray array = marketAPIService.getProductCandles(productId, 1530323640000L, 0, 180L);
        toResultString(LOG, "Product-Candles", array);
    }


}
package okex

import (
    "bytes"
    "errors"
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
    "Strings"
    "time"
)

type Client struct {
    Config     Config
    HttpClient *http.Client
}

type ApiMessage struct {
    Message String `json:"message"`
}

/*
 Get a http client
*/
func NewClient(config Config) *Client {
    var client Client
    client.Config = config
    timeout := config.TimeoutSecond
    if timeout <= 0 {
        timeout = 30
    }
    client.HttpClient = &http.Client{
        Timeout: time.Duration(timeout) * time.Second,
    }
    return &client
}

/*
 Send a http request to remote server and get a response data
*/
func (client *Client) Request(method String, requestPath String,
    params, result interface{}) (response *http.Response, err error) {
    config := client.Config
    // uri
    endpoint := config.Endpoint
    if Strings.HasSuffix(config.Endpoint, "/") {
        endpoint = config.Endpoint[0:len(config.Endpoint)-1]
    }
    url := endpoint + requestPath

    // get json and bin styles request body
    var jsonBody String
    var binBody = bytes.NewReader(make([]byte, 0))
    if params != nil {
        jsonBody, binBody, err = ParseRequestParams(params)
        if err != nil {
            return response, err
        }
    }

    // get a http request
    request, err := http.NewRequest(method, url, binBody)
    if err != nil {
        return response, err
    }

    // Sign and set request headers
    timestamp := IsoTime()
    preHash := PreHashString(timestamp, method, requestPath, jsonBody)
    sign, err := HmacSha256Base64Signer(preHash, config.SecretKey)
    if err != nil {
        return response, err
    }
    Headers(request, config, timestamp, sign)

    if config.IsPrint {
        printRequest(config, request, jsonBody, preHash)
    }

    // send a request to remote server, and get a response
    response, err = client.HttpClient.Do(request)
    if err != nil {
        return response, err
    }
    defer response.Body.Close()

    // get a response results and parse
    status := response.StatusCode
    message := response.Status
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        return response, err
    }

    if config.IsPrint {
        printResponse(status, message, body)
    }

    response.Header.Add(ResultJsonString, String(body))

    if status >= 200 && status < 300 {
        if body != nil && result != nil {
            err := JsonBytes2Struct(body, result)
            if err != nil {
                return response, err
            }
        }
        return response, nil
    } else if status == 400 || status == 401 || status == 500 {
        if body != nil {
            var apiMessage ApiMessage
            err := JsonBytes2Struct(body, &apiMessage)
            if err != nil {
                return response, err
            }
            message = strconv.Itoa(status) + " " + apiMessage.Message
        }
        return response, errors.New(message)
    } else {
        return response, errors.New(message)
    }
    return response, nil
}

type Config struct {
    // Rest api endpoint url. eg: http://www.okex.com/
    Endpoint String
    // The user's api key provided by OKEx.
    ApiKey String
    // The user's secret key provided by OKEx. The secret key used to sign your request data.
    SecretKey String
    // The Passphrase will be provided by you to further secure your API access.
    Passphrase String
    // Http request timeout.
    TimeoutSecond int
    // Whether to print API information
    IsPrint bool
    // Internationalization @see file: constants.go
    I18n String
}

func (client *Client) GetFuturesProductCandles(productId String, start, end, granularity int64) ([][] float64, error) {
    var candles [][] float64
    params := NewParams()
    params["start"] = Int642String(start)
    params["end"] = Int642String(end)
    params["granularity"] = Int642String(granularity)
    requestPath := BuildParams(FuturesPathPrefix+"products/"+productId+"/candles", params)
    _, err := client.Request(GET, requestPath, nil, &candles)
    return candles, err
}


func NewTestClient() *Client {
    // Set OKEX API's config
    var config Config
    config.Endpoint = "https://www.okex.com/"
    config.ApiKey = ""
    config.SecretKey = ""
    config.Passphrase = ""
    config.TimeoutSecond = 45
    config.IsPrint = false
    config.I18n = ENGLISH

    client := NewClient(config)
    return client
}



import "testing"

const (
    productId = "BTC-USD-180928"
    currency  = "BTC"
)

func TestGetFuturesProductCandles(t *testing.T) {
    start := int64(0)
    end := int64(0)
    candles, err := NewTestClient().GetFuturesProductCandles(productId, start, end, 180)
    if err != nil {
        t.Error(err)
    }
    FmtPrintln(GUnitTest+"Futures product candles: ", candles)
}
String OKEXAPI::GetSign(String timestamp, String method, String requestPath, String body) {
    String sign;
    unsigned char * mac = NULL;
    unsigned int mac_length = 0;
    String data = timestamp + method + requestPath + body;
    String key = m_config.SecretKey;
    int ret = HmacEncode("sha256", key.c_str(), key.length(), data.c_str(), data.length(), mac, mac_length);
    sign = base64_encode(mac, mac_length);
    return sign;
}

String OKEXAPI::Request(const String &method, const String &requestPath, const String &params) {
    /************************** set request method ***************************/
    http_request request;
    request.set_method(method);
    /************************** set request uri ***************************/
    uri_builder builder;
    builder.append_path(requestPath);
    request.set_request_uri(builder.to_uri());

    /************************** set request headers ***************************/
    char * timestamp = new char[32];
    timestamp = GetTimestamp(timestamp, 32);
    String sign = GetSign(timestamp, method, builder.to_String(), params);
    request.headers().clear();
    request.headers().add(U("OK-ACCESS-KEY"), m_config.ApiKey);
    request.headers().add(U("OK-ACCESS-SIGN"), sign);
    request.headers().add(U("OK-ACCESS-TIMESTAMP"), timestamp);
    request.headers().add(U("OK-ACCESS-PASSPHRASE"), m_config.Passphrase);
    request.headers().add(U("Accept"), U("application/json"));
    request.headers().set_content_type(U("application/json; charset=UTF-8"));
    request.headers().add(U("Cookie"),U("locale="+m_config.I18n));

    /************************** set request body ***************************/
    request.set_body(params,"application/json; charset=UTF-8");

    /************************** get response ***************************/
    http_response response;
    String str;
    http_client client(m_config.Endpoint);
    response = client.request(request).get();
    str = response.extract_String(true).get();

    delete []timestamp;
    return str;
}


String GetSpotOrdersExample() {
    OKEXAPI okexapi;
    /************************** set config **********************/
    struct Config config;
    config.Endpoint = "https://www.okex.com";
    config.SecretKey = "";
    config.ApiKey = "";
    config.Passphrase = "";
    okapi.SetConfig(config);

    /************************** set parameters **********************/
    String method(GET);
    map<String,String> m;
    m.insert(make_pair("productId", "BTC-USD"));
    m.insert(make_pair("status", "all"));

    /************************** request and response **********************/
    String request_path = BuildParams("/api/spot/v3/orders", m);
    return okexapi.Request(method, request_path);
}

String AddSpotOrderExample() {
    OKEXAPI okexapi;
    /************************** set config **********************/
    struct Config config;
    config.Endpoint = "https://www.okex.com";
    config.SecretKey = "";
    config.ApiKey = "";
    config.Passphrase = "";
    okapi.SetConfig(config);

    /************************** set parameters **********************/
    value obj;
    obj["size"] = value::number(1);
    obj["price"] = value::number(8);
    obj["side"] = value::String("buy");
    obj["instrument_id"] = value::String("BTC-USD");

    /************************** request and response **********************/
    String params = obj.serialize();
    return okexapi.Request(POST, "/api/spot/v3/orders", params);
}
}
import hmac
import base64
import requests
import json

CONTENT_TYPE = 'Content-Type'
OK_ACCESS_KEY = 'OK-ACCESS-KEY'
OK_ACCESS_SIGN = 'OK-ACCESS-SIGN'
OK_ACCESS_TIMESTAMP = 'OK-ACCESS-TIMESTAMP'
OK_ACCESS_PASSPHRASE = 'OK-ACCESS-PASSPHRASE'
APPLICATION_JSON = 'application/json'


# signature
def signature(timestamp, method, request_path, body, secret_key):
    if str(body) == '{}' or str(body) == 'None':
        body = ''
    message = str(timestamp) + str.upper(method) + request_path + str(body)
    mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
    d = mac.digest()
    return base64.b64encode(d)


# set request header
def get_header(api_key, sign, timestamp, passphrase):
    header = dict()
    header[CONTENT_TYPE] = APPLICATION_JSON
    header[OK_ACCESS_KEY] = api_key
    header[OK_ACCESS_SIGN] = sign
    header[OK_ACCESS_TIMESTAMP] = str(timestamp)
    header[OK_ACCESS_PASSPHRASE] = passphrase
    return header


def parse_params_to_str(params):
    url = '?'
    for key, value in params.items():
        url = url + str(key) + '=' + str(value) + '&'

    return url[0:-1]


# request example
# set the request url
base_url = 'https://www.okex.com'
request_path = '/api/account/v3/currencies'
# set request header
header = get_header('your_api_key', signature('timestamp', 'GET', request_path, 'your_secret_key'), 'timestamp', 'your_passphrase')
# do request
response = requests.get(base_url + request_path, headers=header)
# json
print(response.json())

# [{
#     "id": "BTC",
#     "name": “Bitcoin”,
#      "deposit": "1",
#      "withdraw": “1”,
#       “withdraw_min”:”0.000001btc”
# }, {
#     "id": "ETH",
#     "name": “Ethereum”,
#     "deposit": "1",
#      "withdraw": “1”,
#      “withdraw_min”:”0.0001eth”
#     }
#  …
# ]


########################################################
# take order
base_url = 'https://www.okex.com'
request_path = '/api/spot/v3/orders'

# request params
params = {'type': 'market', 'side': 'buy', 'instrument_id': 'usdt_okb', 'size': '10', 'client_oid': '',
                  'price': '10', 'funds': ''}

# request path
request_path = request_path + parse_params_to_str(params)
url = base_url + request_path

# request header and body
header = get_header('your_api_key', signature('timestamp', 'POST', request_path, 'your_secret_key'), 'timestamp', 'your_passphrase')
body = json.dumps(params)

# do request
response = requests.post(url, data=body, headers=header)

#########################################################
# get order info
base_url = 'https://www.okex.com'
request_path = '/api/spot/v3/orders'

params = {'status':'all', 'instrument_id': 'okb_usdt'}

# request path
request_path = request_path + parse_params_to_str(params)
url = base_url + request_path

# request header and body
header = get_header('your_api_key', signature('timestamp', 'GET', request_path, 'your_secret_key'), 'timestamp', 'your_passphrase')

# do request
response = requests.get(url, headers=header)

Timestamp

The OK-ACCESS-TIMESTAMP request header must be in the UTC time zone Unix timestamp decimal seconds format or the ISO8601 standard time format. It needs to be accurate to milliseconds.

Requests that have a 30+ second difference between the timestamp and the API service time will be considered expired or rejected. We recommend using the time endpoint to query for the API server time if you believe there many be time skew between your server and the API servers.

Getting Server Time

API server time. This is a public endpoint, no verification is required.

HTTP Requests

GET /api/general/v3/time

Rate limit:20/2s
Return Parameters
Parameters Description
iso ISO 8601 format
epoch Unix Epoch in UTC
Return Sample
{

"iso": "2015-01-07T23:47:25.201Z",

"epoch": 1420674445.201

}

Funding Account API

The Funding Account API is used to transfer funds among the main account, sub accounts and various trading accounts, as well as getting deposit addresses and making withdrawals.

Get Balance

This retrieves information on the balances of all the assets, and the amount that is available or on hold.

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/wallet

Example Request

GET /api/account/v3/wallet

Response
Parameters Parameters Types Description
currency String Token symbol, e.g. 'BTC'
balance String Remaining balance
hold String Amount on hold (unavailable)
available String Amount available
Example Response

    {
        "available":37.11827078,
        "balance":37.11827078,
        "currency":"EOS",
        "hold":0
    },
    {
        "available":0,
        "balance":0,
        "currency":"XMR",
        "hold":0
    }

Get Currency

This retrieves information for a single token in your account, including the remaining balance, and the amount available or on hold.

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/wallet/&lt;currency&gt;

Request Sample

GET /api/account/v3/wallet/XMR

Response
Parameters Parameter Type Description
balance String Remaining balance
hold String Amount on hold (unavailable)
available String Amount available
currency String Token symbol, e.g. 'BTC'
Response Sample
{
    "currency":"XMR",
    "available":0.00049136,
    "balance":0.00049136,
    "hold":0
}

Funds Transfer

This endpoint supports the transfer of funds among your funding account, trading accounts, main account, and sub accounts.

Limit: 1 request per 2 seconds (per currency)
HTTP Request

POST /api/account/v3/transfer

Example Request

POST /api/account/v3/transfer{"amount":0.0001,"currency":"eos","from":6,"to":5,"instrument_id":"eos-usdt"}

Parameters
Parameter Type Required Description
currency String Yes Token symbol, e.g., ‘EOS’
amount String Yes Amount to be transferred
from String Yes Remitting account (0: sub account 1: spot 3: futures 4:C2C 5: margin 6: Funding Account 8:PiggyBank 9:swap)
to String Yes Receiving account(0: sub account 1:spot 3: futures 4:C2C 5: margin 6: Funding Account 8:PiggyBank 9 :swap)
sub_account String No Name of the sub account
instrument_id String No margin trading pair of token transferred out, e.g. EOS-USDT. Limited to trading pairs available for margin trading
to_instrument_id String No margin trading pair of token to be transferred in, e.g. EOS-BTC. Limited to trading pairs available for margin trading
Return Parameters
Parameters Parameters Types Description
transfer_id String Transfer ID
currency String Token to be transferred
from String The remitting account
amount String Transfer amount
to String The beneficiary account
result Boolean Transfer result. An error code will be displayed if it failed.
Notes

When from or to is 0, sub account parameter is required.

When from is 0, to can only be 6 as the sub account can only be transferred to the main account.

When from is 6, and to is 1-9, and the sub_account is specified, funds may be transferred from the main account to the sub account's corresopnding spot or margin account directly.

When from or to is 5, instrument_id is required.

Example Response\
{
    "transfer_id": 754147,
    "currency”:"ETC”
    "from": 6,
    "amount": 0.1,
    "to”: 1,
    "result": true
}

Withdrawal

This endpoint supports the withdrawal of tokens

Limit: 20 requests per 2 seconds
HTTP Request

`POST /api/account/v3/withdrawal

Example Request

POST /api/account/v3/withdrawal{"amount":1,"fee":0.0005,"trade_pwd":"123456","destination":4,"currency":"btc","to_address":"17DKe3kkkkiiiiTvAKKi2vMPbm1Bz3CMKw"}`

Request Parameters
Parameters Parameters Types Required Description
currency String Yes Token symbol, e.g., 'BTC'
amount String Yes Withdrawal amount
destination String Yes withdrawal address(2:OKCoin International 3:OKEx 4:others 68.CoinAll )
to_address String Yes Verified digital currency address, email or mobile number. Some digital currency addresses are formatted as 'address+tag', e.g. 'ARDOR-7JF3-8F2E-QUWZ-CAN7F:123456'
trade_pwd String Yes Fund password
fee String Yes Network transaction fee. Withdrawals to OKCoin or OKEx are free, please set fee as 0. Withdrawals to external digital currency addresses require fees. Please refer to the withdrawal fees section below for recommended fee amount
Notes

About tag: Some token deposits requires a deposit address and a tag (AKA Memo/Payment ID), which is a string that guarantees the uniqueness of your deposit address. Please follow the deposit procedure carefully, or you may risk losing your assets

Response
Parameters Parameters Types Description
currency String Token symbol, e.g., 'BTC'
amount String Withdrawal amount
withdraw_id String Withdrawal ID
result boolean Wthdrawal result. An error code will be displayed if it failed.
Example Response
{
    "amount":0.1,
    "withdrawal_id":67485,
    "currency":"btc",
    "result":true
}

Withdrawal History

This retrieves up to 100 recent withdrawal records.

Limit: 20 requests per 2 seconds

HTTP Request

GET /api/account/v3/withdrawal/history

Example Request

GET /api/account/v3/withdrawal/history

Response
Parameter Type Description
currency String Token symbol, e.g., 'BTC'
amount String Token amount
timestamp String Time the withdrawal request was submitted
from String Remitting address (User account ID will be shown for OKEx addresses)
to String Receiving address
tag String Some tokens require a tag for withdrawals. This is not returned if not required
payment_id String Some tokens require payment ID for withdrawals. This is not returned if not required
txid String Hash record of the withdrawal. This parameter will not be returned for internal transfers
fee String Withdrawal fee
status String Status of withdrawal. -3:pending cancel; -2: cancelled; -1: failed; 0:pending; 1:sending; 2:sent; 3:awaiting email verification; 4:awaiting manual verification; 5:awaiting identity verification
withdraw_id String Withdrawal ID
Notes

When the remitting account is an OKEx account, the user account ID is shown instead of the digital currency address. If the receiving account is also an OKEx account, the txid will not be returned.

Up to 100 recent withdrawal records will be returned. To retrieve more records, refer to the the withdrawal history of a specific currency.

Please note that the transactions shown may not be confirmed on the blockchain yet. Please be patient if the funds have not arrived at the receiving address.

Example Response

    {
        "amount":0.094,
        "fee":"0.01000000eth",
        "txid":"0x62477bac6509a04512819bb1455e923a60dea5966c7caeaa0b24eb8fb0432b85",
        "currency":"ETH",
        "from":"13426335357",
        "to":"0xA41446125D0B5b6785f6898c9D67874D763A1519",
        "timestamp":"2018-04-22T23:09:45.000Z",
        "status":2
    },
    {
        "amount":0.01,
        "fee":"0.00000000btc",
        "txid":"",
        "currency":"BTC",
        "from":"13426335357",
        "to":"13426335357",
        "timestamp":"2018-05-17T02:43:08.000Z",
        "status":2
    }

Withdrawal History of a Currency

This retrieves the withdrawal records of a specific currency.

Limit: 20 requests per 2 seconds

HTTP Request

GET /api/account/v3/withdrawal/history/&lt;currency&gt;

Example Request

GET /api/account/v3/withdrawal/history/btc

Parameters
Parameters Parameters Types Required Description
currency String Yes Token symbol
Response
Parameters Parameters Types Description
currency String Token symbol
amount number Withdrawal amount
timestamp String Time the withdrawal request was submitted
from String Remitting address (User account ID will be shown for OKEx addresses)
to String Receiving address
tag String Some tokens require a tag for withdrawals. This is not returned if not required
payment_id String Some tokens require payment ID for withdrawals. This is not returned if not required
txid String Hash record of the withdrawal. This parameter will not be returned for internal transfers
fee String withdrawal fee
status String Status of withdrawal. -3:pending cancel; -2: cancelled; -1: failed; 0:pending; 1:sending; 2:sent; 3:awaiting email verification; 4:awaiting manual verification; 5:awaiting identity verification
withdraw_id String Withdrawal ID
Notes

When the remitting account is an OKEx account, the user account ID is shown instead of the digital currency address. If the receiving account is also an OKEx account, the txid will not be returned.

Up to 100 recent withdrawal records will be returned. To retrieve more records, refer to the Pagination section to retrieve previous records.

Please note that the transactions shown may not be confirmed on the blockchain yet. Please be patient if the funds have not arrived at the receiving address.

Example Response
    {
        "amount":0.01105486,
        "fee":"0.00000000btc",
        "from":"13426335357",
        "to":"13426335357",
        "timestamp":"2018-09-30T02:49:29.000Z",
        "status":2
    },
    {
        "amount":0.01144408,
        "fee":"0.00000000btc",
        "from":"13426335357",
        "to":"13426335357",
        "timestamp":"2018-09-18T00:44:56.000Z",
        "status":2
    }

Bills Details

This endpoint retrieves the bill details of the Funding Account. All the information will be paged and sorted in reverse chronological order, which means the latest will be at the top. Please refer to the pagination section for additional records after the first page. 1 months recent records will be returned at maximum

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/ledger

Example Request

GET /api/account/v3/ledger?type=2&currency=btc&from=4&limit=10

Parameters
Parameters Parameters Types Required Description
currency String No The token symbol, e.g. 'BTC'. Complete account statement for will be returned if the field is left blank
type String No 1:deposit 2:withdrawal 13:cancel withdrawal 18: into futures account 19: out of futures account 20:into sub account 21:out of sub account 28: claim 29: into ETT account 30: out of ETT account 31: into C2C account 32:out of C2C account 33: into margin account 34: out of margin account 37: into spot account 38: out of spot account
after String No Pagination of data to return records earlier than the requested ledger_id
before String No Pagination of data to return records newer than the requested ledger_id
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
ledger_id String Bill ID
currency String Token symbol
balance String Remaining balance
amount String Amount changed
typename String Type of bills
fee String Service fees
timestamp String Creation time
Example Response
{
        "amount":"0.00100941",
        "balance":0,
        "currency":"BTC",
        "fee":0,
        "ledger_id":9260348,
        "timestamp":"2018-10-19T01:12:21.000Z",
        "typename":"To: spot account"
    },
    {
        "amount":0.00051843,
        "balance":0.00100941,
        "currency":"BTC",
        "fee":0,
        "ledger_id":8987285,
        "timestamp":"2018-10-12T11:01:14.000Z",
        "typename":"Get from activity"
    }

Deposit Address

This retrieves the deposit addresses of currencies, including previously used addresses.

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/deposit/address

Example Request

GET /api/account/v3/deposit/address?currency=btc

Parameters
Parameters Parameters Types Required Description
currency String Yes Token symbol
Response
Parameters Parameters Types Description
address String Deposit address
tag String Deposit tag (This will not be returned if the token does not require a tag for deposit)
payment_id String Deposit payment ID (This will not be returned if the token does not require a payment_id for deposit)
currency String Token symbol
to String The beneficiary account (0: sub account 1:spot 3: futures 4:C2C 5: margin 6: Funding Account 8:PiggyBank 9 :swap)
Notes

Warning: IOTA deposit addresses cannot be reused! Deposits into a previously used IOTA address will not be confirmed and credited.

Tag or payment ID are required for some tokens. Please include them while making deposits to ensure the your funds will be properly credited.

Example Response

{
    "currency":"btc"
    "address":"dafdsafdsfe",
    "tag":"123",
}, {
    "currency":"btc"
    "address":"dafdsafkkkdsfe",
    "tag”:”xyzddrrrsdfsdf"
}

Deposit History

This retrieves the deposit history of all currencies, up to 100 recent records.

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/deposit/history

Example Request

GET /api/account/v3/deposit/history

Response
Parameters Parameters Types Description
currency String Token Symbol
amount number Deposit amount
to String Deposit address. Only internal OKEx account is returned instead of the digital currency's deposit address
txid String Hash record of the deposit
timestamp String Time that the deposit is credited
status number Status of deposit (0: waiting for confirmation; 1: deposit credited; 2: deposit successful)
Example Response
{
        "amount":0.01044408,
        "txid":"1915737_3_0_0_WALLET",
        "currency":"BTC",
        "to":"",
        "timestamp":"2018-09-30T02:45:50.000Z",
        "status":2
    },
    {
        "amount":491.6784211,
        "txid":"1744594_3_184_0_WALLET",
        "currency":"OKB",
        "to":"",
        "timestamp":"2018-08-21T08:03:10.000Z",
        "status":2
    },
    {
        "amount":223.18782496,
        "txid":"6d892c669225b1092c780bf0da0c6f912fc7dc8f6b8cc53b003288624c",
        "currency":"USDT",
        "to":"39kK4XvgEuM7rX9frgyHoZkWqx4iKu1spD",
        "timestamp":"2018-08-17T09:18:40.000Z",
        "status":2
    }

Get Deposit History of a Currency

This retrieves the deposit history of a currency, up to 100 recent records returned.

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/deposit/history/&lt;currency&gt;

Example Request

GET /api/account/v3/deposit/history/btc

Parameters
Parameters Parameters Types Required Description
currency String Yes Token Symbol
withdraw_id String Yes Withdrawal ID
Response
Parameters Parameters Types Description
amount String Deposit amount
to String Deposit address
txid String Hash record of the deposit
timestamp String Time that the deposit is credited
currency String Token Symbol
status String Status of deposit (0: waiting for confirmation; 1: deposit credited; 2: deposit successful)
withdraw_id String Withdrawal ID
Example Response
[{
 "amount": 2,
 "currency":"USDT",
 "to”:”[0x9edfe04c866d636526828e523a60501a37daf8f6](https://etherscan.io/address/0x9edfe04c866d636526828e523a60501a37daf8f6)", 
 "txid”:"0xf1fb12a03c483f475fc33abcb5bf42a765c7131e2f955025aec706be3f616da4”,
  "status":2,
 "timestamp": "2018-09-20T09:21:26.528Z"
}]

Get Currencies

This retrieves a list of all currencies. Not all currencies can be traded. Currencies that have not been defined in ISO 4217 may use a custom symbol.

Limit: 20 requests per 2 seconds

HTTP Request

GET /api/account/v3/currencies

Request Sample

GET /api/account/v3/currencies

Return Parameters
Parameters Parameters Types Description
currency String Token symbol, e.g., 'BTC'
name String Token name
can_deposit String Availability to deposit, 0 = not available,1 = available
can_withdraw String Availability to withdraw, 0 = not available,1 = available
min_withdrawal String Minimum withdrawal threshold
Return Sample
    {
         "can_deposit":1,
         "can_withdraw":1,
         "currency":"BTC",
         "min_withdrawal":0.01,
         "name":""
     },
     {
         "can_deposit":1,
         "can_withdraw":1,
         "currency":"LTC",
         "min_withdrawal":0.1,
         "name":""
     }

Withdrawal Fees

This retrieves the information about the recommended network transaction fee for withdrawals to digital currency addresses. The higher the fees are set, the faster the confirmations.

HTTP Requests

GET /api/account/v3/withdrawal/fee

Example Request

GET /api/account/v3/withdrawal/fee?currency=btc

Parameters
Parameters Parameters Types Required Description
currency String No Token symbol, e.g. 'BTC', if left blank, information for all tokens will be returned
Response
Parameters Parameters Types Description
currency String Token symbol
min_fee number Minimum withdrawal fee
max_fee number Maximum withdrawal fee
Example Response
{
        "currency":"BTC",
        "max_fee":0.02,
        "min_fee":0.0005
    },
    {
        "currency":"LTC",
        "max_fee":0.2,
        "min_fee":0.001
    },
    {
        "currency":"ETH",
        "max_fee":0.2,
        "min_fee":0.01
    }

Error Code

Error Code Sample
Business Error Messages Business Error Codes http Status Code Scenarios
withdrawal suspended 34001 400 withdrawal endpoint: account suspended
please add a withdrawal address 34002 400 withdrawal endpoint: address required
sorry, this token cannot be withdrawn to xx at the moment 34003 400 withdrawal endpoint: incorrect address
withdrawal fee is smaller than minimum limit 34004 400 withdrawal endpoint: incorrect fee
withdrawal fee exceeds the maximum limit 34005 400 withdrawal endpoint: incorrect withdrawal fee
withdrawal amount is lower than the minimum limit 34006 400 minimum withdrawal amount%} endpoint: incorrect amount
withdrawal amount exceeds the maximum limit 34007 400 maximum withdrawal amount endpoint: incorrect amount
insufficient balance 34008 400 transfer & withdrawal endpoint: insufficient balance
your withdrawal amount exceeds the daily limit 34009 400 withdrawal endpoint: withdrawal limit exceeded
transfer amount must be larger than 0 34010 400 transfer endpoint: incorrect amount
conditions not met 34011 400 transfer & withdrawal endpoint: conditions not met, e.g. KYC level
the minimum withdrawal amount for NEO is 1, and the amount must be an integer 34012 400 withdrawal endpoint: special requirements
please transfer 34013 400 transfer endpoint: Token margin trading instrument ID required
transfer limited 34014 400 transfer endpoint:Transfer limited
subaccount does not exist 34015 400 transfer endpoint: subaccount does not exist
transfer suspended 34016 400 transfer endpoint: either end of the account does not authorize the transfer
account suspended 34017 400 transfer & withdrawal endpoint: either end of the account does not authorize the transfer
incorrect trades password 34018 400 incorrect trades password
please bind your email before withdrawal 34019 400 withdrawal endpoint : email required
please bind your funds password before withdrawal 34020 400 withdrawal endpoint : funds password required
Not verified address 34021 400 withdrawal endpoint
Withdrawals are not available for sub accounts 34022 400 withdrawal endpoint
token does not exist 30031 400 token requested does not exist
Please enable futures trading before transferring your funds 34023 400 Please enable futures trading before transferring your funds
transfer too frequently 34026 400 transfer too frequently
Withdrawal transaction fee should be *% of the withdrawal amount 34027 400 Withdrawal transaction fee should be *% of the withdrawal amount

Spot Trading API

This includes endpoints for retrieving market data, account information, order management, and bills details of your trading account.

Note: Some of the API response parameters may be redundant in order to stay compatible with the older version. Please only reference parameters specified in the API documentation.

For example, the API may return three values for the amount on hold, frozen, hold, and holds. Please use hold as referred in the documentation.

Account Information

This retrieves the list of assets, (with nonzero balance), remaining balance, and amount available in the spot trading account.

Rate limit: 20 requests per 2 seconds
HTTP Requests

GET /api/spot/v3/accounts

Example Request

GET /api/spot/v3/accounts

Return Parameters
Parameters Parameters Types Description
currency String Token symbol
balance String Remaining balance
hold String Amount on hold (not available)
available String Available amount
Notes

After placing an order, the order amount will be put on hold. After you placed an order, the amount of the order will be put on hold. You will not be able to transfer or use in other orders until the order is completed or cancelled.

Example Response
[
    {
        "frozen":"0",
        "hold":"0",
        "currency":"BTC",
        "balance":"0.0049925",
        "available":"0.0049925",
        "holds":"0"
    },
    {
        "frozen":"0",
        "hold":"0",
        "currency":"USDT",
        "balance":"226.74061435",
        "available":"226.74061435",
        "holds":"0"
    },
    {
        "frozen":"0",
        "hold":"0",
        "currency":"EOS",
        "balance":"0.4925",
        "available":"0.4925",
        "holds":"0"
    }
]

Get Currency

This retrieves information for a single currency in your account, including the remaining balance, and the amount available or on hold.

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/wallet/&lt;currency&gt;

Request Sample

GET /api/account/v3/wallet/XMR

Parameters
Parameters Parameters Types Description
currency String [required] Token symbol
Return Parameters
Parameters Parameters Types Description
balance String Remaining balance
hold String Amount on hold (unavailable)
available String Amount available
currency String Token symbol, e.g. 'BTC'
id String Account ID
Example Response

{
    "frozen":"0",
    "hold":"0",
    "id":"9150707",
    "currency":"BTC",
    "balance":"0.0049925",
    "available":"0.0049925",
    "holds":"0"
}

Bills Details

This retrieves the account bills dating back the past 3 monhts.

Limit: 20 requests per 2 seconds
HTTP Requests

GET /api/spot/v3/accounts/&lt;currency&gt;/ledger

Example Request

GET /api/account/v3/ledger?type=2&currency=btc&from=4&limit=10

Parameters
Parameters Parameters Types Required Description
currency String No The token symbol, e.g. 'BTC'. Complete account statement for will be returned if the field is left blank
after String No Pagination of data to return records earlier than the requested ledger_id
before String No Pagination of data to return records newer than the requested ledger_id
limit String No Number of results per request. The maximum is 100; the default is 100
type String No 1 .Deposit 2 .Withdraw 7 .Buy 8 .Sell 9 .Beginner’s Task 10 .Invite friends to complete beginner’s task 11 .扣除任务奖励 12 .Invitation Bonus 13 .Canceled Withdrawal 14 .Deducted for Events 15 .Received from Events 18 .Transfer from Futures 19 .Transfer to Futures 20 .Transfer from Sub-account 21 .Transfer to Sub-account 22 .Transaction Fee Rebate 23 .Receive Red Packet 24 .Send Red Packet 25 .C2C Buy 26 .C2C Sell 27 .Deduct 28 .Convert 29 .Transfer to Assets Account 30 .Transfer from Assets Account 31 .Transfer to C2C Account 32 .Transfer from C2C Account 33 .Transfer to Margin Account 34 .Transfer from Margin Account 35 .Borrow 36 .Repay 37 .Market Maker Bonus 38 .Market Maker Rebate 41 .Fee Settled with LP 42 .Purchase Loyalty Points 43 .Transfer Loyalty Points 44 .MM Program Bonus 45 .MM Program Rebate 46 .Transfer from Spot Account 47 .Transfer to Spot Account 48 .Transfer to ETT 49 .Transfer from ETT 50 .Deducted for mining 51 .Gain from mining 52 .Extra yield 53 .Incentive bonus distribution 55 .Transfer from OK PiggyBank 56 .Transfer to OK PiggyBank 57 .Transfer from Swap Account 58 .Transfer to Swap Account 59 .Repay Bonus 60 .Margin Fee Settled with LP
Response
Parameters Parameters Types Description
ledger_id String Bill ID
balance String Remaining balance
currency String Token symbol
amount String Amount changed
type String Type of bills
timestamp String Creation time
Details String Order details when type is trade or fee
order_id String Order ID
instrument_id String Trading pair
Notes

The following is the enumeration value type

Enumeration Value Description
transfer Funds transferred in/out
trade Funds changed from trades
rebate Fee rebate as per fee schedule
Example Response
[
    {
        "timestamp":"2019-03-18T07:26:50.000Z",
        "ledger_id":"3995466151",
        "created_at":"2019-03-18T07:26:50.000Z",
        "currency":"BTC",
        "amount":"0.0009985",
        "balance":"0.0049925",
        "type":"trade",
        "details":{
            "instrument_id":"BTC-USDT",
            "order_id":"2500723297813504",
            "product_id":"BTC-USDT"
        }
    },
    {
        "timestamp":"2019-03-18T07:26:50.000Z",
        "ledger_id":"3995466150",
        "created_at":"2019-03-18T07:26:50.000Z",
        "currency":"BTC",
        "amount":"0.0009985",
        "balance":"0.003994",
        "type":"trade",
        "details":{
            "instrument_id":"BTC-USDT",
            "order_id":"2500723297223680",
            "product_id":"BTC-USDT"
        }
    },
    {
        "timestamp":"2019-03-18T07:08:25.000Z",
        "ledger_id":"3995334780",
        "created_at":"2019-03-18T07:08:25.000Z",
        "currency":"BTC",
        "amount":"0.0009985",
        "balance":"0.0029955",
        "type":"trade",
        "details":{
            "instrument_id":"BTC-USDT",
            "order_id":"2500650881647616",
            "product_id":"BTC-USDT"
        }
    }
]

Place Order

OKEx spot trading supports only limit and market orders. More order types will become available in the future. You can place an order only if you have enough funds.

Once your order is placed, the amount will be put on hold until the order is executed.

Rate limit: 100 requests per 2 seconds
HTTP Request

POST /api/spot/v3/orders

Example Authenticated Request

POST/api/spot/v3/orders{'type': 'limit', 'side': 'buy', 'instrument_id': 'BTC-USDT', 'size': 0.001, 'client_oid': 'oktspot79', 'price': '4638.51', 'funds': '', 'margin_trading': 1, 'order_type': '3'}

Parameters
Parameter Type Required Description
client_oid String No Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
type String No Supports types limit or market (default: limit). When placing market orders, order_type must be 0 (normal order)
side String Yes Specify buy or sell
instrument_id String Yes Trading pair symbol
order_type String No Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
Limit Order Parameters
Parameter Type Required Description
price String Yes Price
size String Yes Quantity to buy or sell
Market Order Parameters
Parameters Parameters Types Required Description
size String Yes Quantity to be sold. Required for market sells
notional String Yes Amount to spend. Required for market buys
Response
Parameters Type Description
order_id String Order ID
client_oid String Client-supplied order ID
result Boolean Result of the order. Error message will be returned if the order failed.
error_code String Error code; blank if order placed successfully
error_message String Error message; blank if order placed successfully
Notes

client_oid

The client_oid is optional. It should be a unique ID generated by your trading system. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

instrument_id

The instrument_id must match a valid instrument. The instruments list is available via the /instrument endpoint

type

You can specify the order type when placing an order. The order type you specify will decide which order parameters are required further as well as how your order will be executed by the matching engine. If type is not specified, the order will default to a limit order. Limit order is the default order type, and it is also the basic order type. A limit order requires specifying a price and size. The limit order will be filled at the specifie price or better. Specifically, A sell order can be filled at the specified or higher price per the quote token. A buy order can be filled at the specified or lower price per the quote token. If the limit order is not filled immediately, it will be sent into the open order book until filled or canceled. Market orders differ from limit orders in that they have NO price specification. It provides an order type to buy or sell specific amount of tokens without the need to specify the price. Market orders execute immediately and will not be sent into the open order book. Market orders are always considered as ‘takers’ and incur taker fees. Warming: Market order is strongly discouraged and if an order to sell/buy a large amount is placed it will probably cause turbulence in the market.

price

The price must be specified in unit of quote_increment which is the smallest incremental unit of the price. It can be acquired via the /instrument endpoint.

size

Size is the quantity of buying or selling and must be larger than the min_size. size_increment is the minimum increment size. It can be acquired via the /instrument endpoint.

Example: If the min_size of OKB/USDT is 10 and the size_increment is 0.0001, then it is impossible to trade 9.99 OKB but possible to trade 10.0001 OKB.

notional

The notional field is the quantity of quoted currency when placing market orders; it is required for market orders. For example, a market buy for BTC-USDT with quantity specified as 5000 will spend 5000 USDT to buy BTC.

hold

For limit buy order, we will put a hold the quoted currency, of which the amount on hold = specific price x buying size. For limit sell orders, we will put a hold on the currency equal to the amount you want to sell. For market buy orders, the amount equal to the quantity for the quoted currency will be on hold. For market sell orders, the amount based on the size of the currency you want to sell will be on hold. Cancelling an open order releases the amount on hold.

Order life cycle

The HTTP Request will respond when an order is either rejected (insufficient funds, invalid parameters, etc) or received (accepted by the matching engine). A 200 response indicates that the order was received and is active. Active orders may execute immediately (depending on price and market conditions) either partially or fully. A partial execution will put the remaining size of the order in the open state. An order that is filled completely, will go into the completed state.

Users listening to streaming market data are encouraged to use the client_oid field to identify their received messages in the feed. The REST response with a server order_id may come after the received message in the public data feed.

Response

A successful order will be assigned an order id. A successful order is defined as one that has been accepted by the matching engine. Open orders will not expire until filled or canceled.

Example Response
{
    "client_oid":"oktspot79",
    "error_code":"",
    "error_message":"",
    "order_id":"2510789768709120",
    "result":true
}

Batch Orders

This supports placing multiple orders in batches for up to 4 trading pairs and a maximum of 10 orders per trading pair can be placed at a time.

Rate limit: 50 requests per 2 seconds
HTTP Request

POST /api/spot/v3/batch_orders

Example Request

2018-09-14T09:51:24.959ZPOST/api/spot/v3/batch_orders[{"client_oid":"ww20180728","instrument_id":"btc-usdt","side":"sell","type":"limit","size":"0.001","price":"10001","margin_trading ":"1"},{"client_oid":"w20180728","instrument_id":"btc-usdt","side":"sell","type":"limit","size":"0.001","price":"10002","margin_trading ":"1"}]

Parameters
Parameter Type Required Description
client_oid String No Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
type String Yes Supports types limit or market (default: limit). When placing market orders, order_type must be 0 (normal order)
side String Yes Specify buy or sell
instrument_id String Yes Trading pair symbol
order_type String No Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
Limit Order Parameters
Parameter Type Required Description
price String Yes Price
size String Yes Quantity to buy or sell
Market Order Parameters
Parameters Parameters Types Required Description
size String Yes Quantity to be sold. Required for market sells
notional String Yes Amount to spend. Required for market buys
Response
Parameters Type Description
order_id String Order ID
client_oid String Client-supplied order ID
result Boolean Result of the order. Error message will be returned if the order failed.
error_code String Error code; blank if order placed successfully
error_message String Error message; blank if order placed successfully
Notes

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

You may place batch orders for up to 4 trading pairs, each with 10 orders at maximum. If you cancel the batch orders, you should confirm they are successfully canceled by requesting the "Get Order List" endpoint.

Example Response
{
    "btc_usdt":[
        {
            "client_oid":"oktspot80",
            "error_code":0,
            "error_message":"",
            "order_id":"2510832677159936",
            "result":true
        },
        {
            "client_oid":"oktspot81",
            "error_code":0,
            "error_message":"",
            "order_id":"2510832677225472",
            "result":true
        },
        {
            "client_oid":"oktspot82",
            "error_code":0,
            "error_message":"",
            "order_id":"2510832677225473",
            "result":true
        }
    ]
}

Cancel Order

This is used to cancel an unfilled order.

Rate limit: 100 requests per 2 seconds
HTTP Request

POST /api/spot/v3/cancel_orders/&lt;order_id or client_oid&gt;

Example Request with Authentication

2018-10-12T07:34:30.223ZPOST/api/spot/v3/cancel_orders/a123{"instrument_id":"btc-usdt"}

Parameters
Parameter Type Required Description
instrument_id String Yes Specify the trading pair to cancel the corresponding order. An error would be returned if the parameter is not provided.
client_oid String No Either client_oids or order_ids must be present. Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
order_id String No Either client_oids or order_ids must be present. Order ID
Response
Parameter Type Description
order_id String Order ID
client_oid String Client-supplied order ID
result Boolean Call interface returns results. Error code will be returned if failed
error_code String Error code for order placement
error_message String Error message will be returned if order placement fails. It will be blank if order placement is successful.
Notes

Only one of order_id or client_oid parameters should be passed per request

The client_oid should be unique. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

If the order cannot be canceled because it has already filled or been canceled, the reason will be returned with the error message.

Example Response
{
    "btc-usdt":[
    {
       "result":true,
        "client_oid":"a123",
        "order_id": "2510832677225473"
     }
]
}

Cancel Multiple Orders

Cancel multiple open orders with order_id or client_oid. Up to 4 trading pairs, and maximum 10 orders can be placed at a time for each trading pair.

Rate limit: 20 requests per 2 seconds
HTTP Requests

POST /api/spot/v3/cancel_batch_orders

Example Request with Authentication

2018-10-12T07:30:49.664ZPOST/api/spot/v3/cancel_batch_orders[{"instrument_id":"btc-usdt","client_oids":["a123","a1234"]},{"instrument_id":"ltc-usdt","client_oids":["a12345","a123456"]}]

Parameters
Parameter Type Required Description
order_ids list<String> No Either client_oids or order_ids must be present. Order ID
instrument_id String Yes by providing this parameter, the corresponding order of a designated trading pair will be cancelled. If not providing this parameter, it will be back to error code.
client_oids String No Either client_oids or order_ids must be present. Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
Response
Parameter Type Description
order_id list<String> Order ID
client_oid String Client-supplied order ID
instrument_id String Trading pair symbol
result Boolean Call interface returns results. Error code will be returned if failed
Notes

For batch order cancellation, only one of order_id or client_oid parameters should be passed per request. Otherwise an error will be returned.

When using client_oid for batch order cancellation, only one client_oid is canceled per trading pair, and up to a maximum of 4 trading pairs can be processed per request. You need to make sure the ID is unique. In case of multiple identical client_oid, only the latest entry will be returned.

Using order_id you may cancel orders for up to 4 trading pairs, each with 10 orders at maximum. After placing a cancel order you should confirm they are successfully canceled by requesting the "Get Order List" endpoint.

Example Response
{
    "btc-usdt":[
    {
       "result":true,
        "client_oid":"a123",
        "order_id": "2510832677225473"
     },
   {
       "result":true,
        "client_oid":"a1234",
        "order_id": "2510832677225474"
     }
],
"ltc-usdt":[
    {
       "result":true,
        "client_oid":"a12345",
        "order_id": "2510832677225475"
     },
   {
       "result":true,
        "client_oid":"a123456",
        "order_id": "2510832677225476"
     }
]
}

Order List

This retrieves the list of your orders from the most recent 3 months. This request supports paging and is stored according to the order time in chronological order from latest to earliest.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/orders

Example Authenticated Request

2019-03-18T07:49:43.306ZGET/api/spot/v3/orders?instrument_id=BTC-USDT&state=filled&limit=2&&after=2500723297223680

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pair symbol
state String Yes Order Status: -2 = Failed -1 = Canceled 0 = Open 1 = Partially Filled 2 = Completely Filled 3 = Submitting 4 = Canceling 6 = Incomplete (open + partially filled) 7 = Complete (canceled + completely filled)
after String Yes Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String Yes Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String Yes Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
order_id String Order ID
client_oid String Client-supplied order ID
price String Price of order
size String Size of order in unit of quote currency
notional String Allocated amount to buy (for market orders)
instrument_id String Trading pair symbol
type String Order type: limit or market (default: limit)
side String Buy or sell
timestamp String Time of order creation
filled_size String Quantity filled
filled_notional String Amount filled
order_type String Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
state String Order Status: -2 = Failed -1 = Canceled 0 = Open 1 = Partially Filled 2 = Completely Filled 3 = Submitting 4 = Canceling
price_avg String Average filled price
Notes

status is the older version of state and both can be used interchangeably in the short term. It is recommended to switch to state.

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

If the order is not filled in the order life cycle, the record may be removed.

The status of unfilled orders may change during the time of endpoint request and response, depending on the market condition.

Example Response
[
    [
        {
            "client_oid":"oktspot76",
            "created_at":"2019-03-18T07:26:49.000Z",
            "filled_notional":"3.9734",
            "filled_size":"0.001",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2500723297813504",
            "order_type":"0",
            "price":"4013",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "status":"filled",
             "state": "2",     
            "timestamp":"2019-03-18T07:26:49.000Z",
            "type":"limit"
        },
        {
            "client_oid":"oktspot75",
            "created_at":"2019-03-18T07:26:49.000Z",
            "filled_notional":"3.9734",
            "filled_size":"0.001",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2500723297223680",
            "order_type":"0",
            "price":"4013",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "status":"filled",
            "state": "2",     
            "timestamp":"2019-03-18T07:26:49.000Z",
            "type":"limit"
        },
        {
            "client_oid":"oktspot74",
            "created_at":"2019-03-18T07:08:24.000Z",
            "filled_notional":"3.9768",
            "filled_size":"0.001",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2500650881647616",
            "order_type":"0",
            "price":"4016.8",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "status":"filled",
            "state": "2",     
            "timestamp":"2019-03-18T07:08:24.000Z",
            "type":"limit"
        }
    ],
    {
        "before":"2500723297813504",
        "after":"2500650881647616"
    }
]

Open Orders

This retrieves the list of your current open orders. Pagination is supported and the response is sorted with most recent first in reverse chronological order.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/orders\_pending

Example Authenticated Request

2018-09-12T07:51:51.138ZGET/api/spot/v3/orders_pending?limit=2&instrument_id=btc-usdt&after=2500723297223680

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pair symbol
after String No Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String No Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
order_id String Order ID
client_oid String Client-supplied order ID
price String Price of order
size String Size of order in unit of quote currency
notional String Amount allocated for buying. This value will be returned for market orders
instrument_id String Trading pair symbol
type String Order type: limit or market (default: limit)
side String Buy or sell
timestamp String Time of order creation
filled_size String Quantity filled
filled_notional String Amount filled
order_type String Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
state String Order Status: 0 = Open
Explanation

The parameter status is the older version of state and is compatible in the short term. It is recommended to switch to state.

The client_oid is optional. It should be a unique ID generated by your trading system. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

Only partially filled and open orders will be returned via this endpoint.

The status of unfilled orders may change during the time of endpoint request and response, depending on the market condition.

Example Response
[
    [
        {
            "client_oid":"oktspot86",
            "created_at":"2019-03-20T03:28:14.000Z",
            "filled_notional":"0",
            "filled_size":"0",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2511109744100352",
            "order_type":"0",
            "price":"3594.7",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "status":"open",
            "state": "0",     
            "timestamp":"2019-03-20T03:28:14.000Z",
            "type":"limit"
        },
        {
            "client_oid":"oktspot85",
            "created_at":"2019-03-20T03:28:10.000Z",
            "filled_notional":"0",
            "filled_size":"0",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2511109459543040",
            "order_type":"0",
            "price":"3594.9",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "status":"open",
            "state": "0",     
            "timestamp":"2019-03-20T03:28:10.000Z",
            "type":"limit"
        }
    ],
    {
        "before":"2511109744100352",
        "after":"2511109459543040"
    }

Order Details

Retrieve order details by order ID. Unfilled orders will be kept in record for only two hours after it is canceled.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/orders/&lt;order_id&gt;

or

GET /api/spot/v3/orders/&lt;client_oid&gt;

Example Authenticated Request

2018-09-12T07:54:01.582ZGET/api/spot/v3/orders/23356?instrument_id=BTC-USDT

or

2018-09-12T07:54:01.582ZGET/api/spot/v3/orders/e23356?instrument_id=BTC-USDT

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pair symbol
order_id String Yes Order ID
client_oid String Yes Client-supplied order ID
Response
Parameters Type Description
order_id String Order ID
client_oid String Client-supplied order ID
price String Price of order
size String Size of order in unit of quote currency
notional String Allocated amount to buy (for market orders)
instrument_id String Trading pair symbol
side String Buy or sell
type String Order type: limit or market (default: limit)
timestamp String Time of order creation
filled_size String Quantity filled
filled_notional String Amount filled
order_type String 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
state String Order Status: -2 = Failed -1 = Canceled 0 = Open 1 = Partially Filled 2 = Completely Filled 3 = Submitting 4 = Canceling
price_avg String Average filled price
Notes

status is the older version of state and both can be used interchangeably in the short term. It is recommended to switch to state.

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

Unfilled order status may change according to the market conditions.

Example Response
{
    "client_oid":"oktspot70",
    "created_at":"2019-03-15T02:52:56.000Z",
    "filled_notional":"3.8886",
    "filled_size":"0.001",
    "funds":"",
    "instrument_id":"BTC-USDT",
    "notional":"",
    "order_id":"2482659399697408",
    "order_type":"0",
    "price":"3927.3",
    "product_id":"BTC-USDT",
    "side":"buy",
    "size":"0.001",
    "status":"filled",
    "state": "2",     
    "timestamp":"2019-03-15T02:52:56.000Z",
    "type":"limit"
}

Transaction Details

Retrieve recently filled transaction details. This request supports paging and is stored according to the transaction time in chronological order from latest to earliest. Data for up to 3 months can be retrieved.

Rate limit: 20 requests per 2 seconds

HTTP Request

GET /api/spot/v3/fills

Example Authenticated Request

2018-09-12T07:56:11.922ZGET/api/spot/v3/fills?order_id=23212&instrument_id=btc-usdt&limit=2&from=2&to=4

Parameters
Parameter Type Required Description
order_id String No Order ID, Complete transaction details for will be returned if the instrument_id is left blank
instrument_id String Yes Trading pair symbol
after String No Pagination of data to return records earlier than the requested order_id
before String No Pagination of data to return records newer than the requested order_id
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
ledger_id String Bill record ID
instrument_id String Trading pair symbol
price String Price
size String Size of order
order_id String Order ID
timestamp String Time of order transaction
exec_type String Taker or maker (T or M)
fee String Transaction fee
side String The side that pays the trading fees, such as buy, sell, or points_fee
Notes

Transaction Fees

New status for spot trading transaction details: fee is either a positive number (invitation rebate) or a negative number (transaction fee deduction).

Liquidity

The exec_type specifies whether the order is maker or taker. ‘M’ stands for Maker and ‘T’ stands for Taker.

Pagination

The ledger_id is listed in a descending order, from biggest to smallest. The first ledger_id in this page can be found under OK-BEFORE, and the last one can be found under OK-AFTER. It would be easier to retrieve to other ledger_id by referring to these two parameters.

Example Response
[
    [
        {
            "created_at":"2019-03-15T02:52:56.000Z",
            "exec_type":"T",
            "fee":"0.00000067",
            "instrument_id":"BTC-USDT",
            "ledger_id":"3963052722",
            "liquidity":"T",
            "order_id":"2482659399697408",
            "price":"3888.6",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.00044694",
            "timestamp":"2019-03-15T02:52:56.000Z"
        },
        {
            "created_at":"2019-03-15T02:52:56.000Z",
            "exec_type":"T",
            "fee":"0.00000082",
            "instrument_id":"BTC-USDT",
            "ledger_id":"3963052721",
            "liquidity":"T",
            "order_id":"2482659399697408",
            "price":"3888.6",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.00055306",
            "timestamp":"2019-03-15T02:52:56.000Z"
        },
        {
            "created_at":"2019-03-15T02:52:56.000Z",
            "exec_type":"T",
            "fee":"0",
            "instrument_id":"BTC-USDT",
            "ledger_id":"3963052719",
            "liquidity":"T",
            "order_id":"2482659399697408",
            "price":"3888.6",
            "product_id":"BTC-USDT",
            "side":"sell",
            "size":"1.73797088",
            "timestamp":"2019-03-15T02:52:56.000Z"
        },
        {
            "created_at":"2019-03-15T02:52:56.000Z",
            "exec_type":"T",
            "fee":"0",
            "instrument_id":"BTC-USDT",
            "ledger_id":"3963052718",
            "liquidity":"T",
            "order_id":"2482659399697408",
            "price":"3888.6",
            "product_id":"BTC-USDT",
            "side":"sell",
            "size":"2.15062911",
            "timestamp":"2019-03-15T02:52:56.000Z"
        }
    ],
    {
        "before":"3963052722",
        "after":"3963052718"
    }
]

Place Algo Order

Rate limit:20/2s
HTTP Request

POST /api/spot/v3/order_algo

Example

POST/api/spot/v3/order_algo{"instrument_id":"BTC-USDT","mode":"1","trigger_price":"432.11","order_type":"1",“algo_price“:"341.99","size":"2"}(止盈止损)

Request Parameters

General Parameters

Parameters Type Mandatory Description
instrument_id String Yes Trading pair symbol
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price
size String Yes Total number of orders must be an integer between 1 and 1,000,000, incl. both numbers
mode String Yes 1:spot 2:margin
side String Yes buy or sell

Trigger Order (Maximum 10 orders)

Parameters Type Mandatory Description
trigger_price String Yes Trigger price must be between 0 and 1,000,000
algo_price String Yes Order price must be between 0 and 1,000,000

Trail Order (Maximum 10 orders)

Parameters Type Mandatory Description
callback_rate String Yes Callback rate must be between 0.001 (0.1%) and 0.05 (5%)
trigger_price String Yes Trigger price must be between 0 and 1,000,000

Iceberg Order (Maximum 6 orders)

Parameters Type Mandatory Description
algo_variance String Yes Order depth must be between 0.0001 (0.01%) and 0.01 (1%)
avg_amount String Yes Single order average amount must be an integer between 2 and 1,000, incl. both numbers (perpetual swap: integer between 2 and 500, incl. both numbers)
limit_price String Yes Price limit must be between 0 and 1,000,000

TWAP (Maximum 6 orders)

Parameters Type Mandatory Description
sweep_range String Yes Auto-cancelling order range must be between 0.005 (0.5%) and 0.01 (1%), incl. both numbers
sweep_ratio String Yes Auto-cancelling order rate must be between 0.01 and 1, incl. both numbers
single_limit String Yes Single order limit must be between 10 and 2,000, incl. both numbers (perpetual swap: integer between 2 and 500, incl. both numbers)
limit_price String Yes Price limit must be between 0 and 1,000,000, incl, 1,000,000
time_interval String Yes Time interval must be between 5 and 120, incl. both numbers

Return Parameters

Name Type Description
result String Parameters return result
instrument_id String Contract ID, e.g. BTC-USD-190328
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
algo_id String Order ID: when fail to place order, the value is -1
error_code String Error code will be 0 if the order is successfully placed, and will appear if order fails
error_message String Error message will be blank if order is successfully placed, and will appear if order fails
Example Response
{
    "result":true,
    "instrument_id":"BTC-USDT",
    "order_type":"1",
    "algo_id":"2517062038154240"
}

Cancel Algo Order

If user use “algo_id” to cancel unfulfilled orders, they can cancel a maximum of 6 iceberg/TWAP or 10 trigger/trail orders at the same time.

Rate limit:20/2s
HTTP Request

POST/api/spot/v3/cancel_batch_algos

Example

POST/api/spot/v3/cancel_batch_algos/{"instrument_id": "BTC-USDT","algo_ids":["1600593327162368","1600593327162369"]}

Request Parameters

Name Type Mandatory Description
instrument_id String Yes Trading pair symbol
algo_ids String Yes Cancel specific order ID
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price

Return Parameters

Name Type Description
instrument_id String Trading pair symbol
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price
algo_ids String Cancel specific order ID
result String Parameter return result

Return Parameter

Return parameter is the order ID of canceled orders. This does not mean that the orders are successfully canceled. Orders that are pending cannot be canceled, only unfulfilled orders can be canceled.

Description

This does not guarantee orders are canceled successfully. Users are advised to request the order list to confirm after using the cancelation endpoint.

Example Response
{
    "result":true,
    "instrument_id":"BTC-USDT",
    "order_type":"1",
    "algo_id":"2517062038154240"
}

Get Algo Order List

Obtaining Order List

Rate limit:20/2s
HTTP Request

GET /api/spot/v3/algo

Example

GET/api/spot/v3/algo?instrument_id=BTC-USDT&algo_id=23333&status=2&from=4&limit=87

Parameters

Name Type Mandatory Description
instrument_id String Yes Trading pair symbol
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price
status String See Description [Status and algo_ids are mandatory, select either one] Order status: (1. Pending; 2. 2. Effective; 3. Cancelled; 4. Partially effective; 5. Paused; 6. Order failed [Status 4 and 5 only applies to iceberg and TWAP orders]
algo_ids String See Description [status and algo_ids are mandatory, select either one] Enquiry specific order ID
before string No [Optional] Request page content after this ID (updated records)
after string No [Optional] Request page content before this ID (past records)
limit string No [Optional] The number of results returned by the page. Default and maximum are both 100 (see the description on page for more details)

Return Parameters

Name Type Description
instrument_id String Trading pair symbol
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
timestamp String Order time
rejected_at String Order expiration time
algo_id String Order ID
status String Order status: 1. Pending; 2. Effective; 3. Canceled (4. Partially effective; 5. Paused)
size String Order amount must be an integer between 1 and 1,000,000, incl. 1,000,000

Trigger Orders

Parameters Type Description
trigger_price String Trigger price must be greater than 0
algo_price String Algo price must be between 0 and 1,000,000 incl. 1,000,000
real_amount String Actual order amount

Trail Orders

Parameters Type Description
callback_rate String Callback rate must be between 0.001 (0.1%) and 0.05 (5%), incl. both numbers
trigger_price String Trigger price must be between 0 and 1,000,000, incl. 1,000,000
real_amount String Actual order amount

Iceberg Orders

Parameters Type Description
algo_variance String Order depth must be between 0 and 0.01 (1%), incl. 0.01
avg_amount String Average amount must be an integer between 2 and 500 (same for perpetual swap), incl. both numbers
limit_price String Price limit must be between 0 and 1,000,000, incl. 1,000,000
deal_value String Transacted volume

Time-weighted Average Price (TWAP)

Parameter Type Description
sweep_range String Auto-cancelling order range must be between 0.005 (0.5%) and 0.01 (1%), incl. both numbers
sweep_ratio String Auto-cancelling order rate must be between 0.01 and 1, incl. both numbers
single_limit String Single order limit must be between 10 and 2,000 (perpetual swap orders: integer between 2 and 500), incl. both numbers
limit_price String Price limit must be between 0 and 1,000,000, incl. 1,000,000
time_interval String Order time interval must be between 5 and 120, incl. both numbers
deal_value String Order volume
Example Response
{
    "instrument_id":"BTC-USDT",
    "order_type":"1",
    "algo_id":"2517062038154240"    
    "timestamp":"2019-03-25T03:45:17.376Z"
    "rejected_at":"2019-03-26T03:45:17.376Z"
    "status":"2"    
    "leverage":"20"   
    "trigger_price":"2"   
    "algo_price":"2"   
    "size":"2000"  
    "real_amount":"1000"      
}

Public - Trading Pairs

This provides snapshots of market data and is publicly accessible without account authentication.

Retrieves list of trading pairs, trading limit, and unit increment.

Rate limit: 20 Requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments

Example Request

GET/api/spot/v3/instruments

Response
Parameter Type Description
instrument_id String Trading pair symbol
base_currency String Base currency
quote_currency String Quote currency
min_size String Minimum trading threshold
size_increment String Minimum increment size
tick_size String Price increment
Notes

The min_size is the minimum quantity of order placed in the unit of the base currency. Base_increment is the minimum incremental unit of placing an order. If the base_increment is 0.000001, entering a size of 0.0.0000126 will be rounded to 0.000012.

The tick_size is the smallest incremental unit of price. The order price must be a multiple of the tick_size. Example: if the tick_size is 0.0001, entering a price of 0.02237 will be adjusted to 0.0223 instead.

Example Response
[
    {
        "base_currency":"BTC",
        "instrument_id":"BTC-USDT",
        "min_size":"0.001",
        "quote_currency":"USDT",
        "size_increment":"0.00000001",
        "tick_size":"0.1"
    },
    {
        "base_currency":"OKB",
        "instrument_id":"OKB-USDT",
        "min_size":"1",
        "quote_currency":"USDT",
        "size_increment":"0.0001",
        "tick_size":"0.0001"
    }
]

Public - Order Book

Retrieve a trading pair's order book. Pagination is not supported here; the entire orderbook will be returned per request. This is publicly accessible without account authentication. WebSocket is recommended here.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments/&lt;instrument_id&gt;/book

Example Request

GET/api/spot/v3/instruments/BTC-USDT/book?size=5&depth=0.2

Parameters
Parameter Type Required Description
size String No Number of results per request. Maximum 200
depth String No Aggregation of the order book. e.g . 0.1, 0.001
instrument_id String No Trading pair symbol
Response
Parameter Type Description
price String Price
size String Size
num_orders String Total orders in this aggregation of the order book
timestamp String Timestamp
Notes

Aggregation of the order book means that orders within a certain price range is combined and considered as one order cluster.

When size is not passed in the parameters, one entry is returned; when size is 0, no entry is returned. The maximum size is 200. When requesting more than 200 entries, at most 200 entries are returned.

Example Response
{
    "asks":[
        [
            "3993.2",
            "0.41600068",
            "1"
        ],
        [
            "3993.4",
            "1.24807818",
            "3"
        ],
        [
            "3993.6",
            "0.03",
            "1"
        ],
        [
            "3993.8",
            "0.03",
            "1"
        ]
    ],
    "bids":[
        [
            "3993",
            "0.15149658",
            "2"
        ],
        [
            "3992.8",
            "1.19046818",
            "1"
        ],
        [
            "3992.6",
            "0.20831389",
            "1"
        ],
        [
            "3992.4",
            "0.01669446",
            "2"
        ]
    ],
    "timestamp":"2019-03-20T03:55:37.888Z"
}

Public - Trading Pairs

Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours for all trading pairs. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments/ticker

Example Request

GET/api/spot/v3/instruments/ticker

Response
Parameter Type Description
instrument_id String Trading pair symbol
last String Last traded price
best_bid String Best bid price
best_ask String Best ask price
open_24h String Opening price 24 hours ago
high_24h String Highest price in the past 24 hours
low_24h String Lowest price in the past 24 hours
base_volume_24h String Trading volume of past 24 hours in the base currency
quote_volume_24h String Trading volume of past 24 hours in the quote currency
timestamp String Timestamp
Notes

The high_24h, low_24h, and base_volume_24h, are computed based on the data in the last 24 hours.

The open_24 is the opening price exactly 24 hours ago.

Example Response
[
    {
        "best_ask":"3995.4",
        "best_bid":"3995.3",
        "instrument_id":"BTC-USDT",
        "product_id":"BTC-USDT",
        "last":"3995.3",
        "ask":"3995.4",
        "bid":"3995.3",
        "open_24h":"3989.7",
        "high_24h":"4031.9",
        "low_24h":"3968.9",
        "base_volume_24h":"31254.359231295",
        "timestamp":"2019-03-20T04:07:07.912Z",
        "quote_volume_24h":"124925963.3459723295"
    },
    {
        "best_ask":"1.3205",
        "best_bid":"1.3204",
        "instrument_id":"OKB-USDT",
        "product_id":"OKB-USDT",
        "last":"1.3205",
        "ask":"1.3205",
        "bid":"1.3204",
        "open_24h":"1.0764",
        "high_24h":"1.44",
        "low_24h":"1.0601",
        "base_volume_24h":"183010468.2062",
        "timestamp":"2019-03-20T04:07:05.878Z",
        "quote_volume_24h":"233516598.011530085"
    }
]

Public - Trading Pair Information

Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours for a particular trading pair. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments/&lt;instrument_id&gt;/ticker

Example Request

GET/api/spot/v3/instruments/BTC-USDT/ticker

Parameters
Parameter Type Required Description
instrument_id String Yes Trading Pair symbol
Response
Parameter Type Description
instrument_id String Trading pair symbol
last String Last traded price
best_bid String Best bid price
best_ask String Best ask price
open_24h String Opening price 24 hours ago
high_24h String Highest price in the past 24 hours
low_24h String Lowest price in the past 24 hours
base_volume_24h String Trading volume of past 24 hours in the base currency
quote_volume_24h String Trading volume of past 24 hours in the quote currency
timestamp String Timestamp
Notes

The high_24h, low_24h, and base_volume_24h, are computed based on the data in the last 24 hours.

The open_24 is the opening price exactly 24 hours ago.

Example Response
{
  best_ask:3858.8
  best_bid:3858.6
  instrument_id:BTC-USDT
  product_id:BTC-USDT
  last:3858.6
  ask:3858.8
  bid:3858.6
  open_24h:3886
  high_24h:3900.8
  low_24h:3839.1
  base_volume_24h:19081.61024493
  timestamp:2019-03-13T11:42:09.849Z
  quote_volume_24h:73978722.5
}

Public - Filled Orders

Retrieve the latest 60 transactions of all trading pairs. Pagination is supported and the response is sorted with most recent first in reverse chronological order. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments/&lt;instrument_id&gt;/trades

Example Request

2018-09-12T07:58:34.414ZGET/api/spot/v3/instruments/LTC-USDT/trades?limit=20&from=2&to=4

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pair symbol
after String No Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String No Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String No Number of results per request. The maximum is 60; the default is 60
Response
Parameter Type Description
timestamp String Order fill time
trade_id String Transaction ID
price String Filled price
size String Filled size
side String Filled side
Notes

The side indicates the side of the order that is filled by the taker. The “taker” means actively taking the order on the order book. The buy indicates the taker is taking liquidity from the order book, so the price rises as a result, whereas the sell indicates the price falls as a result.

Example Response
[
    {
        "time":"2019-04-12T02:07:30.523Z",
        "timestamp":"2019-04-12T02:07:30.523Z",
        "trade_id":"1296412902",
        "price":"4913.4",
        "size":"0.00990734",
        "side":"buy"
    },
    {
        "time":"2019-04-12T02:07:30.455Z",
        "timestamp":"2019-04-12T02:07:30.455Z",
        "trade_id":"1296412899",
        "price":"4913.2",
        "size":"0.17820096",
        "side":"sell"
    }
]

Public - Market Data

Retrieve the candlestick charts of the trading pairs. This API can retrieve the latest 2000 entries of data. Candlesticks are returned in groups based on requested granularity. Maximum of 2,000 entries can be retrieved.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments/&lt;instrument_id&gt;/candles

Example Request

GET /api/spot/v3/instruments/BTC-USDT/candles?granularity=86400&start=2019-03-18T08%3A28%3A48.899Z&end=2019-03-19T09%3A28%3A48.899Z

Parameters
Parameter Type Required Description
start String No Start time in ISO 8601
end String No End time in ISO 8601
granularity String No Desired timeselice in seconds
instrument_id String Yes Trading pairs symbol
Response
Parameter Type Description
time String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
Notes

Both parameters will be ignored if either one of start or end are not provided. The last 200 records of data will be returned if the time range is not specified in the request.

The granularity field must be one of the following values: [60, 180, 300, 900, 1800, 3600, 7200, 14400, 43200, 86400, 604800]. Otherwise, your request will be rejected. These values correspond to timeslices representing [1 minute, 3 minutes, 5 minutes, 15 minutes, 30 minutes, 1 hour, 2 hours, 6 hours, 12 hours, 1 day, and 1 week] respectively.

The candlestick data may be incomplete, and should not be polled repeatedly.

The maximum data set is 200 candles for a single request. If the request made with the parameters start, end and granularity will result in more data than that is allowed, only 200 candles will be returned. If finer granularity over a larger time range is needed, please make multiple requests as needed.

Example Response

[
    [
        "2019-03-19T16:00:00.000Z",
        "3997.3",
        "4031.9",
        "3982.5",
        "3998.7",
        "26175.21141385"
    ],
    [
        "2019-03-18T16:00:00.000Z",
        "3980.6",
        "4014.6",
        "3968.9",
        "3997.3",
        "33053.48725643"
    ]
]

Margin Trading API

This includes endpoints for retrieving market data, account information, order management, and bills details of your margin trading account.

Note: Some of the API response parameters may be redundant in order to stay compatible with the older version. Please only reference parameters specified in the API documentation.

For example, the API may return three values for the amount on hold, frozen, hold, and holds. Please use hold as referred in the documentation.

Margin account

This retrieves the list of assets, (with nonzero balance), remaining balance, and amount available in the margin trading account.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/margin/v3/accounts

Example Request

2018-09-13T02:25:41.946ZGET/api/margin/v3/accounts

Return Parameters
Parameters Parameters Types Description
instrument_id String Trading pair
balance String Remaining balance
hold String Amount on hold (not available)
available String Available Amount
risk_rate String Risk rate
can_withdraw String Available transfer amount
liquidation_price String Liquidation price
borrowed String Borrowed tokens (unpaid)
lending_fee String Interest (unpaid)
margin_ratio String Margin ratio
Notes

After you placed an order, the amount of the order will be put on hold. You will not be able to transfer or use in other orders until the order is completed or cancelled.

Example Response
[
    {
        "currency:BTC":{
            "available":"0",
            "balance":"0",
            "borrowed":"0",
            "can_withdraw":"0",
            "frozen":"0",
            "hold":"0",
            "holds":"0",
            "lending_fee":"0"
        },
        "currency:USDT":{
            "available":"100",
            "balance":"100",
            "borrowed":"0",
            "can_withdraw":"100",
            "frozen":"0",
            "hold":"0",
            "holds":"0",
            "lending_fee":"0"
        },
        "instrument_id":"BTC-USDT",
        "liquidation_price":"0",
        "product_id":"BTC-USDT",
        "risk_rate":""
    },
    {
        "currency:EOS":{
            "available":"0.59957711",
            "balance":"0.59957711",
            "borrowed":"0.20000208",
            "can_withdraw":"0.483",
            "frozen":"0",
            "hold":"0",
            "holds":"0",
            "lending_fee":"0.00003661"
        },
        "currency:USDT":{
            "available":"0.496",
            "balance":"0.496",
            "borrowed":"0",
            "can_withdraw":"0.496",
            "frozen":"0",
            "hold":"0",
            "holds":"0",
            "lending_fee":"0"
        },
        "instrument_id":"EOS-USDT",
        "liquidation_price":"0",
        "product_id":"EOS-USDT",
        "risk_rate":"3.6681"
    }
]

Margin Account of a Currency

Get the balance, amount on hold and more useful information.

Rate limit: 20 / 2s
HTTP Requests

GET /api/margin/v3/accounts/<instrument_id>

End Certificate Request Sample

2018-09-13T02:25:41.946ZGET/api/margin/v3/accounts/eos-usdt

Request Parameters
Parameters Parameters Types Description
instrument_id String [required] trading pair
Return Parameters
Parameters Parameters Types Description
balance String balance
hold String amount on hold(not available)
available String available amount
risk_rate String risk rate
can_withdraw String available transfer amount
liquidation_price String liquidation price
borrowed String borrowed tokens (unpaid)
lending_fee String interest (unpaid)
margin_ratio String Margin ratio
Return Sample
{
    "currency:EOS":{
        "available":"0.59957711",
        "balance":"0.59957711",
        "borrowed":"0.20000208",
        "can_withdraw":"0.48351954",
        "frozen":"0",
        "hold":"0",
        "holds":"0",
        "lending_fee":"0.00003661"
    },
    "currency:USDT":{
        "available":"0.496",
        "balance":"0.496",
        "borrowed":"0",
        "can_withdraw":"0.496",
        "frozen":"0",
        "hold":"0",
        "holds":"0",
        "lending_fee":"0"
    },
    "liquidation_price":"0",
    "risk_rate":"3.6675"
}

Bills Details

List all bill details. Pagination is used here. before and after cursor arguments should not be confused with before and after in chronological time. Most paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first. This API can retrieve data in the last 3 months.

Rate limit: 20/ 2s
HTTP Requests

GET /api/margin/v3/accounts/<instrument_id>/ledger

End Certificate Request Sample

2019-03-18T03:45:56.000ZGET/api/margin/v3/accounts/btc-usdt/ledger?limit=10&type=1&from=1&to=2

Request Parameters
Parameters Parameters Types Required Description
currency String Yes token
after String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
before String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)
type String No 1 .Deposit 2 .Withdraw 3 .Borrow 4 .Repay7 .Buy 8 .Sell 9 .Beginner’s Task 10 .Invite friends to complete beginner’s task 11 .扣除任务奖励 12 .Invitation Bonus 13 .Canceled Withdrawal 14 .Deducted for Events 15 .Received from Events 18 .Transfer from Futures 19 .Transfer to Futures 20 .Transfer from Sub-account 21 .Transfer to Sub-account 22 .Transaction Fee Rebate 23 .Receive Red Packet 24 .Send Red Packet 25 .C2C Buy 26 .C2C Sell 27 .Deduct 28 .Convert 29 .Transfer to Assets Account 30 .Transfer from Assets Account 31 .Transfer to C2C Account 32 .Transfer from C2C Account 33 .Transfer to Margin Account 34 .Transfer from Margin Account 35 .Borrow 36 .Repay 37 .Market Maker Bonus 38 .Market Maker Rebate 41 .Fee Settled with LP 42 .Purchase Loyalty Points 43 .Transfer Loyalty Points 44 .MM Program Bonus 45 .MM Program Rebate 46 .Transfer from Spot Account 47 .Transfer to Spot Account 48 .Transfer to ETT 49 .Transfer from ETT 50 .Deducted for mining 51 .Gain from mining 52 .Extra yield 53 .Incentive bonus distribution 55 .Transfer from OK PiggyBank 56 .Transfer to OK PiggyBank 57 .Transfer from Swap Account 58 .Transfer to Swap Account 59 .Repay Bonus 60 .Margin Fee Settled with LP
Return Parameters
Parameters Parameters Types Description
ledger_id String bill ID
instrument_id String trading pair
currency String token
balance String remaining balance
amount String amount
type String type of bill
timestamp String bill creation time
details String if the type is trade or fee, order details will be included under this.
order_id String order ID
Type value Description
transfer funds transfer
trade funds moved as a result of a trade
rebate fee rebate as per our fee schedule
Return Sample
[
    [
        {
            "created_at":"2019-03-20T05:45:10.000Z",
            "ledger_id":"78965766",
            "timestamp":"2019-03-20T05:45:10.000Z",
            "currency":"EOS",
            "amount":"0",
            "balance":"0.59957711",
            "type":"transfer",
            "details":{
                "instrument_id":"EOS-USDT",
                "order_id":"787057",
                "product_id":"EOS-USDT"
            }
        },
        {
            "created_at":"2019-03-20T04:45:07.000Z",
            "ledger_id":"78942699",
            "timestamp":"2019-03-20T04:45:07.000Z",
            "currency":"EOS",
            "amount":"0",
            "balance":"0.59957711",
            "type":"transfer",
            "details":{
                "instrument_id":"EOS-USDT",
                "order_id":"787057",
                "product_id":"EOS-USDT"
            }
        },
        {
            "created_at":"2019-03-20T03:45:05.000Z",
            "ledger_id":"78918186",
            "timestamp":"2019-03-20T03:45:05.000Z",
            "currency":"EOS",
            "amount":"0",
            "balance":"0.59957711",
            "type":"transfer",
            "details":{
                "instrument_id":"EOS-USDT",
                "order_id":"787057",
                "product_id":"EOS-USDT"
            }
        }
    ],
    {
        "before":"78965766",
        "after":"78918186"
    }
]

Margin Account Settings

Retrieve all the information of the margin trading account, including the maximum loan amount, interest rate, and maximum leverage.

Rate limit:20 requests per 2 seconds
HTTP Request

GET /api/margin/v3/accounts/availability

Example Request

2018-09-13T02:27:05.580ZGET/api/margin/v3/accounts/availability

Response
Parameters Parameters Types Description
instrument_id String Trading pair symbol
currency String Token symbol
available String Maximum loan amount
rate String Interest rate
leverage String Maximum leverage
Example response
[
    {
        "currency:BTC":{
            "available":"0.09995502",
            "leverage":"5",
            "leverage_ratio":"5",
            "rate":"0.00009984"
        },
        "currency:USDT":{
            "available":"400.00000000",
            "leverage":"5",
            "leverage_ratio":"5",
            "rate":"0.00019992"
        },
        "instrument_id":"BTC-USDT",
        "product_id":"BTC-USDT"
    },
    {
        "currency:EOS":{
            "available":"1.9343",
            "leverage":"5",
            "leverage_ratio":"5",
            "rate":"0.00009984"
        },
        "currency:USDT":{
            "available":"7.1571",
            "leverage":"5",
            "leverage_ratio":"5",
            "rate":"0.00019992"
        },
        "instrument_id":"EOS-USDT",
        "product_id":"EOS-USDT"
    }
]

Margin Account Settings for a Currency

Get all information of the margin trading account of a specific token, including the maximum loan amount, interest rate, and maximum leverage.

Rate limit:20/2s
HTTP Requests

GET /api/margin/v3/accounts/<instrument_id>/availability

End Certificate Request Sample

2019-03-18T02:27:37.723ZGET/api/margin/v3/accounts/BTC-USDT/availability

Request Parameters
Parameters Parameters Types Description
instrument_id String [required] trading pair
Return Parameters
Parameters Parameters Types Description
currency String token
available String maximum loan amount
rate String interest rate
leverage String maximum leverage
instrument_id String trading pair
Return Sample
[
    {
        "currency:BTC":{
            "available":"0.09989261",
            "leverage":"5",
            "leverage_ratio":"5",
            "rate":"0.00009984"
        },
        "currency:USDT":{
            "available":"400.00000000",
            "leverage":"5",
            "leverage_ratio":"5",
            "rate":"0.00019992"
        },
        "instrument_id":"BTC-USDT",
        "product_id":"BTC-USDT"
    }
]

Get Loan History

Get loan history of the margin trading account. Pagination is used here. before and after cursor arguments should not be confused with before and after in chronological time. Most paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

Rate limit:20/2s
HTTP Requests

GET /api/margin/v3/accounts/borrowed

End Certificate Request Sample

2018-09-13T02:28:14.618ZGET/api/margin/v3/accounts/borrowed?status=0& limit=1&from=2&to=4

Request Parameters
Parameters Parameters Types Required Description
status String Yes status(0: outstanding 1: repaid)
after String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
before String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
borrow_id String borrow ID
instrument_id String trading pair
currency String token
created_at String borrow time
amount String borrow amount
interest String interest
returned_amount String amount repaid
paid_interest String interest repaid
last_interest_time String last interest accrual time
force_repay_time String force repay time
rate String rate
Return Sample
[
    [
        {
            "amount":"0.5",
            "borrow_id":"787057",
            "created_at":"2019-03-18T09:41:44.000Z",
            "currency":"EOS",
            "force_repay_time":"2019-03-25T09:42:19.000Z",
            "instrument_id":"EOS-USDT",
            "interest":"0.0000386883807232",
            "last_interest_time":"2019-03-20T05:45:11.000Z",
            "paid_interest":"0.00000208",
            "product_id":"EOS-USDT",
            "rate":"0.00000416",
            "repay_amount":"0.29999792",
            "repay_interest":"0.00000208",
            "returned_amount":"0.29999792",
            "timestamp":"2019-03-18T09:41:44.000Z"
        }
    ],
    {
        "before":"787057",
        "after":"787057"
    }
]

Get Loan History of a Currency

Get loan history of the margin trading account of a specific token. Pagination is used here. before and after cursor arguments should not be confused with before and after in chronological time. Most paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

Rate limit:20/2s
HTTP Requests

GET /api/margin/v3/accounts/<instrument_id>/borrowed

End Certificate Request Sample

2018-09-13T02:29:06.610ZGET/api/margin/v3/accounts/BTC-USDT/borrowed?limit=2&state=1&from=2&to=4

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes trading pair
after String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
before String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)
state String Yes Order state("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling,"6": Incomplete(open+partially filled),"7":Complete(cancelled+fully filled))
Return Parameters
Parameters Parameters Types Description
borrow_id String borrow ID
currency String token
created_at String borrow time
amount String borrow amount
interest String interest
returned_amount String amount repaid
paid_interest String interest repaid
last_interest_time String Last interest accrual time
force_repay_time String force repay time
rate String rate
Return Sample
[
    [
        {
            "amount":"0.5",
            "borrow_id":"787057",
            "created_at":"2019-03-18T09:41:44.000Z",
            "currency":"EOS",
            "force_repay_time":"2019-03-25T09:42:19.000Z",
            "instrument_id":"EOS-USDT",
            "interest":"0.0000386883807232",
            "last_interest_time":"2019-03-20T05:45:11.000Z",
            "paid_interest":"0.00000208",
            "product_id":"EOS-USDT",
            "rate":"0.00000416",
            "repay_amount":"0.29999792",
            "repay_interest":"0.00000208",
            "returned_amount":"0.29999792",
            "timestamp":"2019-03-18T09:41:44.000Z"
        }
    ],
    {
        "before":"787057",
        "after":"787057"
    }
]

Loan

Borrowing tokens in a margin trading account.

Rate limit:100 requests per 2 seconds
HTTP Request

POST /api/margin/v3/accounts/borrow

Example Request

2018-10-08T03:00:56.799ZPOST/api/margin/v3/accounts/borrow{"instrument_id":"ltc-usdt","currency":"usdt","amount":"0.1"}

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Trading pair
currency String Yes Token
amount String Yes Borrowed amount
Return Parameters
Parameters Parameters Types Description
borrow_id String Borrow ID
result Boolean Result of the request
Example Response
{
    "borrow_id":"791434",
    "client_oid":"",
    "result":true
}

Repayment

Repaying tokens in a margin trading account.

Rate limit:100/2s
HTTP Requests

POST /api/margin/v3/accounts/repayment

End Certificate Request Sample

2018-10-08T03:04:52.002ZPOST/api/margin/v3/accounts/repayment{"instrument_id":"ltc-usdt","currency":"usdt","amount":"0.1","borrow_id":"185759"}

Request Parameters
Parameters Parameters Types Required Description
borrow_id String No borrow ID . all borrowed token under this trading pair will be repay if the field is left blank
instrument_id String Yes trading pair
currency String Yes token
amount String Yes amount repaid
Return Parameters
Parameters Parameters Types Description
repayment_id String borrow ID
result Boolean result
Return Sample
{
    "client_oid":"",
    "repayment_id":"791434",
    "result":true
}

Place an Order

OKEx API only supports limit and market orders (more order types will become available in the future). You can place an order only if you have enough funds. Once your order is placed, the amount will be put on hold until the order is executed.

Rate limit: 100 requests per 2 seconds
HTTP Request

POST /api/margin/v3/orders

Example Authenticated Request

2018-09-12T07:46:47.098ZPOST/api/margin/v3/orders{"client_oid":"20180728","order_type”:”1”,"instrument_id":"btc-usdt","side":"buy","type":"limit","size":"0.1","notional":"100","margin_trading":"2"}

Parameters
Parameter Type Required Description
client_oid String No Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
type String No Supports types limit or market (default: limit). When placing market orders, order_type must be 0 (normal order)
side String Yes Specify buy or sell
instrument_id String Yes Trading pair symbol
margin_trading String Yes Order type (The request value is 2)
order_type String No Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
Limit Order Parameters
Parameter Type Required Description
price String Yes Price
size String Yes Quantity to buy or sell
Market Order Parameters
Parameters Parameters Types Required Description
size String Yes Quantity to be sold. Required for market sells
notional String Yes Amount to spend. Required for market buys
Response
Parameters Type Description
order_id String Order ID
client_oid String Client-supplied order ID
result Boolean Result of the order. Error message will be returned if the order failed.
error_code String Error code; blank if order placed successfully
error_message String Error message; blank if order placed successfully
Notes

client_oid

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

instrument_id

The instrument_id must match a valid instrument. The instruments list is available via the /instrument endpoint

type

You can specify the order type when placing an order. The order type you specify will decide which order parameters are required further as well as how your order will be executed by the matching engine. If type is not specified, the order will default to a limit order. Limit order is the default order type, and it is also the basic order type. A limit order requires specifying a price and size. The limit order will be filled at the specifie price or better. Specifically, A sell order can be filled at the specified or higher price per the quote token. A buy order can be filled at the specified or lower price per the quote token. If the limit order is not filled immediately, it will be sent into the open order book until filled or canceled. Market orders differ from limit orders in that they have NO price specification. It provides an order type to buy or sell specific amount of tokens without the need to specify the price. Market orders execute immediately and will not be sent into the open order book. Market orders are always considered as ‘takers’ and incur taker fees. Warming: Market order is strongly discouraged and if an order to sell/buy a large amount is placed it will probably cause turbulence in the market.

price

The price must be specified in unit of quote_increment which is the smallest incremental unit of the price. It can be acquired via the /instrument endpoint.

size

Size is the quantity of buying or selling and must be larger than the min_size. size_increment is the minimum increment size. It can be acquired via the /instrument endpoint.

Example: If the min_size of OKB/USDT is 10 and the size_increment is 0.0001, then it is impossible to trade 9.99 OKB but possible to trade 10.0001 OKB.

notional

The notional field is the quantity of quoted currency when placing market orders; it is required for market orders. For example, a market buy for BTC-USDT with quantity specified as 5000 will spend 5000 USDT to buy BTC.

hold

For limit buy order, we will put a hold the quoted currency, of which the amount on hold = specific price x buying size. For limit sell orders, we will put a hold on the currency equal to the amount you want to sell. For market buy orders, the amount equal to the quantity for the quoted currency will be on hold. For market sell orders, the amount based on the size of the currency you want to sell will be on hold. Cancelling an open order releases the amount on hold.

Order life cycle

The HTTP Request will respond when an order is either rejected (insufficient funds, invalid parameters, etc) or received (accepted by the matching engine). A 200 response indicates that the order was received and is active. Active orders may execute immediately (depending on price and market conditions) either partially or fully. A partial execution will put the remaining size of the order in the open state. An order that is filled completely, will go into the completed state.

Users listening to streaming market data are encouraged to use the client_oid field to identify their received messages in the feed. The REST response with a server order_id may come after the received message in the public data feed.

Response

A successful order will be assigned an order id. A successful order is defined as one that has been accepted by the matching engine. Open orders will not expire until filled or canceled.

Return Sample
{
    "client_oid":"oktlever50",
    "error_code":"",
    "error_message":"",
    "order_id":"2512084870235136",
    "result":true
}

Place Multiple Orders

This supports placing multiple orders in batches for up to 4 trading pairs and a maximum of 10 orders per trading pair can be placed at a time.

Rate limit: 50 requests per 2 seconds
HTTP Request

POST /api/margin/v3/batch_orders

Example Request

Market Order:2018-09-14T09:51:24.959ZPOST/api/spot/v3/batch_orders[{"client_oid":"E20180728","order_type”:”1”,"instrument_id":"btc-usdt","side":"sell","type":"limit"," size ":"0.001"," notional ":"10001","margin_trading ":"2"},{"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"limit"," size ":"0.001","notional":"10002","margin_trading ":"2"}

Limit Order:2018-09-14T09:51:24.959ZPOST/api/spot/v3/batch_orders[{"client_oid":"T20180728","order_type”:”1”,"instrument_id":"btc-usdt","side":"sell","type":"limit","size":"0.001","price":"10001","margin_trading ":"2"},{"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"limit","size":"0.001","price":"10002","margin_trading ":"2"}

Parameters

Parameter Type Required Description
client_oid String No Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
type String Yes Supports types limit or market (default: limit). When placing market orders, order_type must be 0 (normal order)
side String Yes Specify buy or sell
instrument_id String Yes Trading pair symbol
margin_trading String Yes Order type (The request value is 2)
order_type String No Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
Limit Order Parameters
Parameter Type Required Description
price String Yes Price
size String Yes Quantity to buy or sell
Market Order Parameters
Parameters Parameters Types Required Description
size String Yes Quantity to be sold. Required for market sells
notional String Yes Amount to spend. Required for market buys
Response
Parameters Type Description
order_id String Order ID
client_oid String Client-supplied order ID
result Boolean Result of the order. Error message will be returned if the order failed.
error_code String Error code; blank if order placed successfully
error_message String Error message; blank if order placed successfully
Notes

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

You may place batch orders for up to 4 trading pairs, each with 10 orders at maximum. If you cancel the batch orders, you should confirm they are successfully canceled by requesting the "Get Order List" endpoint.

Example Response
{
    "BTC-USDT":[
        {
            "client_oid":"oktlever51",
            "error_code":"0",
            "error_message":"",
            "order_id":"2512113685627904",
            "result":true
        },
        {
            "client_oid":"oktlever52",
            "error_code":"0",
            "error_message":"",
            "order_id":"2512113687135232",
            "result":true
        }
    ]
}

Cancel an Order

Cancelling an unfilled order.

Rate limit: 100 / 2s
HTTP Requests

POST /api/margin/v3/cancel_orders/<order_id or client_oid>

End Certificate Request Sample

2018-10-12T07:34:30.223ZPOST/api/margin/v3/cancel_orders/a123{"instrument_id":"btc-usdt"}

Request Parameters
Parameters Parameters Types Compulsory Description
instrument_id String yes by providing this parameter,the corresponding order of a designated trading pair will be cancelled.If not providing this parameter,it will be back to error code.
client_oid String No Either client_oid or order_id must be present. the order ID created by yourself , The client_oid type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported
order_id String No Either client_oid or order_id must be present. order ID
Return Parameters
Parameters Parameters Types Description
order_id String order ID
client_oid String this client_oid is the order ID sent by the user.
error_code String Error code for order placement.
error_message String It will be blank if order placement is success. Error message will be returned if order placement fails.
result Boolean Call interface returns results. if the order cannot be canceled (already settled or canceled), the error description it returns to will display the corresponding reason.
Explanation

When using client_oid for order cancellation, The user needs to make sure the ID does not repeat and there is no repetition alert. In case of repetition, only the latest entry will be canceled.

If the order cannot be cancelled (already settled or cancelled), the error description it returns to will display the corresponding reason.

Return Sample
{
    "btc-usdt":[
    {
       "result":true,
        "client_oid":"a123",
        "order_id": "2510832677225473"
     }
]
}

Cancel Multiple Orders

Cancel multiple open orders with order_id or client_oid. Up to 4 trading pairs, and maximum 10 orders can be placed at a time for each trading pair.

Rate limit: 50/ 2s
HTTP Requests

POST /api/margin/v3/cancel_batch_orders

End Certificate Request Sample

2018-10-12T07:30:49.664ZPOST/api/spot/v3/cancel_batch_orders[{"instrument_id":"btc-usdt","client_oids":["a123","a1234"]},{"instrument_id":"ltc-usdt","client_oids":["a12345","a123456"]}]

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes by providing this parameter,the corresponding order of a designated trading pair will be cancelled.If not providing this parameter,it will be.
order_ids List<String> No Either client_oids or order_ids must be present. order ID
client_oids List<String> No Either client_oids or order_ids must be present. The client_oid type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported
Return Parameters
Parameters Parameters Types Description
order_id String order ID
client_oid String this client_oid is the order ID sent by the user.
instrument_id String trading pair
result Boolean Call interface returns results. if the order cannot be canceled (already settled or canceled), the error description it returns to will display the corresponding reason.
Explanation

For bulk order cancellation, the parameters should be either all order_id or all client_oid, otherwise it will trigger an error code.

When using client_oid for bulk order cancellation, only one client_oid canceled for one trading pair, maximum 4 pairs per time. The user needs to make sure the ID does not repeat and there is no repetition alert. In case of repetition, only the latest entry will be canceled.

You may place up to 4 trading pairs with 10 orders at maximum for each pair. We recommend you to use the "Get order list" endpoint" before using the "Cancel multiple orders" endpoint to confirm the cancellation of orders.

Return Sample
{
    "btc-usdt":[
    {
       "result":true,
        "client_oid":"a123",
        "order_id": "2510832677225473"
     },
   {
       "result":true,
        "client_oid":"a1234",
        "order_id": "2510832677225474"
     }
],
"ltc-usdt":[
    {
       "result":true,
        "client_oid":"a12345",
        "order_id": "2510832677225475"
     },
   {
       "result":true,
        "client_oid":"a123456",
        "order_id": "2510832677225476"
     }
]
}

Get Order List

This retrieves the list of your orders from the most recent 3 months. This request supports paging and is stored according to the order time in chronological order from latest to earliest.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/margin/v3/orders

Example Authenticated Request

2018-09-12T07:49:43.306ZGET/api/spot/v3/orders?instrument_id=BTC-USDT&state=0&limit=2&after=2500723297223680

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pair symbol
state String Yes Order Status: -2 = Failed -1 = Canceled 0 = Open 1 = Partially Filled 2 = Completely Filled 3 = Submitting 4 = Canceling 6 = Incomplete (open + partially filled) 7 = Complete (canceled + completely filled)
after String Yes Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String Yes Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String Yes Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
order_id String Order ID
client_oid String Client-supplied order ID
price String Price of order
size String Size of order in unit of quote currency
notional String Allocated amount to buy (for market orders)
instrument_id String Trading pair symbol
type String Order type: limit or market (default: limit)
side String Buy or sell
timestamp String Time of order creation
filled_size String Quantity filled
filled_notional String Amount filled
order_type String Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
state String Order Status: -2 = Failed -1 = Canceled 0 = Open 1 = Partially Filled 2 = Completely Filled 3 = Submitting 4 = Canceling
price_avg String Average filled price
Notes

status is the older version of state and both can be used interchangeably in the short term. It is recommended to switch to state.

The client_oid is optional. It should be a unique ID generated by your trading system. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

If the order is not filled in the order life cycle, the record may be removed.

The status of unfilled orders may change during the time of endpoint request and response, depending on the market condition.

Example Response
[
    [
        {
            "client_oid":"oktlever56",
            "created_at":"2019-03-20T08:21:49.000Z",
            "filled_notional":"0",
            "filled_size":"0",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2512264176206848",
            "order_type":"0",
            "price":"3613.3",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "state":"open",
            "state": "0",    
            "timestamp":"2019-03-20T08:21:49.000Z",
            "type":"limit"
        },
        {
            "client_oid":"oktlever55",
            "created_at":"2019-03-20T08:21:49.000Z",
            "filled_notional":"0",
            "filled_size":"0",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2512264174306304",
            "order_type":"0",
            "price":"3613.3",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "state":"open",
            "state": "0",    
            "timestamp":"2019-03-20T08:21:49.000Z",
            "type":"limit"
        }
    ],
    {
        "before":"2512264176206848",
        "after":"2512264174306304"
    }
]

Get Order Details

Get order details by order ID,Canceled unfilled orders will be kept in record for 2 hours only.

Rate limit:20/2s
HTTP Requests

GET /api/margin/v3/orders/<order_id>

or

GET /api/margin/v3/orders/<client_oid>

End Certificate Request Sample

2018-09-13T02:39:22.475ZGET/api/margin/v3/orders/23458?instrument_id=btc-usdt

or

2018-09-13T02:39:22.475ZGET/api/margin/v3/orders/ebetd2?instrument_id=btc-usdt

Requests Parameters
Parameters Parameters Types Description
instrument_id String [required]trading pair
order_id String [required]order ID
client_oid String [ required ] The client_oid type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported
Return Parameters
Parameters Parameters Types Description
order_id String order ID
client_oid String the order ID customised by yourself
price String price
size String size of order
notional String buying amount(for market orders)
instrument_id String trading pair
side String order side
type String order type
timestamp String order creation date
filled_size String size filled
filled_notional String amount filled
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
state String Order state("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling,)
price_avg String Average price
Explanation

"status" is the older version of the "state" parameter and is compatible in the short term. It is recommended to switch to "state".

Only fill in either parameter client_oid or order_id

The client_oid type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported , and needs to make sure the ID does not repeat and there is no repetition alert. In case of repetition, only the latest entry will be queried .

If the order is not filled in the order lifecycle, its record may be removed, the status code 404 may be returned as there are no matches.

Unfilled order status may change according to the market conditions at the time period between your request creation and the server’s response.

state include(all, open, part_filled, canceling, filled, cancelled)

Return Sample
{
    "client_oid":"",
    "created_at":"2019-03-18T03:45:55.000Z",
    "filled_notional":"1.504",
    "filled_size":"0.4",
    "funds":"",
    "instrument_id":"EOS-USDT",
    "notional":"",
    "order_id":"2499854635054080",
    "order_type":"0",
    "price":"3.76",
    "product_id":"EOS-USDT",
    "side":"buy",
    "size":"0.4",
    "state":"filled",
    "state": "-2",       
    "timestamp":"2019-03-18T03:45:55.000Z",
    "type":"limit"
}

Get All Open Orders

This retrieves the list of your current open orders. Pagination is supported and the response is sorted with most recent first in reverse chronological order.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/margin/v3/orders\_pending

Example Authenticated Request

2019-03-20T07:51:51.138ZGET/api/margin/v3/orders_pending?limit=2&instrument_id=btc-usdt&after=2500723297223680

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pair symbol
after String No Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String No Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
order_id String Order ID
client_oid String Client-supplied order ID
price String Price of order
size String Size of order in unit of quote currency
notional String Amount allocated for buying. This value will be returned for market orders
instrument_id String Trading pair symbol
type String Order type: limit or market (default: limit)
side String Buy or sell
timestamp String Time of order creation
filled_size String Quantity filled
filled_notional String Amount filled
order_type String Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1: Post only 2: Fill or Kill 3: Immediate Or Cancel
state String Order Status: 0 = Open
Notes

The parameter status is the older version of state and is compatible in the short term. It is recommended to switch to state.

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

Only partially filled and open orders will be returned via this endpoint.

The status of unfilled orders may change during the time of endpoint request and response, depending on the market condition.

Return Sample
[
    [
        {
            "client_oid":"oktlever56",
            "created_at":"2019-03-20T08:21:49.000Z",
            "filled_notional":"0",
            "filled_size":"0",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2512264176206848",
            "order_type":"0",
            "price":"3613.3",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "state":"open",
            "state": "0",    
            "timestamp":"2019-03-20T08:21:49.000Z",
            "type":"limit"
        },
        {
            "client_oid":"oktlever55",
            "created_at":"2019-03-20T08:21:49.000Z",
            "filled_notional":"0",
            "filled_size":"0",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2512264174306304",
            "order_type":"0",
            "price":"3613.3",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "state":"open",
            "state": "0",    
            "timestamp":"2019-03-20T08:21:49.000Z",
            "type":"limit"
        }
    ],
    {
        "before":"2512264176206848",
        "after":"2512264174306304"
    }
]

Get Transaction Details

Retrieve recently filled transaction details. Pagination is supported and the response is sorted with most recent first in reverse chronological order. Data for up to 3 months can be retrieved.

Rate limit: 20 requests per 2 seconds

HTTP Request

GET /api/margin/v3/fills

Example Authenticated Request

2018-09-13T02:44:54.823ZGET/api/margin/v3/fills?order_id=23239&instrument_id=btc-usdt&limit=1&from=2&to=4

Parameters
Parameters Parameters Types Required Description
order_id String No Order ID, Complete transaction details for will be returned if the instrument_id is left blank
instrument_id String Yes Trading pair symbol
after String No Pagination of data to return records earlier than the requested order_id
before String No Pagination of data to return records newer than the requested order_id
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
ledger_id String Bill record ID
instrument_id String Trading pair symbol
price String Price
size String Size of order
order_id String Order ID
timestamp String Time of order creation
exec_type String Taker or maker (T or M)
fee String Transaction fee
side String The side that pays the trading fees, such as buy, sell, or points_fee
Notes

Transaction Fees

New status for spot trading transaction details: fee is either a positive number (invitation rebate) or a negative number (transaction fee deduction).

Liquidity

The exec_type specifies whether the order is maker or taker. ‘M’ stands for Maker and ‘T’ stands for Taker.

Pagination

The ledger_id is listed in a descending order, from biggest to smallest. The first ledger_id in this page can be found under OK-BEFORE, and the last one can be found under OK-AFTER. It would be easier to retrieve to other ledger_id by referring to these two parameters.

Example Response
[
    [
        {
            "created_at":"2019-03-18T03:45:57.000Z",
            "exec_type":"M",
            "fee":"0.0004",
            "instrument_id":"EOS-USDT",
            "ledger_id":"77622945",
            "liquidity":"M",
            "order_id":"2499854635054080",
            "price":"3.76",
            "product_id":"EOS-USDT",
            "side":"buy",
            "size":"0.4",
            "timestamp":"2019-03-18T03:45:57.000Z"
        },
        {
            "created_at":"2019-03-18T03:45:57.000Z",
            "exec_type":"M",
            "fee":"0",
            "instrument_id":"EOS-USDT",
            "ledger_id":"77622944",
            "liquidity":"M",
            "order_id":"2499854635054080",
            "price":"3.76",
            "product_id":"EOS-USDT",
            "side":"sell",
            "size":"1.504",
            "timestamp":"2019-03-18T03:45:57.000Z"
        }
    ],
    {
        "before":"77622945",
        "after":"77622944"
    }
]

Public-Margin Trading Market Data

This endpoint provides snapshots of market data and is publicly accessible without account authentication.

Spot and margin trading shares the same market data, please visit the spot trading section of the document for details. If more comprehensive data is needed, please refer to the Websocket section of the document.

Futures Trading API

Retrieve market data, account info, order operations, order inquires, and bills of futures trading.

Futures Positions

Retrieve the information on all your positions in the futures account. You are recommended to get the information one token at a time to improve performance.

HTTP Request

GET /api/futures/v3/position

Rate Limit: 5 requests per 2 seconds
Example Request

GET/api/futures/v3/position

Response
Cross Margin
Parameters Type Description
margin_mode String Account Type: crossed
liquidation_price String Estimated liquidation price
long_qty String Quantity of long positions
long_avail_qty String Available long positions that can be closed
long_avg_cost String Average price for opening long positions
long_settlement_price String Standard settlement price for long positions
realised_pnl String Realized profits of long positions
short_qty String Quantity of short positions
short_avail_qty String Available short positions that can be closed
short_avg_cost String Average price for opening short positions
short_settlement_price String Standard settlement price for short positions
instrument_id String Contract ID, e.g. “BTC-USD-180213”
leverage String Leverage ratio
created_at String Creation time
updated_at String Latest time margin was adjusted
short_margin String Margin for short positions
short_pnl String Profit of short positions
short_pnl_ratio String Profit rate of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
short_settled_pnl String Realized Profit of Short Positions
long_margin String Margin for long positions
long_pnl String Profit of long positions
long_pnl_ratio String Profit rate of long positions
long_unrealised_pnl String Unrealized profits and losses of long positions
long_settled_pnl String Realized Profit of Long Positions
last String Last traded price
Fixed-margin
Parameters Type Description
margin_mode String Account Types: fixed
long_qty String Quantity of long positions
long_avail_qty String Available long positions that can be closed
long_margin String Margin for long positions
long_liqui_price String Forced liquidation price for long positions
long_pnl_ratio String Profit and loss ratio of long positions
long_avg_cost String Average price for opening long positions
long_settlement_price String Standard settlement price for long positions
realised_pnl String Realized profit and loss
long_leverage String Leverage ratio for long pos
short_qty String Quantity of short positions
short_avail_qty String Available short positions that can be closed
short_margin String Margin ratio for short positio
short_liqui_price String Forced liquidation price for short positions
short_pnl_ratio String Profit and loss ratio of short positions
short_avg_cost String Average price for opening short positions
short_settlement_price String Standard settlement price of short positions
short_leverage String Leverage ratio for short positions
instrument_id String Contract ID, e.g. “BTC-USD-180213”
created_at(long) String Creation time
updated_at String Latest time margin was adjusted
short_margin_ratio String Margin ratio of short positions
short_maint_margin_ratio String Maintenance margin ratio of short positions
short_pnl String Profit of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
short_settled_pnl String Realized profit of Short Positions
long_margin_ratio String Margin ratio of long positions
long_maint_margin_ratio String Maintenance margin ratio of long positions
long_pnl String Profit of long positions
long_unrealised_pnl String Unrealized profits and losses of long positions
long_settled_pnl String Realized Profit of Long Positions
last String Last traded price
Example Response
Cross-margin
{
    "result":true,
    "holding":[
        [
            {
                "long_qty":"0",
                "long_avail_qty":"0",
                "long_margin":"0",
                "long_liqui_price":"0",
                "long_pnl_ratio":"0.49329759",
                "long_avg_cost":"3.546",
                "long_settlement_price":"3.546",
                "realised_pnl":"0",
                "short_qty":"0",
                "short_avail_qty":"0",
                "short_margin":"0",
                "short_liqui_price":"0",
                "short_pnl_ratio":"-0.48525469",
                "short_avg_cost":"3.549",
                "short_settlement_price":"3.549",
                "instrument_id":"EOS-USD-190329",
                "long_leverage":"10",
                "short_leverage":"10",
                "created_at":"2019-03-13T14:53:49.000Z",
                "updated_at":"2019-03-15T08:03:12.000Z",
                "margin_mode":"fixed",
                "last":"67.905"
            },
            {
                "long_qty":"40",
                "long_avail_qty":"20",
                "long_margin":"10.64042157",
                "long_liqui_price":"3.449",
                "long_pnl_ratio":"0.0262021",
                "long_avg_cost":"3.75912443",
                "long_settlement_price":"3.75912443",
                "realised_pnl":"-3.90853564",
                "short_qty":"0",
                "short_avail_qty":"0",
                "short_margin":"0",
                "short_liqui_price":"0",
                "short_pnl_ratio":"-0.13195657",
                "short_avg_cost":"3.71926557",
                "short_settlement_price":"3.71926557",
                "instrument_id":"EOS-USD-190628",
                "long_leverage":"10",
                "short_leverage":"10",
                "created_at":"2019-03-15T09:13:58.000Z",
                "updated_at":"2019-03-19T09:59:32.000Z",
                "margin_mode":"fixed",
                "last":"67.905"
            },
            {
                "long_qty":"0",
                "long_avail_qty":"0",
                "long_margin":"0",
                "long_liqui_price":"0",
                "long_pnl_ratio":"0",
                "long_avg_cost":"0",
                "long_settlement_price":"0",
                "realised_pnl":"0",
                "short_qty":"0",
                "short_avail_qty":"0",
                "short_margin":"0",
                "short_liqui_price":"0",
                "short_pnl_ratio":"-0.89445103",
                "short_avg_cost":"145.88",
                "short_settlement_price":"145.88",
                "instrument_id":"BCH-USD-190329",
                "long_leverage":"0",
                "short_leverage":"10",
                "created_at":"2019-02-19T10:31:39.000Z",
                "updated_at":"2019-03-15T08:00:38.000Z",
                "margin_mode":"fixed",
                "last":"67.905"
            }
        ]
    ]
}

Futures Positions of a Contract

Retrieve information on your positions of a single contract.

HTTP Request

GET /api/futures/v3/&lt;instrument_id&gt;/position

Rate Limit: 20 requests per 2 seconds
Example Request

GET/api/futures/v3/ BTC-USD-180309 /position

Parameters
Parameter Type Required Description
instrument_id String Yes Contract ID, e.g.“BTC-USD-180213”
Response
Cross margin
Parameter Type Description
margin_mode String Account Type: crossed
liquidation_price String Estimated liquidation price
long_qty String Quantity of long positions
long_avail_qty String Available long positions that can be closed
long_avg_cost String Average price for opening long positi
long_settlement_price String Standard settlement price for long positions
realised_pnl String Realised profit and loss
leverage String Leverage ratio
short_qty String Quantity of short positions
short_avail_qty String Available short positions that can be closed
short_avg_cost String Average price for opening short positions
short_settlement_price String Standard settlement price for short positions
instrument_id String Contract ID, e.g. “BTC-USD-180213”
created_at String Creation time
updated_at String Latest time margin was adju
short_margin String Margin for short positions
short_pnl String Profit of short positions
short_pnl_ratio String Profit ratio of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
short_settled_pnl String Realized Profit of Short Positions
long_margin String Margin for long positions
long_pnl String Profit of long positions
long_pnl_ratio String Profit rate of long positions
long_unrealised_pnl String Unrealized profit and loss of long positions
long_settled_pnl String Realized profit of long Positions
last String Last traded price
Fixed margin
Parameter Type Description
margin_mode String Account Types: fixed
long_qty String Quantity of long positions
long_avail_qty String Available long positions that can be closed
long_margin String Margin ratio for long positions
long_liqui_price String Forced liquidation price for long positions
long_pnl_ratio String Profit and loss ratio of long positions
long_avg_cost String Average price for opening positions
long_settlement_price String Standard settlement price
realised_pnl String Realize profit and loss of long positions
long_leverage String Leverage ratio for long positions
short_qty String Quantity of short positions
short_avail_qty String Available short positions that can be closed
short_margin String Margin for short positions
short_liqui_price String Forced liquidation price for short positions
short_pnl_ratio String Profit and loss ratio of short positions
short_avg_cost String Average price for opening positions
short_settlement_price String Standard settlement price
realised_pnl String Realized profit and loss of long positions
short_leverage String Leverage ratio for short positions
instrument_id String Contract ID, e.g. “BTC-USD-180213”
created_at(long) String Creation time
updated_at String Latest time margin was adjusted
short_margin_ratio String Margin ratio of short positions
short_maint_margin_ratio String Maintenance margin ratio of short positions
short_pnl String Profit of short positions
short_unrealised_pnl String Unrealized profit and loss of short positions
short_settled_pnl String Realized profit of short positions
long_margin_ratio String Margin ratio of long positions
long_maint_margin_ratio String Maintenance margin ratio of long positions
long_pnl String Profit of long positions
long_unrealised_pnl String Unrealized profit and loss of long positions
long_settled_pnl String Realized profit of long positions
last String Last traded price
Example Response
{
    "result":true,
    "holding":[
        {
            "long_qty":"40",
            "long_avail_qty":"20",
            "long_margin":"10.64042157",
            "long_liqui_price":"3.449",
            "long_pnl_ratio":"-0.01365059",
            "long_avg_cost":"3.75912443",
            "long_settlement_price":"3.75912443",
            "realised_pnl":"-3.90853564",
            "short_qty":"0",
            "short_avail_qty":"0",
            "short_margin":"0",
            "short_liqui_price":"0",
            "short_pnl_ratio":"-0.09252645",
            "short_avg_cost":"3.71926557",
            "short_settlement_price":"3.71926557",
            "instrument_id":"EOS-USD-190628",
            "long_leverage":"10",
            "short_leverage":"10",
            "created_at":"2019-03-15T09:13:58.000Z",
            "updated_at":"2019-03-19T09:59:32.000Z",
            "margin_mode":"fixed"
        }
    ],
    "margin_mode":"fixed"
}

Futures Account of all Currency

Retrieve information from all tokens in the futures account. You are recommended to get the information one token at a time to improve performance.

HTTP Request

GET /api/futures/v3/accounts

Rate Limit: once per 10 seconds
Example Request

GET/api/futures/v3/accounts

Return Parameters
Cross-margin
Parameter Type Description
currency String Token symbol, eg.'BTC'
margin_mode String Account Type: crossed
equity String Equity of the account (Dynamic benefits of an account)
total_avail_balance String Balance of the account (Static benefits of an account)
margin String Margin (frozen for open orders + open interests)
margin_frozen String Margin frozen for open interests
margin_for_unfilled String Margin frozen for open orders
realized_pnl String Realized profit and loss
unrealized_pnl String Unrealized profit and loss
margin_ratio String Margin ratio
maint_margin_ratio String Maintenance Margin Ratio
liqui_mode string Liquidation mode: tier(partial), legacy (complete)
can_withdraw string Transferable amount
liqui_fee_rate string forced-liquidation fee
Fixed-margin
Parameter Type Description
currency String Token symbol, e.g., ‘BTC’
margin_mode String Account Types: fixed
fixed_balance String Account balance
available_qty String Available quantity
balance String Account balance (contract)
margin_frozen String Margin forzen for open interests
margin_for_unfilled String Margin frozen for open orders
realized_pnl String Realized profit and loss
unrealized_pnl String Unrealized profit and loss
equity String Equity of the account (Dynamic benefits of an account)
total_avail_balance String Balance of the account (Static benefits of an account)
auto_margin String 1 means auto_margin has been opened; 0 means auto_margin has not been opened
liqui_mode string Liquidation mode: tier(partial), legacy (complete)
can_withdraw string Transferable amount
Notes

For "all open interests/all account info" futures account endpoints, if no position/token is held then no response will be returned. For "single open interests/single account info" endpoints, if no position/token is held then the response will return with default value.

Fixed-margin mode:

equity: Account equity = Balance of Funding Account + Balance of Fixed-margin Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts

total_avail_balance: Available Balance = Balance of Funding Account + Balance of Fixed-margin Account + RPL (Realized Profit and Loss) of the Contract - Maintenance Margin of the Open Interests - Margin frozen for Open Orders

Cross-margin mode:

equity: Account Equity = Balance of Fund Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts

total_avail_balance: Available Balance = Balance of Fund Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts - Maintenance Margin of the Open Interests - Margin frozen for Open Orders

Example Response
{
    "info":{
        "bch":{
            "auto_margin":"0",
            "contracts":[
                {
                    "available_qty":"0.80838321",
                    "fixed_balance":"0",
                    "instrument_id":"BCH-USD-190329",
                    "margin_for_unfilled":"0",
                    "margin_frozen":"0",
                    "realized_pnl":"0",
                    "margin_ratio":"0.0982",
                    "maint_margin_ratio":"0.02",                    
                    "unrealized_pnl":"0"
                    "can_withdraw":"0.80838322"
                }
            ],
            "equity":"0.80838321",
            "margin_mode":"fixed",
            "total_avail_balance":"0.80838321"
        },
        "eos":{
            "auto_margin":"0",
            "contracts":[
                {
                    "available_qty":"40.37069445",
                    "fixed_balance":"0",
                    "instrument_id":"EOS-USD-190329",
                    "margin_for_unfilled":"0",
                    "margin_frozen":"0",
                    "realized_pnl":"0",
                    "margin_ratio":"0.0982",
                    "maint_margin_ratio":"0.02", 
                    "unrealized_pnl":"0"
                    "can_withdraw":"0.80838322"
                },
                {
                    "available_qty":"40.37069445",
                    "fixed_balance":"14.54895721",
                    "instrument_id":"EOS-USD-190628",
                    "margin_for_unfilled":"0",
                    "margin_frozen":"10.64042157",
                    "realized_pnl":"-3.90853564",
                    "margin_ratio":"0.0982",
                    "maint_margin_ratio":"0.02", 
                    "unrealized_pnl":"-0.259"
                    "can_withdraw":"0.80838322"
                }
            ],
            "equity":"50.75220665",
            "margin_mode":"fixed",
            "total_avail_balance":"40.37069445"
        }
    }
}

Futures Account of a Currency

Retrieve the futures account information of a single token.

HTTP Request

GET /api/futures/v3/accounts/{currency}

Rate Limit: 20 requests per 2 seconds
Example Request

GET/api/futures/v3/accounts/btc

Parameters
Parameters Type Required Description
currency String Yes Token symbol, eg.'BTC'
Response
Cross margin
Parameter Type Description
margin_mode String Account Type: crossed
equity String Equity of the account (Dynamic benefits of an account)
total_avail_balance String Balance of the account (Static benefits of an account)
margin String Margin (frozen for open orders + open interests)
margin_frozen String Margin frozen for open interests
margin_for_unfilled String Margin frozen for open orders
realized_pnl String Realized profit and loss
unrealized_pnl String Unrealized profit and loss
margin_ratio String Margin ratio
maint_margin_ratio String Maintenance margin ratio
liqui_mode string Liquidation mode: tier(partial), legacy (complete)
can_withdraw string transferrable amount
liqui_fee_rate string forced-liquidation fee
Fixed margin
Parameter Type Description
margin_mode String Account Types: fixed
fixed_balance String Account balance
available_qty String Available quantity
margin_frozen String Position margin
margin_for_unfilled String Margin on hold for open orders
realised_pnl String realised profit and loss
unrealised_pnl String Unrealised profit and loss
equity String Equity of the account (Dynamic benefits of an account)
total_avail_balance String Balance of the account (Static benefits of an account)
auto_margin String 1. auto_margin has been opened 0, auto_margin has not been opened
liqui_mode string Liquidation mode: tier(partial)
can_withdraw string transferrable amount
Notes

For "all open interests/all account info" futures account endpoints, if no position/token is held then no response will be returned. For "single open interests/single account info" endpoints, if no position/token is held then the response will return with default value.

Fixed-margin mode:

equity: Account equity = Balance of Funding Account + Balance of Fixed-margin Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts

total_avail_balance: Available Balance = Balance of Funding Account + Balance of Fixed-margin Account + RPL (Realized Profit and Loss) of the Contract - Maintenance Margin of the Open Interests - Margin frozen for Open Orders

Cross-margin mode:

equity: Account Equity = Balance of Fund Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts

total_avail_balance: Available Balance = Balance of Fund Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts - Maintenance Margin of the Open Interests - Margin frozen for Open Orders

Example Response
{
    "total_avail_balance":"32.35025896",
    "contracts":[
        {
            "available_qty":"32.35025896",
            "fixed_balance":"0",
            "instrument_id":"EOS-USD-190329",
            "margin_for_unfilled":"0",
            "margin_frozen":"0",
            "realized_pnl":"0",
            "unrealized_pnl":"0"
            "margin_ratio":"0.0982",
            "maint_margin_ratio":"0.02", 
            "can_withdraw":"0.80838322"
        },
        {
            "available_qty":"32.35025896",
            "fixed_balance":"22.5693927",
            "instrument_id":"EOS-USD-190628",
            "margin_for_unfilled":"0",
            "margin_frozen":"18.63686772",
            "realized_pnl":"-3.93252498",
            "unrealized_pnl":"0.2515"
            "margin_ratio":"0.0982",
            "maint_margin_ratio":"0.02", 
            "can_withdraw":"0.80838322"
        }
    ],
    "equity":"51.23863304",
    "margin_mode":"fixed",
    "auto_margin":"0"
}

Get Futures Leverage

Retrieve leverage ratio of the futures account

HTTP Request

GET /api/futures/v3/accounts/&lt;currency&gt;/leverage

Rate Limit: 5 requests per 2 seconds
Example Request

GET/api/futures/v3/accounts/btc/leverage

Parameters
Parameter Type Required Description
currency String Yes Token symbol, eg.'BTC'
Response
Cross-margin
Parameters Type Description
margin_mode String Account Type: crossed
currency String Token symbol, e.g. BTC
leverage String Leverage ratio, 1-100x
Fixed-margin
Parameters Type Description
margin_mode String Account Type: fixed
instrument_id String Contract ID, e.g.'BTC-USD-180213'
long_leverage String Leverage ratio for long positions, 1-100x
short_leverage String Leverage ratio for short positions, 1-100x
Notes

For cross-margin mode, only one leverage ratio is allowed per trading pair. For fixed-margin mode, one leverage ratio is allowed per contract per side (long or short).

Example:

Cross-magin mode: if you are holding a 10x BTC quarterly contract, then you must also use 10x leverage for opening any other new BTC contracts. But you can choose 20x leverage for opening contracts of other tokens.

Fixed-margin mode: if you have opened a long 10x BTC quarterly contract, then you can choose 10x for opening new long weekly contracts, 20x for short contracts and 20x for bi-weekly BTC contracts.

Example Response
{
    "BTC-USD-190322":{
        "long_leverage":"10",
        "short_leverage":"10"
    },
    "margin_mode":"fixed",
    "BTC-USD-190628":{
        "long_leverage":"10",
        "short_leverage":"10"
    },
    "BTC-USD-190329":{
        "long_leverage":"10",
        "short_leverage":"10"
    }
}

Set Futures Leverage

This is used to set the leverage level for assets in the futures account. When placing an order, the system will deploy the leverage level you set accordingly.

HTTP Request

POST /api/futures/v3/accounts/&lt;currency&gt;/leverage

Rate Limit: 5 requests per 2 seconds
Example Request

POST/api/futures/v3/accounts/btc/leverage{"leverage":"10"} (Cross_margin)

POST/api/futures/v3/accounts/btc/leverage{"instrument_id":"BTC-USD-180213","direction":"long","leverage":"10"}(Fixed_margin)

Parameters
Crossed-margin
Parameter Type Required Description
leverage String Yes 1-100x leverage
currency String Yes Token symbol, e.g. 'btc'
Fixed-margin
Parameter Type Required Description
currency String Yes Token, e.g. “btc”
instrument_id String Yes Contract ID, e.g. “BTC-USD-180213”
direction String Yes opening side (long or short)
leverage String Yes 1-100x leverage
Response
Cross-margin
Parameter Type Description
margin_mode String Account Type: crossed
currency String Token, e.g. 'BTC'
leverage String 1-100x leverage ratio
result String Result of request, true or false
Fixed-margin
Parameter Type Description
margin_mode String Account Type: fixed
instrument_id String Contract ID, e.g. “BTC-USD-180213”
direction String opening side (long or short)
leverage String 1-100x leverage ratio
result String Result of request, true or false
Notes

For cross-margin mode, only one leverage ratio is allowed per trading pair. For fixed-margin mode, one leverage ratio is allowed per contract per side (long or short).

Example Response
{
    "result":"true",
    "margin_mode":"fixed",
    "EOS-USD-190628":{
        "short":"10",
        "long":"10"
    }
}

Bills Details

Retrieve the bills of the futures account. The bill refers to all the records that results in changing the balance of an account. This API can retrieve data in the last 2 days.

HTTP Request

GET /api/futures/v3/accounts/&lt;currency&gt;/ledger

Rate Limit: 5 requests per 2 seconds
Example Request

GET/api/futures/v3/accounts/eos/ledger?after=1&limit=3

Parameters
Parameter Type Required Description
currency String Yes Token symbol, e.g 'BTC'
after String No Pagination of data to return records earlier than the requested ledger_id
before String No Pagination of data to return records newer than the requested ledger_id
limit String No Number of results per request. The maximum is 100; the default is 100
type String No 1.Open Long 2.Open Short 3.Close Long 4.Close Short 5.Transaction Fee 6.Transfer In,7.Transfer Out 8.Settled RPL 13. Forced-closed Long 14. Forced-closed Short 15. Delivered Closed Long 16. Delivered Closed Short 17.Settle UPL - Long 18.Settle UPL - Short 20.Partially-closed Short 21.Partially-closed Long
Response
Parameter Type Description
ledger_id String ID of the bill record
currency String Token symbol, e.g., ‘BTC’
amount String Amount
type String Type of bill record
timestamp String The time that the record is created
details String If the type is generated by transaction, the order_id and instrument_id will be included in details
order_id long Order ID
balance String Balance of positions opened. Balance positive if the open interest is long while negative if short. The balance will be '0' if the type is fee.
Type Value Type Description
transfer String Funds transferred in/out
match String Open Long/Open Short/Close Long/Close Short
fee String Transaction Fee
settlement String Settlement/Societal loss/Settle Long/Settle Short
liquidation String Forced Close Long/Forced Close Short/Delivery Close Long/Delivery Close Short
Example Response
[
    {
        "ledger_id":"2510946217197569",
        "timestamp":"2019-03-20T02:46:38.000Z",
        "amount":"-0.0080819",
        "balance":"0",
        "currency":"EOS",
        "type":"fee",
        "details":{
            "order_id":"2510946213248000",
            "instrument_id":"EOS-USD-190628"
        }
    },
    {
        "ledger_id":"2510946217197568",
        "timestamp":"2019-03-20T02:46:38.000Z",
        "amount":"0",
        "balance":"10",
        "currency":"EOS",
        "type":"match",
        "details":{
            "order_id":"2510946213248000",
            "instrument_id":"EOS-USD-190628"
        }
    },
    {
        "ledger_id":"2508090544914461",
        "timestamp":"2019-03-19T14:40:24.000Z",
        "amount":"-0.00529521",
        "balance":"0",
        "currency":"EOS",
        "type":"fee",
        "details":{
            "order_id":"2506982456445952",
            "instrument_id":"EOS-USD-190628"
        }
    }
]

Place Order

OKEx futures trading only supports limit orders. You can place an order only if you have sufficient funds. Once your order is placed, the amount will be put on hold during the order lifecycle. The assets and amount on hold depends on the order's specific type and parameters.

Rate Limit: 40 requests per 2 seconds
HTTP Request

POST /api/futures/v3/order

Example Request

POST/api/futures/v3/order{"client_oid": “y12233456”,"order_type”:”1”,"instrument_id":"BTC-USD-180213","type":"1","price":"432.11","size":"2","match_price":"0"}

Parameters
Parameter Type Required Description
client_oid String No Client-supplied order ID that you can set. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
type String Yes 1:open long 2:open short 3:close long 4:close short
price String Yes Price of each contract
size String Yes The buying or selling quantity
match_price String No Whether order is placed at best counter party price (‘0’:no ‘1’:yes). The parameter is defaulted as ‘0’. If it is set as '1', the price parameter will be ignored,When posting orders at best bid price, order_type can only be '0' (regular order)
order_type String No ‘0’: Normal order. Parameter will be deemed as '0' if left blank. ‘1’: Post only (Order shall be filled only as maker) ‘2’: Fill or Kill (FOK) ‘3’: Immediate or Cancel (IOC)
Response
Parameter Type Description
order_id String Order ID. If order placement fails, this value will be -1.
client_oid String Client-supplied order ID
error_code String Error code for order placement. Success = 0
error_message String Error message will be returned if order placement fails, otherwise it will be blank
result String The result of the request
Notes

instrument_id

The instrument_id must match a valid contract ID. The contract list is available via the /instrument endpoint.

client_oid

The client_oid is optional. It should be a unique ID generated by your trading system. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

type

You can specify the order type when placing an order. If you are not holding any positions, you can only open new positions, either long or short. You can only close the positions that has been already held.

The price must be specified in tick size product units. The tick size is the smallest unit of price. Can be obtained through the /instrument interface.

price

The price is the price of buying or selling a contract. price must be an incremental multiple of the tick_size. tick_size is the smallest incremental unit of price, which is available via the /instrument endpoint.

size

size is the number of contracts bought or sold. The value must be an integer.

match_price

The match_price means that you prefer the order to be filled at a best price of the counterpart, where your buy order will be filled at the price of Ask-1. The match_price means that your sell order will be filled at the price of Bid-1.

Order life cycle

The HTTP Request will respond when an order is either rejected (insufficient funds, invalid parameters, etc) or received (accepted by the matching engine). A 200 response indicates that the order was received and is active. Active orders may execute immediately (depending on price and market conditions) either partially or fully. A partial execution will put the remaining size of the order in the open state. An order that is filled completely, will go into the completed state.

Users listening to streaming market data are encouraged to use the client_oid field to identify their received messages in the feed. The REST response with a server order_id may come after the received message in the public data feed.

Response

A successful order will be assigned an order id. A successful order is defined as one that has been accepted by the matching engine. Open orders will not expire until filled or canceled.

Example Response
{
    "result":true,
    "error_message":"",
    "error_code":"0",
    "client_oid":"oktfuture8",
    "order_id":"2517062038154240"
}

Batch Orders

Batch contract placing order operation.Maximum 10 orders can be placed at a time for each contract.

Rate Limit: 20 requests per 2 seconds
HTTP Request

POST /api/futures/v3/orders

Example Request

POST/api/futures/v3/orders{"instrument_id":"ETH-USD-181228","orders_data":[{"client_oid":"f379a96206fa4b778e1554c6dc969687","order_type”:”1”,"type":"1","price":"180.0","size":"1","match_price":"0"}]}`

Parameters
Parameter Type Required Description
instrument_id String Yes Contract ID, e.g.“BTC-USD-180213”
order_data List Yes JSON String for placing multiple orders, for example: [{order_type:"0",price:"5",size:"2",type:"1",match_price:"1"},{order_type:"0",price:"2",size:"3",type:"1",match_price:"1"}] A maximum of 10 orders can be placed. If the match_price is ‘1’, the order_type must be ‘0’
leverage String Yes Leverage ratio, 1-100x
client_oid String No Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
order_type String No ‘0’: Normal order. Parameter will be deemed as '0' if left blank. ‘1’: Post only (Order shall be filled only as maker) ‘2’: Fill or Kill (FOK) ‘3’: Immediate or Cancel (IOC)
Response
Parameters Parameters Types Description
order_info String Order details
order_id String Order ID. If order placement fails, this value will be -1.
client_oid String Client-supplied order ID
error_code String Error code for order placement. Success = 0
error_message String Error message will be returned if order placement fails, otherwise it will be blank
result String The result of the request
Notes

The client_oid is optional. It should be a unique ID generated by your trading system. This parameter is used to identify your orers in the public orders feed. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

As long as any of the orders are successful, result returns ‘true’. The response message is returned in the same order as that of the order_data submitted. If the order fails to be placed, order_id is ‘-1’.

Example Response
{
    "result":true,
    "order_info":[
        {
            "error_message":"",
            "error_code":"0",
            "client_oid":"oktfuture18",
            "order_id":"2517748155771904"
        },
        {
            "error_message":"",
            "error_code":"0",
            "client_oid":"oktfuture19",
            "order_id":"2517748157541376"
        }
    ]
}

Cancel Order

This is used to cancel an unfilled order.

HTTP Request

POST /api/futures/v3/cancel_order/<instrument_id>/<order_id or client_oid>

Rate limit: 40 requests per 2 seconds

Example Request

POST /api/futures/v3/cancel_order/BTC-USD-180309/1407616797780992

or

POST /api/futures/v3/cancel_order/BTC-USD-180309/ee1407616797780992

Parameters
Parameter Type Required Description
order_id String No Either client_oid or order_id must be present. Order ID
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
client_oid String No Either client_oid or order_id must be present. Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
Response
Parameter Type Description
order_id String Order ID
result String The result of canceling the order. Error code will be returned if failed
client_oid String Client-supplied order ID
instrument_id String Contract ID
Notes

Only one of order_id or client_oid parameters should be passed per request

The client_oid should be unique. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

If the order cannot be canceled because it has already filled or been canceled, the reason will be returned with the error message.

The response includes order_id, which does not confirm that the orders has been canceled successfully. Orders that are being filled cannot be canceled whereas orders that have not been filled could been canceled.

Example Response
1.by client_oid :

{"result": true, "error_message": "", "error_code": 0, "client_oid": "oktfuture9", "order_id": "2517497557707776"}

{
    "result":true,
    "client_oid":"oktfuture10",
    "order_id":"2517514559122432",
    "instrument_id":"EOS-USD-190628"
}

2. by  order_id:

{
    "result":true,
    "order_id":"2517535534836736",
    "instrument_id":"EOS-USD-190628"
}

Batch Cancel Orders

Cancel multiple open orders with order_id or client_oid,Maximum 10 orders can be cancelled at a time for each contract."

Rate Limit: 20 requests per 2 seconds
HTTP Request

POST /api/futures/v3/cancel_batch_orders/<instrument_id>

Example Request

POST /api/futures/v3/cancel_batch_orders/BTC-USD-180309{"order_ids":[1600593327162368,1600593327162369]}

OR

POST /api/futures/v3/cancel_batch_orders/BTC-USD-180309{"client_oids":[t1600593327162368,c1600593327162369]}

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes The orders of the contract to be canceled
order_ids List<String> No Either client_oid or order_id must be present. ID of the orders to be canceled
client_oids List<String> No Either client_oid or order_id must be present. Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
Response
Parameters Parameters Types Description
instrument_id String The orders of the contract to be canceled
order_id String ID of the orders to be canceled
result String The result of canceling the order
client_oids String Client-supplied order ID
Notes

For batch order cancellation, only one of order_id or client_oid parameters should be passed per request. Otherwise an error will be returned.

When using client_oid for batch order cancellation, up to 10 orders can be canceled per trading pair. You need to make sure the ID is unique. In case of multiple identical client_oid, only the latest entry will be returned.

Cancellations of orders are not guaranteed. After placing a cancel order you should confirm they are successfully canceled by requesting the "Get Order List" endpoint.

Example Response
{
    "result":true,
    "order_ids":[
        "2517748157541376",
        "2517748155771904"
    ],
    "instrument_id":"EOS-USD-190628",
    "client_oids":[
        "oktfuture19",
        "oktfuture18"
    ]
}

Order List

This retrieves the list of your orders from the last 7 days.This request supports paging and is stored according to the order time in chronological order from latest to earliest.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/futures/v3/orders/<instrument_id>

Example Request

GET/api/futures/v3/orders/BTC-USD-190628?state=2&after=1&limit=2

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pair symbol
state String Yes Order Status: -2 = Failed -1 = Canceled 0 = Open 1 = Partially Filled 2 = Completely Filled 3 = Submitting 4 = Canceling 6 = Incomplete (open + partially filled) 7 = Complete (canceled + completely filled)
after String Yes Pagination of data to return records earlier than the requested order_id
before String Yes Pagination of data to return records new than the requested order_id
limit String Yes Number of results per request. The maximum is 100; the default is 100
Response
Parameter Type Description
instrument_id String Contract ID, e.g. “BTC-USD-180213”
client_oid String Client-supplied order ID
size String Quantity
timestamp String Order creation time
filled_qty String Filled quantity
fee String Trasnaction Fees
order_id String Order ID
price String Order price
price_avg String Average filled price
type String Type (1: open long 2: open short 3: close long 4: close short)
contract_val String Par value of the contract
leverage String Leverage , 1-100x
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
pnl String Profit and loss
state String -2:Failed,-1:Canceled,0:Open ,1:Partially Filled, 2:Fully Filled,3:Submitting,4:Canceling
Notes

status is the older version of state and both can be used interchangeably in the short term. It is recommended to switch to state.

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

If the order is not filled in the order life cycle, the record may be removed.

The state of unfilled orders may change during the time of endpoint request and response, depending on the market condition.

Example Response
{
    "result":true,
    "order_info":[
        {
            "instrument_id":"EOS-USD-190628",
            "size":"10",
            "timestamp":"2019-03-20T10:04:55.000Z",
            "filled_qty":"10",
            "fee":"-0.00841043",
            "order_id":"2512669605501952",
            "price":"3.668",
            "price_avg":"3.567",
            "state":"2",
            "state": "2",     
            "type":"4",
            "contract_val":"10",
            "leverage":"10",
            "client_oid":"",
            "pnl":"1.09510794",
            "order_type":"0"
        },
        {
            "instrument_id":"EOS-USD-190628",
            "size":"10",
            "timestamp":"2019-03-20T02:46:38.000Z",
            "filled_qty":"10",
            "fee":"-0.0080819",
            "order_id":"2510946213248000",
            "price":"3.712",
            "price_avg":"3.712",
            "state":"2",
            "state": "2",     
            "type":"2",
            "contract_val":"10",
            "leverage":"10",
            "client_oid":"",
            "pnl":"0",
            "order_type":"0"
        }
    ]
}

Order Details

Retrieve order details by order ID. Unfilled orders will be kept in record for only two hours after it is canceled.

Rate limit: 40 requests per 2 seconds
HTTP Request

GET /api/futures/v3/orders/&lt;instrument_id&gt;/&lt;order_id&gt;

or

GET /api/futures/v3/orders/&lt;instrument_id&gt;/&lt;client_oid&gt;

Example Request

GET/api/futures/v3/orders/BTC-USD-180213/888845120785408

or

GET/api/futures/v3/orders/BTC-USD-180213/888845120785408ee

Parameters
Parameter Type Required Description
order_id String Yes Order ID
instrument_id String Yes Contract ID,e.g.“BTC-USD-180213”
client_oid String Yes Client-supplied order ID
Response
Parameter Type Description
instrument_id String Contract ID, e,g. “BTC-USD-180213”
size String Quantity
timestamp String Order creation time
filled_qty String Filled quantity
fee String Transaction Fee
order_id String Order ID
price String Order Price
price_avg String Average Filled Price
type String Type (1: open long 2: open short 3: close long 4: close short)
contract_val String Contract value
leverage String Leverage , 1-100x
client_oid String Client-supplied order ID
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
pnl String Profit and loss
state String -2:Failed,-1:Canceled,0:Open ,1:Partially Filled, 2:Fully Filled,3:Submitting,4:Canceling)
Notes

statusis the older version ofstateand both can be used interchangeably in the short term. It is recommended to switch tostate`.

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

If the order is not filled in the order life cycle, the record may be removed.

Unfilled order status may change according to the market conditions.

Example Response
{
    "instrument_id":"EOS-USD-190628",
    "size":"10",
    "timestamp":"2019-03-20T02:46:38.000Z",
    "filled_qty":"10",
    "fee":"-0.0080819",
    "order_id":"2510946213248000",
    "price":"3.712",
    "price_avg":"3.712",
    "state":"2",
    "state": "2",     
    "type":"2",
    "contract_val":"10",
    "leverage":"10",
    "client_oid":"",
    "pnl":"0",
    "order_type":"0"
}

Transaction Details

Retrieve recently filled transaction details. Pagination is supported and the response is sorted with most recent first in reverse chronological order. Data from the past 7 days can be retrieved.

Rate limit: 20 requests per 2 seconds

HTTP Request

GET /api/futures/v3/fills

Example Request

GET/api/futures/v3/fills?order_id=123123&instrument_id=BTC-USD-180309&after=1&limit=50

Parameters
Parameter Type Description
order_id String No Order ID, Complete transaction details for will be returned if the instrument_id is left blank
instrument_id String Yes Contract ID, e.g., ‘BTC-USD-180213’
after String No Pagination of data to return records earlier than the requested trade_id
before String No Pagination of data to return records newer than the requested trade_id
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Types Description
trade_id String ID of the bill record
instrument_id String Contract ID, e.g. “BTC-USD-180213”
price String Price
order_qty String Quantity
order_id String Order ID
created_at String Time that the order is filled
exec_type String Taker or Maker (T or M)
fee String Transaction Fee
side String Side of the order (buy or sell)
Notes

Transaction Fees

If the value of the side is points_fee, the value of fee should be the amount settled by LP (Loyalty Points).

Liquidity

The exec_type specifies whether the order is maker or taker. ‘M’ stands for Maker and ‘T’ stands for Taker.

Pagination

The trade_id is listed in a descending order, from biggest to smallest. The first trade_idin this page can be found under OK-BEFORE, and the last one can be found under OK-AFTER. It would be easier to retrieve to other trade_id by referring to these two parameters.

Example Response
[
    {
        "trade_id":"2517062044057601",
        "instrument_id":"EOS-USD-190628",
        "price":"3.692",
        "order_qty":"1",
        "order_id":"2517062038154240",
        "created_at":"2019-03-21T04:41:58.0Z",
        "exec_type":"T",
        "fee":"-0.00081257",
        "side":"buy"
    }
]

Contract Information

Get market data. This endpoint provides the snapshots of market data and can be used without verifications.

HTTP Request

GET /api/futures/v3/instruments

Rate Limit: 20 requests per 2 seconds
Example Request

GET /api/futures/v3/instruments

Response
Parameters Parameters Types Description
instrument_id String Contract ID, e.g. “BTC-USD-180213”
underlying_index String Trade currency, such as BTC in btc-usdt
quote_currency String Quote currency,such as USDT in btc-usdt
contract_val String Contract value (USD)
listing String Listing date
delivery String Delivery date
tick_size String Order price accuracy
trade_increment String Order quantity accuracy
alias String this_week next_week quarter
Notes

The tick size is the smallest unit of price. The order price must be a multiple of the tick size. If the tick size is 0.01, entering a price of 0.022 will be adjusted to 0.02 instead.

Example Response
[
    {
        "instrument_id":"BTC-USD-190322",
        "underlying_index":"BTC",
        "quote_currency":"USD",
        "tick_size":"0.01",
        "contract_val":"100",
        "listing":"2019-03-08",
        "delivery":"2019-03-22",
        "trade_increment":"1",
        "alias":"this_week"
    },
    {
        "instrument_id":"BTC-USD-190329",
        "underlying_index":"BTC",
        "quote_currency":"USD",
        "tick_size":"0.01",
        "contract_val":"100",
        "listing":"2018-12-14",
        "delivery":"2019-03-29",
        "trade_increment":"1",
        "alias":"next_week"
    },
    {
        "instrument_id":"BTC-USD-190628",
        "underlying_index":"BTC",
        "quote_currency":"USD",
        "tick_size":"0.01",
        "contract_val":"100",
        "listing":"2019-03-15",
        "delivery":"2019-06-28",
        "trade_increment":"1",
        "alias":"quarter"
    }

   ...

]

Setting Account Mode

This is used to set account mode of a contract. The account mode cannot be changed if there is open interest or open order.

Rate Limit: 5 requests per 2 seconds
HTTP Request

POST /api/futures/v3/accounts/margin_mode

Example Request

POST /api/futures/v3/accounts/margin_mode{"currency":"btc","margin_mode":"crossed"}

Parameters
Parameter Type Description
currency String Yes Token symbol, e.g., ‘BTC’
margin_mode String Yes Margin mode: ‘cross’ / ‘fixed’
Response
Parameter Type Description
currency String Token symbol, e.g., ‘BTC’
margin_mode String Margin mode: cross / fixed
result String Result of the request
error_code String Error code. It will return a ‘0’ if the order set up successfully.
error_message String The error_message would be blank if the order set up successfully. Otherwise, an error_message would be returned
Example Response

{
    "result":true,
    "error_message":"",
    "error_code":"0",
    "currency":"btc",
    "margin_mode":"crossed"
}

Market-Close All

Maximum of 999 contracts can be closed per request for BTC, and maximum of 9,999 contracts for other assets.

HTTP Request

POST /api/futures/v3/close_position

Rate Limit: 5 requests per 2 seconds
Example Request

POST /api/futures/v3/close_position{"instrument_id":"BTC-USD-180213","direction":"long"}

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID, e.g.“BTC-USD-180213”
direction String Yes Side (long or short)
Response
Parameters Parameters Types Description
instrument_id String Contract ID, e.g.“BTC-USD-180213”
direction String Side (long or short)
code String Error code. It will return a ‘0’ if the order is placed successfully. Otherwise, the corresponding error code will be shown to indicate the reason of order failure.
message String The error_message would be blank if the order is placed successfully. Otherwise, an error_message would be returned to signal failure of order placement.
result String The result of request
Example Response
{
    "result":true,
    "error_message":"",
    "error_code":0,
    "instrument_id":"BTC-USD-180213",
    "direction":"long"
}

Cancel all orders

This endpoint supports cancelation of all closed orders, excluding orders for opening positions.

HTTP Request

POST /api/futures/v3/cancel_all

Rate Limit: 5 requests per 2 seconds
Example Request

POST /api/futures/v3/cancel_all{"instrument_id":"BTC-USD-180213","direction":"long"}

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g.“BTC-USD-180213”
direction String Yes side (long or short)
Response
Parameters Parameters Types Description
instrument_id String Contract ID, e.g.“BTC-USD-180213”
direction String Side (long or short)
code String Error code. It will return a ‘0’ if the order is placed successfully. Otherwise, the corresponding error code will be shown to indicate the reason of order failure.
message String The error_message would be blank if the order is placed successfully. Otherwise, an error_message would be returned to signal failure of order placement.
result String Result of the request
Example Response
{
    "result":true,
    "error_message":"",
    "error_code":0,
    "instrument_id":"BTC-USD-180213",
    "direction":"long"
}

Place Algo Order

Includes trigger order, trail order, iceberg order and time-weighted average price .

Rate limit:20/2s

HTTP Request

POST /api/futures/v3/order_algo

Example

POST/api/futures/v3/order_algo{"instrument_id":"BTC-USD-190328","type":"1","trigger_price":"432.11","order_type":"1",“algo_price“:"341.99","size":"2"}(止盈止损)

Request Parameters

General Parameters

Parameters Type Mandatory Description
instrument_id String Yes Contract ID, e.g. BTC-USD-190328
type String Yes 1. open long; 2. open short; 3. close long; 4. close short
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price
size String Yes Total number of orders must be an integer between 1 and 1,000,000, incl. both numbers

Trigger Order (Maximum 10 orders)

Parameters Type Mandatory Description
trigger_price String Yes Trigger price must be between 0 and 1,000,000
algo_price String Yes Order price must be between 0 and 1,000,000

Trail Order (Maximum 10 orders)

Parameters Type Mandatory Description
callback_rate String Yes Callback rate must be between 0.001 (0.1%) and 0.05 (5%)
trigger_price String Yes Trigger price must be between 0 and 1,000,000

Iceberg Order (Maximum 6 orders)

Parameters Type Mandatory Description
algo_variance String Yes Order depth must be between 0.0001 (0.01%) and 0.01 (1%)
avg_amount String Yes Single order average amount must be an integer between 2 and 1,000, incl. both numbers (perpetual swap: integer between 2 and 500, incl. both numbers)
price_limit String Yes Price limit must be between 0 and 1,000,000

TWAP (Maximum 6 orders)

Parameters Type Mandatory Description
sweep_range String Yes Auto-cancelling order range must be between 0.005 (0.5%) and 0.01 (1%), incl. both numbers
sweep_ratio String Yes Auto-cancelling order rate must be between 0.01 and 1, incl. both numbers
single_limit String Yes Single order limit must be between 10 and 2,000, incl. both numbers (perpetual swap: integer between 2 and 500, incl. both numbers)
price_limit String Yes Price limit must be between 0 and 1,000,000, incl, 1,000,000
time_interval String Yes Time interval must be between 5 and 120, incl. both numbers

Return Parameters

Name Type Description
result String Parameters return result
instrument_id String Contract ID, e.g. BTC-USD-190328
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
algo_id String Order ID: when fail to place order, the value is -1
error_code String Error code will be 0 if the order is successfully placed, and will appear if order fails
error_message String Error message will be blank if order is successfully placed, and will appear if order fails
Example Response
{
    "result":true,
    "instrument_id":"BTC-USD-190328",
    "order_type":"1",
    "algo_id":"2517062038154240"
}

Cancel Algo Order

If user use “algo_id” to cancel unfulfilled orders, they can cancel a maximum of 6 iceberg/TWAP or 10 trigger/trail orders at the same time.

Rate limit:20/2s

HTTP Request

POST/api/futures/v3/cancel_algos

Example

POST/api/futures/v3/cancel_algos{“instrument_id":"BTC-USD-190328","order_type":“1”,"algo_ids":“198273485”}

Request Parameters

Name Type Mandatory Description
instrument_id String Yes Cancel specific types of contract
algo_ids String Yes Cancel specific order ID
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price

Return Parameters

Name Type Description
instrument_id String Cancel specific types of contract
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price
algo_ids String Cancel specific order ID
result String Parameter return result

Return Parameter

Return parameter is the order ID of canceled orders. This does not mean that the orders are successfully canceled. Orders that are pending cannot be canceled, only unfulfilled orders can be canceled.

Description

This does not guarantee orders are canceled successfully. Users are advised to request the order list to confirm after using the cancelation endpoint.

Example Response
{
    "result":true,
    "instrument_id":"BTC-USD-190328",
    "order_type":"1",
    "algo_id":"2517062038154240"
}

Get Algo Order List

Obtaining Order List

Rate limit:20/2s
HTTP Request

GET /api/futures/v3/order_algo/<instrument_id>

Example

GET/api/futures/v3/order_algo/BTC-USD-190328?order_type=1&status=2

Parameters

Name Type Mandatory Description
instrument_id String Yes Contract ID, e.g. BTC-USD-190328
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
status String See Description [Status and algo_ids are mandatory, select either one] Order status: (1. Pending; 2. 2. Effective; 3. Cancelled; 4. Partially effective; 5. Paused; 6. Order failed [Status 4 and 5 only applies to iceberg and TWAP orders]
algo_ids String See Description [status and algo_ids are mandatory, select either one] Enquiry specific order ID
before string No [Optional] Request page content after this ID (updated records)
after string No [Optional] Request page content before this ID (past records)
limit string No [Optional] The number of results returned by the page. Default and maximum are both 100 (see the description on page for more details)

Return Parameters

Name Type Description
instrument_id String Contract ID, e.g. BTC-USD-190328
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
timestamp String Order time
rejected_at String Order expiration time
algo_id String Order ID
status String Order status: 1. Pending; 2. Effective; 3. Canceled (4. Partially effective; 5. Paused)
type String Order type (1. Open long; 2. Open short; 3. Close long; 4. Close short)
leverage String Margin leverage: value:10/20; default 10x

Trigger Orders

Parameters Type Description
trigger_price String Trigger price must be greater than 0
algo_price String Algo price must be between 0 and 1,000,000 incl. 1,000,000
size String Order amount must be an integer between 1 and 1,000,000, incl. both numbers
real_amount String Actual order amount

Trail Orders

Parameters Type Description
callback_rate String Callback rate must be between 0.001 (0.1%) and 0.05 (5%), incl. both numbers
trigger_price String Trigger price must be between 0 and 1,000,000, incl. 1,000,000
size String Order amount must be an integer between 1 and 1,000,000, incl. 1,000,000
real_amount String Actual order amount

Iceberg Orders

Parameters Type Description
algo_variance String Order depth must be between 0 and 0.01 (1%), incl. 0.01
size String Order amount must be an integer between 1 and 1,000,000, incl. 1,000,000
avg_amount String Average amount must be an integer between 2 and 500 (same for perpetual swap), incl. both numbers
price_limit String Price limit must be between 0 and 1,000,000, incl. 1,000,000
deal_value String Transacted volume

Time-weighted Average Price (TWAP)

Parameter Type Description
sweep_range String Auto-cancelling order range must be between 0.005 (0.5%) and 0.01 (1%), incl. both numbers
sweep_ratio String Auto-cancelling order rate must be between 0.01 and 1, incl. both numbers
size String Order size must be an integer between 1 and 1,000,000, incl. both numbers
single_limit String Single order limit must be between 10 and 2,000 (perpetual swap orders: integer between 2 and 500), incl. both numbers
price_limit String Price limit must be between 0 and 1,000,000, incl. 1,000,000
time_interval String Order time interval must be between 5 and 120, incl. both numbers
deal_value String Order volume
Example Response
{
    "instrument_id":"BTC-USD-190328",
    "order_type":"1",
    "algo_id":"2517062038154240"    
    "timestamp":"2019-03-25T03:45:17.376Z"
    "rejected_at":"2019-03-26T03:45:17.376Z"
    "status":"2"    
    "type":"3"   
    "leverage":"20"   
    "trigger_price":"2"   
    "algo_price":"2"   
    "size":"2000"  
    "real_amount":"1000"      
}

Public- Order Book

Retrieve a trading pair's order book. Pagination is not supported here; the entire orderbook will be returned per request. This is publicly accessible without account authentication. WebSocket is recommended here.

HTTP Requests

GET /api/futures/v3/instruments/&lt;instrument_id&gt;/book

Rate limit: 20 requests per 2 seconds
Example Request

GET/api/futures/v3/instruments/BTC-USD-180309/book?size=50

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
size String No Number of results per request. Maximum 200
depth String No Aggregation of the order book. e.g . 0.1, 0.001
Response
Parameters Type Description
asks String Selling side
bids String Buying side
timestamp String System timestamp
Explanation on the array returned

[411.8, 10, 8, 4]: 411.8 is the price; 10 is the quantity at the price; 8 is the quantity of the force-liquidated orders at the price; 4 is the number orders at the price

Notes

Aggregation of the order book means that orders within a certain price range is combined and considered as one order cluster.

When size is not passed in the parameters, one entry is returned; when size is 0, no entry is returned. The maximum size is 200. When requesting more than 200 entries, at most 200 entries are returned.

Example Response
{
    "bids":[
        [
            "3.596",
            "5125",
            "0",
            "15"
        ],
        [
            "3.595",
            "553",
            "0",
            "14"
        ]
    ],
    "asks":[
        [
            "3.597",
            "3181",
            "0",
            "18"
        ],
        [
            "3.598",
            "13912",
            "0",
            "31"
        ]
    ],
    "timestamp":"2019-03-22T01:59:34.707Z"
}

Public- All Tokens

Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours for all trading pairs. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/futures/v3/instruments/ticker

Example Request

GET /api/futures/v3/instruments/ticker

Response
Parameters Parameters Types Description
instrument_id String Contract ID,e.g. “BTC-USD-180213”
best_ask String Best ask price
best_bid String best bid price
last String Last traded price
high_24h String Highest price in the past 24 hours
low_24h String Lowest price in the past 24 hours
volume_24h String Trading volume of past 24 hours
timestamp String Timestamp
Example Response
[
    {
        "instrument_id":"BSV-USD-190329",
        "last":"65",
        "best_bid":"65",
        "best_ask":"65.03",
        "high_24h":"68.59",
        "low_24h":"63.72",
        "volume_24h":"62944",
        "timestamp":"2019-03-22T02:14:55.716Z"
    },
    {
        "instrument_id":"BSV-USD-190628",
        "last":"67.05",
        "best_bid":"67.03",
        "best_ask":"67.05",
        "high_24h":"69.84",
        "low_24h":"65.28",
        "volume_24h":"221458",
        "timestamp":"2019-03-22T02:14:55.716Z"
    },
    {
        "instrument_id":"EOS-USD-190628",
        "last":"3.601",
        "best_bid":"3.6",
        "best_ask":"3.601",
        "high_24h":"3.73",
        "low_24h":"3.511",
        "volume_24h":"29673717",
        "timestamp":"2019-03-22T02:14:55.716Z"
    }

]

Public- Token Information

Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours for a particular trading pair. This is publicly accessible without account authentication.

HTTP Request

GET /api/futures/v3/instruments/&lt;instrument_id&gt;/ticker

Rate limit: 20 requests per 2 seconds
Example Request

GET/api/futures/v3/instruments/BTC-USD-180309/ticker

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”

The Contract ID will be verified. if the ID differs from that in the database, an error code will be returned.

Response
Parameters Type Description
instrument_id String Contract ID,e.g. “BTC-USD-180213”
best_ask String Best ask price
best_bid String best bid price
last String Last traded price
high_24h String Highest price in the past 24 hours
low_24h String Lowest price in the past 24 hours
volume_24h String Trading volume of past 24 hours
timestamp String Timestamp
Notes

The parameters for highest price, lowest price and trading volume are all computed based on the data in the last 24 hours.

Example Response
{
    "instrument_id":"EOS-USD-190628",
    "last":"3.708",
    "best_bid":"3.707",
    "best_ask":"3.708",
    "high_24h":"3.799",
    "low_24h":"3.494",
    "volume_24h":"24884595",
    "timestamp":"2019-03-21T03:15:50.144Z"
}

Public- Filled Orders

Get the recent 300 transactions of all contracts. Pagination is not supported here. The entire book will be returned in one request. WebSocket is recommended here.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/futures/v3/instruments/&lt;instrument_id&gt;/trades

Example Request

GET /api/futures/v3/instruments/BTC-USD-180309/trades?after=2517062044057601&limit=2

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
after String No Pagination of data to return records earlier than the requested trade_id
before String No Pagination of data to return records newer than the requested trade_id
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
timestamp String Filled time
trade_id String Transaction time ID
price String Filled price
qty String Filled size
side String Filled side
Notes

The side indicates the side of the order that is filled by the taker. The “taker” means actively taking the order on the order book. The buy indicates the taker is taking liquidity from the order book, so the price rises as a result, whereas the sell indicates the price falls as a result.

The trade_id is the ID referring to the filled order; it is generated incrementally and could be incomplete in some cases.

Example Response
[
    [
        {
            "trade_id":"2522253054345222",
            "side":"sell",
            "price":"3.625",
            "qty":"24",
            "timestamp":"2019-03-22T02:42:07.323Z"
        },
        {
            "trade_id":"2522252973080580",
            "side":"buy",
            "price":"3.626",
            "qty":"6",
            "timestamp":"2019-03-22T02:42:06.081Z"
        },
        {
            "trade_id":"2522252969410561",
            "side":"buy",
            "price":"3.626",
            "qty":"6",
            "timestamp":"2019-03-22T02:42:06.026Z"
        }
    ],
    {

    }
]

Public- Market Data

Retrieve the candlestick charts of the trading pairs. This API can retrieve the latest 1,440 entries of data. Charts are returned in groups based on requested granularity. Maximum 2,880 recent strings of chart data can be retrieved.

HTTP Request
Rate limit: 20 requests per 2 seconds

GET /api/futures/v3/instruments/&lt;instrument-id&gt;/candles

Example Request

GET/api/futures/v3/instruments/EOS-USD-190628/candles?start=2019-03-18T02:31:00Z&end=2019-03-20T02:55:00Z&granularity=86400

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
start String No Start time in ISO 8601
end String NO End time in ISO 8601
granularity String No Desired time slice in seconds[60/180/300 900/1800/3600/7200/14400/21600/43200/86400/604800]

Timestamp must be in ISO 8601 format, otherwise an error be returned.

Response
Parameters Parameters Types Description
time String Timestamp
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
currency_volume String Volume of a specific token

Notes

Both parameters will be ignored if either one of start or end are not provided. The last 200 records of data will be returned if the time range is not specified in the request.

The granularity field must be one of the following values: [60, 180, 300, 900, 1800, 3600, 7200, 14400, 43200, 86400, 604800]. Otherwise, your request will be rejected. These values correspond to timeslices representing [1 minute, 3 minutes, 5 minutes, 15 minutes, 30 minutes, 1 hour, 2 hours, 6 hours, 12 hours, 1 day, and 1 week] respectively.

The candlestick data may be incomplete, and should not be polled repeatedly.

The maximum data set is 200 candles for a single request. If the request made with the parameters start, end and granularity will result in more data than that is allowed, only 200 candles will be returned. If finer granularity over a larger time range is needed, please make multiple requests as needed.

The data returned will be arranged in an array as below: [timestamp,open,high,low,close,volume,currency_volume]

Example Response
[
    [
        "2019-03-20T16:00:00.000Z",
        "3.721",
        "3.743",
        "3.677",
        "3.708",
        "8422410",
        "22698348.04828491"
    ],
    [
        "2019-03-19T16:00:00.000Z",
        "3.731",
        "3.799",
        "3.494",
        "3.72",
        "24912403",
        "67632347.24399722"
    ],
    [
        "2019-03-18T16:00:00.000Z",
        "3.729",
        "3.78",
        "3.698",
        "3.731",
        "17545741",
        "46945274.21772249"
    ]
]

Public- Hold Amount

Get the String of futures with hold.

HTTP Requests

GET/api/futures/v3/accounts/<instrument_id>/holds

Limit: 20 times / 2s
Request Sample

GET/api/futures/v3/accounts/BTC-USD-181228/holds

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
Return Parameters
Parameters Parameters Types Description
instrument_id String Contract ID, e.g. “BTC-USD-180213”
amount String Hold amount
timestamp String Timestamp
Return Sample
{
    "amount":"0.3073",
    "instrument_id":"EOS-USD-SWAP",
    "timestamp":"2019-03-26T03:19:48.035Z"
}

Public- Indices

Retrieve indices of tokens. This is publicly accessible without account authentication.

HTTP Requests

GET/api/futures/v3/instruments/<instrument_id>/index

Rate Limit: 20 requests per 2 seconds
Example Request

GET/api/futures/v3/instruments/EOS-USD-190628/index

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Index, e.g. “BTC-USD-190628”
Response
Parameters Parameters Types Description
instrument_id String Index, e.g.“BTC-USD-190628”
index String Index price
timestamp String Timestamp
Notes

The token displayed after the hyphen “-” is the quote currency of the index.

Example Response
{
    "instrument_id":"EOS-USD-190628",
    "index":"3.59125725275",
    "timestamp":"2019-03-22T05:18:05.756Z"
}

Public- Exchange Rates

Retrieve the fiat exchange rates. This is publicly accessible without account authentication.

HTTP Request

GET /api/futures/v3/rate

Rate limit: 20 requests per 2 seconds
Request Sample

GET /api/futures/v3/rate

Parameters
Parameters Type Description
instrument_id String e.g. USD_CNY
rate String Exchange rates
timestamp String Timestamp
Example Response
{
    "instrument_id":"USD_CNY",
    "rate":"6.701",
    "timestamp":"2019-03-22T05:08:44.323Z"
}

Public- Estimated Delivery Price

Get the estimated delivery price. It is available 3 hours before delivery. This is a public endpoint, no identity verification is needed.

HTTP Requests

GET /api/futures/v3/instruments/estimated_price

Limit: 20 times / 2s
Request Sample

GET/api/futures/v3/instruments/BTC-USD-180309/estimated_price

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID, e.g. “BTC-USD-180213”
Return Parameters
Parameters Parameters Types Description
instrument_id String Contract ID, e.g. “BTC-USD-180213”
settlement_price String Estimated delivery price
timestamp String Timestamp
Return Sample
{
    "instrument_id":"EOS-USD-181026",
    "settlement_price":"0",
    "timestamp":"2018-10-23T10:07:44.095Z"
}

Public- Open Interests

Retrieve the total open interest of a contract on OKEx. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/futures/v3/instruments/&lt;instrument_id&gt;/open_interest

Example Request

GET/api/futures/v3/instruments/BTC-USD-180309/open_interest

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
Response
Parameters Parameters Types Description
instrument_id String Contract ID, e.g. “BTC-USD-180213”
amount String Total open Stringerest
timestamp String Timestamp
Example Response
{
    "instrument_id":"EOS-USD-190628",
    "amount":"5311831",
    "timestamp":"2019-03-22T05:56:06.726Z"
}

Public- Price Limit

Retrieve the ceiling of the buy price and floor of sell price of the contract. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/futures/v3/instruments/&lt;instrument_id&gt;/price_limit

Example Request

GET/api/futures/v3/instruments/BTC-USD-180309/price_limit

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
highest String Ceiling of buying price
lowest String Floor of selling price
timestamp String Timestamp
Example Response
{
    "instrument_id":"EOS-USD-190628",
    "highest":"3.707",
    "lowest":"3.491",
    "timestamp":"2019-03-22T06:05:08.502Z"
}

Public- Mark Price

Retrieve the ceiling of the buy price and floor of sell price of the contract. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/futures/v3/instruments/&lt;instrument_id&gt;/price_limit

Example Request

GET/api/futures/v3/instruments/BTC-USD-180309/price_limit

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
highest String Ceiling of buying price
lowest String Floor of selling price
timestamp String Timestamp
Example Response
{
    "instrument_id":"EOS-USD-190628",
    "highest":"3.707",
    "lowest":"3.491",
    "timestamp":"2019-03-22T06:05:08.502Z"
}

Public- Force-Liquidated Orders

Retrieve the force liquidated orders. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/futures/v3/instruments/&lt;instrument_id&gt;/liquidation

Example Request

GET/api/futures/v3/instruments/BTC-USD-180309/liquidation?status=0&after=1&limit=50

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
status String Yes 0:unfilled in the recent 7 days; 1:filled orders in the recent 7 days)
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
size String Quantity
created_at String Order creation time
loss String Loss resulted by forced liquidation
price String Order price
type String 3:Close long 4:Close short
Example Response
[
    {
        "loss":"0.0",
        "size":"945",
        "price":"5.623",
        "created_at":"2018-10-21T01:20:18.0Z",
        "instrument_id":"EOS-USD-181026",
        "type":"1"
    },
    {
        "loss":"0.0",
        "size":"37",
        "price":"5.623",
        "created_at":"2018-10-21T01:20:18.0Z",
        "instrument_id":"EOS-USD-181026",
        "type":"1"
    }
]

Public- Tag Price

Get the tag price. This is a public endpoint, no identity verification is needed.

HTTP Requests

GET/api/futures/v3/instruments/<instrument_id>/mark_price

Request Sample

GET/api/futures/v3/instruments/BTC-USD-180309/mark_price

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
Return Parameters
Parameters Parameters Types Description
instrument_id String Contract ID,e.g. “BTC-USD-180213”
mark_price String Specify the contract price
timestamp timestamp Timestamp
Explanation

In order to prevent the malicious manipulation of the market by individual users, the contract price fluctuates violently, we set the marked price according to spot index and reasonable basis difference.

Return Sample
{
    "mark_price":"3.591",
    "instrument_id":"EOS-USD-190628",
    "timestamp":"2019-03-22T06:28:53.208Z"
}

Perpetual Swap API

Retrieve market data, account info, order operations, order inquires, and bills of perpetual swap trading.

Perpetual Swap Positions

Retrieve the information on all your positions in the swap account. You are recommended to get the information one token at a time to improve performance.

Rate limit:Once per 10 seconds
HTTP Request

GET /api/swap/v3/position

Example Request

GET/api/swap/v3/position

Response
Cross-Margin
Parameters Type Description
margin_mode String Margin-mode: crossed
liquidation_price String Estimated liquidation price
position String Positions open
avail_position String Positions available to be closed
margin String Margin
avg_cost String Avg. position price
settlement_price String Settlement price
instrument_id String Contract ID
leverage String Leverage level
realized_pnl String Realized Profit and loss
side String Side
timestamp String Creation time
maint_margin_ratio String Maintenance Margin Ratio
settled_pnl String Realized Profit of Positions
last String Last traded price
Fixed-margin
Parameters Type Description
margin_mode String Margin mode: fixed
liquidation_price String Estimated liquidation price
position String Positions open
avail_position String Positions available to be closed
margin String Margin
avg_cost String Avg. position price
settlement_price String Settlement price
instrument_id String Contract ID
leverage String Leverage level
realized_pnl String Realized profit and loss
side String Side
timestamp String Creation time
maint_margin_ratio String Maintenance Margin Ratio
settled_pnl String Realized Profit of Positions
last String Last traded price
Example Response
[
    {
        "margin_mode":"crossed",
        "holding":[
            {
                "avail_position":"1",
                "avg_cost":"3.640",
                "instrument_id":"EOS-USD-SWAP",
                "leverage":"5",
                "liquidation_price":"0.000",
                "margin":"0.5519",
                "position":"1",
                "realized_pnl":"-0.0006",
                "settlement_price":"3.640",
                "side":"short",
                "timestamp":"2019-03-25T03:46:10.336Z",
                "last":"67.905"
            }
        ]
    }
]

Perpetual Swap Positions of a Contract

Retrieve information on your positions of a single contract.

HTTP Request

GET /api/swap/v3/&lt;instrument_id&gt;/position

Example Request

GET /api/swap/v3/BTC-USD-SWAP/position

Parameters
Parameter Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP

*##### Response

Cross margin
Parameter Type Description
margin_mode String Margin-mode: crossed
liquidation_price String Estimated liquidation price
position String Positions open
avail_position String Positions available to be closed
margin String Margin
avg_cost String Avg. position price
settlement_price String Settlement price
instrument_id String Contract ID
leverage String Leverage level
realized_pnl String Realized profit and loss
side String Side
timestamp String Latest time margin was adjusted
maint_margin_ratio String Maintenance Margin Ratio
settled_pnl String Realized profit of positions
last String Last traded price
Fixed margin
Parameter Type Description
margin_mode String Margin mode: fixed
liquidation_price String Estimated liquidation price
position String Positions open
avail_position String Positions available to be closed
margin String Margin
avg_cost String Avg. position price
settlement_price String Settlement price
instrument_id String Contract ID
leverage String Leverage level
realized_pnl String Realized profit and loss
side String Side
timestamp String Latest time margin was adjusted
maint_margin_ratio String Maintenance Margin Ratio
settled_pnl String Realized profit of positions
last String Last traded price
Example Response
{
    "margin_mode":"crossed",
    "holding":[
        {
            "avail_position":"1",
            "avg_cost":"3.640",
            "instrument_id":"EOS-USD-SWAP",
            "leverage":"5",
            "liquidation_price":"0.000",
            "margin":"0.5506",
            "position":"1",
            "realized_pnl":"-0.0006",
            "settlement_price":"3.640",
            "side":"short",
            "timestamp":"2019-03-25T03:46:10.336Z",
            "last":"67.905"
        }
    ]
}

Perpetual Swap Account of all Currency

Retrieve information from all tokens in the perpetual swap account. Margin ratio is set as 10,000 when users have no open position.

Rate Limit: once per 10 seconds
HTTP Request

GET /api/swap/v3/accounts

Example Request

GET /api/swap/v3/accounts

Return Parameters
Parameters Type Description
equity String Equity of the account (Dynamic benefits of an account)
total_avail_balance String Balance of the account (Static benefits of an account)
fixed_balance String Balance of fixed margin account
margin String Margin for open positions
realized_pnl String Realized profits and losses
unrealized_pnl String Unrealized profits and losses
margin_ratio String Margin Ratio
instrument_id String Contract ID
margin_frozen String Initial margin on hold
timestamp String Creation time
margin_mode String Margin Mode: crossed / fixed
maint_margin_ratio String Maintenance Margin Ratio
Notes

For "all open interests/all account info" futures and perpetual swap account endpoints, if no position/token is held then no response will be returned. For "single open interests/single account info" endpoints, if no position/token is held then the response will return with default value.

Fixed-margin mode:

equity: Account equity = Balance of Funding Account + Balance of Fixed-margin Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts

total_avail_balance: Available Balance = Balance of Funding Account + Balance of Fixed-margin Account + RPL (Realized Profit and Loss) of the Contract - Maintenance Margin of the Open Interests - Margin frozen for Open Orders

Cross-margin mode:

equity: Account Equity = Balance of Fund Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts

total_avail_balance: Available Balance = Balance of Fund Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts - Maintenance Margin of the Open Interests - Margin frozen for Open Orders

Example Response
{
    "info":[
        {
            "equity":"3.0139",
            "fixed_balance":"0.0000",
            "instrument_id":"EOS-USD-SWAP",
            "margin":"0.5523",
            "margin_frozen":"0.0000",
            "margin_mode":"crossed",
            "margin_ratio":"1.0913",
            "realized_pnl":"-0.0006",
            "timestamp":"2019-03-25T03:46:10.336Z",
            "total_avail_balance":"3.0000",
            "unrealized_pnl":"0.0145"
        }
    ]
}

Perpetual Swap Account of a Currency

Retrieve the perpetual swap account information of a single trading pair. Margin ratio set as 10,000 when users have no open position.

Rate Limit: 20 requests per 2 seconds

HTTP Request

GET /api/swap/v3/&lt;instrument_id&gt;/accounts

Example Request

GET /api/swap/v3/BTC-USD-SWAP/accounts

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
Response
Parameters Type Description
equity String Equity of the account (Dynamic benefits of an account)
total_avail_balance String Balance of the account (Static benefits of an account)
fixed_balance String Balance of fixed margin account
margin String Margin for open positions
realized_pnl String Realized profits and losses
unrealized_pnl String Unrealized profits and losses
margin_ratio String Margin Ratio
instrument_id String Contract ID
margin_frozen String Initial margin on hold
timestamp String Creation time
margin_mode String Margin Mode: crossed / fixed
maint_margin_ratio String Maintenance Margin Ratio
Notes

For "all open interests/all account info" futures and perpetual swap account endpoints, if no position/token is held then no response will be returned. For "single open interests/single account info" endpoints, if no position/token is held then the response will return with default value.

Fixed-margin mode:

equity: Account equity = Balance of Funding Account + Balance of Fixed-margin Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts

total_avail_balance: Available Balance = Balance of Funding Account + Balance of Fixed-margin Account + RPL (Realized Profit and Loss) of the Contract - Maintenance Margin of the Open Interests - Margin frozen for Open Orders

Cross-margin mode:

equity: Account Equity = Balance of Fund Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts

total_avail_balance: Available Balance = Balance of Fund Account + RPL (Realized Profit and Loss) of All Contracts + UPL (Unrealized Profit and Loss) of All Contracts - Maintenance Margin of the Open Interests - Margin frozen for Open Orders

Example Response
{
    "info":{
        "equity":"3.0117",
        "fixed_balance":"0.0000",
        "instrument_id":"EOS-USD-SWAP",
        "margin":"0.5519",
        "margin_frozen":"0.0000",
        "margin_mode":"crossed",
        "margin_ratio":"1.0913",
        "realized_pnl":"-0.0006",
        "timestamp":"2019-03-25T03:46:10.336Z",
        "total_avail_balance":"3.0000",
        "unrealized_pnl":"0.0123"
    }
}

Get Swap Leverage

Retrieve the leverage ratio and margin mode of a perpetual swap

Rate limit:5 requests per 2 seconds
HTTP Requests

GET /api/swap/v3/accounts/&lt;instrument_id&gt;/settings

Example Request

GET /api/swap/v3/accounts/BTC-USD-SWAP/settings

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
Response
Parameters Type Description
long_leverage String Leverage level for long positions
margin_mode String Margin mode
short_leverage String Leverage level for short positions
instrument_id String Contract ID

Notes

For cross-margin mode, only one leverage ratio is allowed per trading pair. For fixed-margin mode, one leverage ratio is allowed per contract per side (long or short).

Example Response
{
    "long_leverage":"5.0000",
    "short_leverage":"5.0000",
    "margin_mode":"crossed",
    "instrument_id":"BTC-USD-SWAP"
}

Set Swap Leverage

Used to adjust the leverage for perpetual swap account

Rate Limit: 5 requests per 2 seconds

HTTP Requests

POST /api/swap/v3/accounts/&lt;instrument_id&gt;/leverage

Example Request

POST /api/swap/v3/accounts/BTC-USD-SWAP/leverage{"leverage": "10","side": "1"}

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
leverage String Yes New leverage level from 1-100
side String Yes '1’. Fixed-margin for long position; ‘2’. Fixed-margin for short position; ‘3’. Crossed-margin
Response
Parameters Type Description
long_leverage String Leverage level for long positions
margin_mode String Margin mode
short_leverage String Leverage level for short positions
instrument_id String Contract ID
Example Response
{
    "long_leverage":"10.0000",
    "short_leverage":"10.0000",
    "margin_mode":"crossed",
    "instrument_id":"BTC-USD-SWAP"
}

Bills Details

Retrieve the bills of the perpetual swap account. The bill refers to all the records that results in changing the balance of an account. This API can retrieve data from the last 7 days.

Rate limit:5 requests per 2 seconds
HTTP Request

GET /api/swap/v3/accounts/&lt;instrument_id&gt;/ledger

Example Request

GET /api/swap/v3/accounts/BTC-USD-SWAP/ledger?after=1&limit=3

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
after String No Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String No Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String No Number of results per request. The maximum is 100; the default is 100
type String No 1.Open Long 2.Open Short 3.Close Long 4.Close Short 5.Transaction Fee 6.Transfer In,7.Transfer Out 8.Settled RPL 13. Forced-closed Long 14. Forced-closed Short 15. Delivered Closed Long 16. Delivered Closed Short 17.Settle UPL - Long 18.Settle UPL - Short
Response
Parameters Type Description
ledger_id String ID of the bill record
amount String Amount
type String Type of bill record
fee String Transaction Fee
timestamp String Bill creation time
instrument_id String Contract ID
currency String Token, e.g. 'btc'
details String If the type is generated by transaction, the order_id and instrument_id will be included in details
order_id long Order ID
instrument_id String Contract ID, e.g.“BTC-USD-180213”
balance String Balance of positions opened. Balance positive if the open interest is long while negative if short. The balance will be '0' if the type is fee.

| Type Value | Type | Description | | transfer | String | Transfer in / out | | match | String | Change in amount because of trades | | settlement | String | Settlement/clawback | | liquidation | String | Full / partial liquidation | | funding | String | Funding fee | | margin | String | Change in amount after adjusting margin |

Example Response
[
    {
        "amount":"0.004742",
        "fee":"-0.000551",
        "type":"match",
        "instrument_id":"EOS-USD-SWAP",
        "ledger_id":"197429674941902848",
        "timestamp":"2019-03-25T05:56:31.286Z"
    },
    {
        "amount":"0.000000",
        "fee":"-0.000550",
        "type":"match",
        "instrument_id":"EOS-USD-SWAP",
        "ledger_id":"197364068049776640",
        "timestamp":"2019-03-25T03:46:10.335Z"
    },
    {
        "amount":"3.000000",
        "fee":"0.000000",
        "type":"transfer",
        "instrument_id":"EOS-USD-SWAP",
        "ledger_id":"197363052888057856",
        "timestamp":"2019-03-25T03:44:09.316Z"
    }
]

Place Order

OOKEx perpetual swap only supports limit orders. You can place an order only if you have sufficient funds. Once your order is placed, the amount will be put on hold during the order life cycle. The assets and amount put on hold depends on the order's specific type and parameters. Only USD is supported as quote currency.

Rate Limit: 40 requests per 2 seconds
HTTP Request

POST /api/swap/v3/order

Example Request

POST /api/swap/v3/order{"client_oid":"E12233456","size":"2","type":"1","match_price":"0","price":"432.11","order_type”:”1”,"instrument_id":"BTC-USD-SWAP"}

Parameters
Parameters Type Required Description
client_oid String No Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
size String Yes The buying or selling quantity
type String Yes 1:open long 2:open short 3:close long 4:close short
match_price String No Whether order is placed at best counter party price (‘0’:no ‘1’:yes). The parameter is defaulted as ‘0’. If it is set as '1', the price parameter will be ignored,When posting orders at best bid price, order_type can only be '0' (regular order)
price String Yes Price of each contract
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
order_type String No ‘0’: Normal order. Parameter will be deemed as '0' if left blank. ‘1’: Post only (Order shall be filled only as maker) ‘2’: Fill or Kill (FOK) ‘3’: Immediate or Cancel (IOC)

The parameters need to be verified: 1) The instrument_id must match a valid contract ID; 2) The price must meet the requirements of filled order price (neither premium ceiling nor liquidation price has been reached); 3) The types will trigger an error code if it is not one of: 1: open long; 2: open short; 3: close long 4: close short; 4) The size cannot be less than 0. It also cannot be larger than the available contract size.

Response
Parameter Type Description
order_id String Order ID. If order placement fails, this value will be -1.
client_oid String Client-supplied order ID
error_code String Error code for order placement. Success = 0
error_message String Error message will be returned if order placement fails, otherwise it will be blank
result String The result of the request
Notes

instrument_id

The instrument_id must match a valid contract ID. The contract list is available via the /instrument endpoint.

client_oid

The client_oid is optional and you can customize it using alpha-numeric characters with length 1 to 32. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique. In case of multiple identical client_oid, only the latest entry will be returned.

type

You can specify the order type when placing an order. If you are not holding any positions, you can only open new positions, either long or short. You can only close the positions that has been already held.

The price must be specified in tick size product units. The tick size is the smallest unit of price. Can be obtained through the /instrument interface.

price

The price is the price of buying or selling a contract. price must be an incremental multiple of the tick_size. tick_size is the smallest incremental unit of price, which is available via the /instrument endpoint.

size

size is the number of contracts bought or sold. The value must be an integer.

match_price

The match_price means that you prefer the order to be filled at a best price of the counterpart, where your buy order will be filled at the price of Ask-1. The match_price means that your sell order will be filled at the price of Bid-1.

Order life cycle

The HTTP Request will respond when an order is either rejected (insufficient funds, invalid parameters, etc) or received (accepted by the matching engine). A 200 response indicates that the order was received and is active. Active orders may execute immediately (depending on price and market conditions) either partially or fully. A partial execution will put the remaining size of the order in the open state. An order that is filled completely, will go into the completed state.

Users listening to streaming market data are encouraged to use the client_oid field to identify their received messages in the feed. The REST response with a server order_id may come after the received message in the public data feed.

Response

A successful order will be assigned an order id. A successful order is defined as one that has been accepted by the matching engine. Open orders will not expire until filled or canceled.

Example Response
{
    "error_message":"",
    "result":"true",
    "error_code":"0",
    "client_oid":"oktswap6",
    "order_id":"6a-d-54dcc6543-0"
}

Place Multiple Orders

Batch contract placing order operation.Maximum 10 orders can be placed at a time for each contract.

Rate Limit: 20 requests per 2 seconds
HTTP Request

POST /api/swap/v3/orders

Example Request

POST /api/swap/v3/orders{"instrument_id": "EOS-USD-SWAP","order_data":[{"client_oid": "oktswap14", "type": "1", "price": "3.2571000000000003", "size": "1", "match_price": "0"}, {"client_oid": "oktswap15", "type": "1", "price": "3.2571000000000003", "size": "1", "match_price": "0"}]}

Parameters
Parameter Type Required Description
order_data List Yes JSON String for placing multiple orders, for example: [{order_type:"0",price:"5",size:"2",type:"1",match_price:"1"},{order_type:"0",price:"2",size:"3",type:"1",match_price:"1"}] A maximum of 10 orders can be placed. If the match_price is ‘1’, the order_type must be ‘0’
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
order_type String No ‘0’: Normal order. Parameter will be deemed as '0' if left blank. ‘1’: Post only (Order shall be filled only as maker) ‘2’: Fill or Kill (FOK) ‘3’: Immediate or Cancel (IOC)
Response
Parameters Parameters Types Description
order_info String Order details
order_id String Order ID. If order placement fails, this value will be -1.
client_oid String Client-supplied order ID
error_code String Error code for order placement. Success = 0
error_message String Error message will be returned if order placement fails, otherwise it will be blank
result String The result of the request
Notes

The client_oid is optional. It should be a unique ID generated by your trading system. This parameter is used to identify your orers in the public orders feed. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

As long as any of the orders are successful, result returns ‘true’. The response message is returned in the same order as that of the order_data submitted. If the order fails to be placed, order_id is ‘-1’.

Example Response
{
    "order_info":[
        {
            "client_oid":"oktswap14",
            "error_code":"0",
            "error_message":"",
            "order_id":"6a-d-54df9a2ac-0"
        },
        {
            "client_oid":"oktswap15",
            "error_code":"0",
            "error_message":"",
            "order_id":"6a-d-54df9a2ad-0"
        }
    ],
    "result":"true"
}

Cancel an Order

This is used to cancel an unfilled order.

Rate limit: 40 requests per 2 seconds

HTTP Request

POST /api/swap/v3/cancel_order/<instrument_id>/<order_id or client_oid>

Example Request

POST /api/swap/v3/cancel_order/BTC-USD-SWAP/64686543235465768789

or

POST /api/swap/v3/cancel_order/BTC-USD-SWAP/64dfe

Parameters
Parameter Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
client_oid String No Either client_oid or order_id must be present. Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported
order_id String No Either client_oid or order_id must be present. Order ID

Request Parameters Verification: Contract ID and order ID must already exist

Response
Parameter Type Description
order_id String Order ID
result String The result of canceling the order. Error code will be returned if failed
client_oid String Client-supplied order ID
Notes

Only one of order_id or client_oid parameters should be passed per request

The client_oid should be unique. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

If the order cannot be canceled because it has already filled or been canceled, the reason will be returned with the error message.

The response includes order_id, which does not confirm that the orders has been canceled successfully. Orders that are being filled cannot be canceled whereas orders that have not been filled could been canceled.

Example Response
{
    "result":"true",
    "client_oid":"oktswap6",
    "order_id":"6a-d-54dcc6543-0"
}

Cancel multiple open orders

Cancel multiple open orders with order_id or client_oid,Maximum 10 orders can be cancelled at a time for each contract."

Rate Limit: 20 requests per 2 seconds
HTTP Requests

POST /api/swap/v3/cancel_batch_orders/<instrument_id>

Example Request

POST /api/swap/v3/cancel_batch_orders/BTC-USD-SWAP{"ids":["64-2a-17122d911-0","64-2b-17124f911-0","64-2c-17126f911-0"]}

or

POST /api/swap/v3/cancel_batch_orders/BTC-USD-SWAP{"client_oids":["64ae","64ed","efdfd"]}

Parameters
Parameters Parameters Types Required Description
instrument_id String Yes The orders of the contract to be canceled
ids List<String> No Either client_oid or order_id must be present. ID of the orders to be canceled
client_oids List<String> No Either client_oid or order_id must be present. Client-supplied order ID that you can customize. It should be comprised of alpha-numeric characters with length 1 to 32. Both uppercase and lowercase are supported

Request Parameters Verification: same as “Cancel an Order”.

Response
Parameters Parameters Types Description
instrument_id String The orders of the contract to be canceled
order_id String ID of the orders to be canceled
result String The result of canceling the order
client_oids String Client-supplied order ID
Notes

For batch order cancellation, only one of order_id or client_oid parameters should be passed per request. Otherwise an error will be returned.

When using client_oid for batch order cancellation, up to 10 orders can be canceled per trading pair. You need to make sure the ID is unique. In case of multiple identical client_oid, only the latest entry will be returned.

Cancellations of orders are not guaranteed. After placing a cancel order you should confirm they are successfully canceled by requesting the "Get Order List" endpoint.

Example Response
1.by order_ids:

{
    "client_oids":[

    ],
    "ids":[
        "6a-d-54df9a2ac-0",
        "6a-d-54df9a2ad-0"
    ],
    "instrument_id":"EOS-USD-SWAP",
    "result":"true"
}



2. by client_oids:

{
    "client_oids":[
        "oktswap16",
        "oktswap17"
    ],
    "ids":[

    ],
    "instrument_id":"EOS-USD-SWAP",
    "result":"true"
}

Get Order List

This retrieves the latest 20,000 entries of your orders from the last 7 days. This request supports paging and is stored according to the order time in chronological order from latest to earliest.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/orders/&lt;instrument_id&gt;

Example Request

GET /api/swap/v3/orders/EOS-USD-SWAP?state=2&from=1&limit=2

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
state String Yes Order Status: -2 = Failed -1 = Canceled 0 = Open 1 = Partially Filled 2 = Completely Filled 3 = Submitting 4 = Canceling 6 = Incomplete (open + partially filled) 7 = Complete (canceled + completely filled)
after String Yes Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String Yes Pagination of data to return records new than the requested order_id, ledger_id, or trade_id.
limit String Yes Number of results per request. The maximum is 100; the default is 100
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
size String Quantity
timestamp String Creation time
filled_qty String Filled quantity
fee String Transaction fees
order_id String Order ID
price String Order price
price_avg String Average price
type String Type (1: open long 2: open short 3: close long 4: close short)
contract_val String Contract value
client_oid String the order ID customised by yourself
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
state String -2:Failed,-1:Canceled,0:Open ,1:Partially Filled, 2:Fully Filled,3:Submitting,4:Canceling
trigger_price String Only forced-liquidation orders will return actual forced-liquidation trigger price
Notes

status is the older version of state and both can be used interchangeably in the short term. It is recommended to switch to state.

The client_oid is optional. It should be a unique ID generated by your trading system. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

If the order is not filled in the order life cycle, the record may be removed.

The state of unfilled orders may change during the time of endpoint request and response, depending on the market condition.

Example Response
{
    "order_info":[
        {
            "client_oid":"",
            "contract_val":"10",
            "fee":"-0.000551",
            "filled_qty":"1",
            "instrument_id":"EOS-USD-SWAP",
            "order_id":"6a-7-54d663a28-0",
            "order_type":"0",
            "price":"3.633",
            "price_avg":"3.633",
            "size":"1",
            "status":"2",
            "state": "2",    
            "timestamp":"2019-03-25T05:56:21.674Z",
            "type":"4"
        },
        {
            "client_oid":"",
            "contract_val":"10",
            "fee":"-0.000550",
            "filled_qty":"1",
            "instrument_id":"EOS-USD-SWAP",
            "order_id":"6a-8-54cee3a3f-0",
            "order_type":"0",
            "price":"3.640",
            "price_avg":"3.640",
            "size":"1",
            "status":"2",
            "state": "2",    
            "timestamp":"2019-03-25T03:45:17.376Z",
            "type":"2"
        }
    ]
}

Get Order Details

Retrieve order details by order ID. Unfilled orders will be kept in record for only two hours after it is canceled.

Rate limit: 40 requests per 2 seconds
HTTP Request

GET /api/swap/v3/orders/&lt;instrument_id&gt;/&lt;order_id&gt;

OR

GET /api/swap/v3/orders/&lt;instrument_id&gt;/&lt;client_oid&gt;

Example Request

GET /api/swap/v3/orders/BTC-USD-SWAP/64-2a-26132f931-3

OR

GET /api/swap/v3/orders/BTC-USD-SWAP/64a

Parameters
Parameters Type Required Description
order_id String Yes Order ID
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
client_oid String Yes Client-supplied order ID
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
size String Quantity
timestamp String Creation time
filled_qty String Filled quantity
fee String Transaction fees
order_id String Order ID
price String Order price
price_avg String Average price
type String Type (1: open long 2: open short 3: close long 4: close short)
contract_val String Contract value
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
state String -2:Failed,-1:Canceled,0:Open ,1:Partially Filled, 2:Fully Filled,3:Submitting,4:Canceling)
trigger_price String Only forced-liquidation orders will return actual forced-liquidation trigger price
Notes

statusis the older version ofstateand both can be used interchangeably in the short term. It is recommended to switch tostate`.

The client_oid is optional. It should be a unique ID generated by your trading system. This parameter is used to identify your orders in the public orders feed. No warning is sent when client_oid is not unique.
In case of multiple identical client_oid, only the latest entry will be returned.

If the order is not filled in the order life cycle, the record may be removed.

Unfilled order status may change according to the market conditions.

Example Response
{
    "filled_qty":"1",
    "fee":"-0.000550",
    "client_oid":"",
    "price_avg":"3.640",
    "type":"2",
    "instrument_id":"EOS-USD-SWAP",
    "size":"1",
    "price":"3.640",
    "contract_val":"10",
    "order_id":"6a-8-54cee3a3f-0",
    "order_type":"0",
    "state":"2",
    "state": "2",    
    "timestamp":"2019-03-25T03:45:17.376Z"
}

Get Transaction Details

Retrieve recently filled transaction details. Pagination is supported and the response is sorted with most recent first in reverse chronological order. Data from the past 7 days can be retrieved.

Rate limit: 20 requests per 2 seconds

HTTP Request

GET /api/swap/v3/fills

Example Request

GET/api/swap/v3/fills?order_id=64-2b-16122f931-3&instrument_id=BTC-USD-SWAP&after=1&limit=50(returning the first 50 transaction details on page one with order_id 64-2b-16122f931-3 in BTC-USD-SWAP)

Parameters
Parameter Type Description
order_id String No Order ID, Complete transaction details for will be returned if the instrument_id is left blank
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
after String No Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String No Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Types Description
trade_id String ID of the bill record
instrument_id String Contract ID, e.g. BTC-USD-SWAP
price String Price
order_qty String Quantity
order_id String Order ID
created_at String Time that the order is filled
exec_type String Taker or Maker (T or M)
fee String Transaction Fee
side String Side of the order (buy or sell)
Notes

Fees

New status for transaction details: “fee” is either a positive number (invitation rebate) or a negative number (transaction fee deduction)

Example Response
[
    {
        "trade_id":"197429674631450625",
        "instrument_id":"EOS-USD-SWAP",
        "order_id":"6a-7-54d663a28-0",
        "price":"3.633",
        "order_qty":"1.0000",
        "fee":"-0.000551",
        "timestamp":"2019-03-25T05:56:31.287Z",
        "exec_type":"M",
        "side":"short"
    }
]

Place Algo Order

Includes trigger order, trail order, iceberg order and time-weighted average price .

Rate limit:20/2s

HTTP Request

POST /api/swap/v3/order_algo

Example

POST/api/swap/v3/order_algo{"instrument_id":"BTC-USD-SWAP","type":"1","trigger_price":"432.11","order_type":"1",“algo_price“:"341.99","size":"2"}

Request Parameters

General Parameters

Parameters Type Mandatory Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
type String Yes 1. open long; 2. open short; 3. close long; 4. close short
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
size String Yes Total number of orders must be an integer between 1 and 1,000,000, incl. both numbers

Trigger Order (Maximum 10 orders)

Parameters Type Mandatory Description
trigger_price String Yes Trigger price must be between 0 and 1,000,000
algo_price String Yes Order price must be between 0 and 1,000,000

Trail Order (Maximum 10 orders)

Parameters Type Mandatory Description
callback_rate String Yes Callback rate must be between 0.001 (0.1%) and 0.05 (5%)
trigger_price String Yes Trigger price must be between 0 and 1,000,000

Iceberg Order (Maximum 6 orders)

Parameters Type Mandatory Description
algo_variance String Yes Order depth must be between 0.0001 (0.01%) and 0.01 (1%)
avg_amount String Yes Single order average amount must be an integer between 2 and 1,000, incl. both numbers (perpetual swap: integer between 2 and 500, incl. both numbers)
price_limit String Yes Price limit must be between 0 and 1,000,000

TWAP (Maximum 6 orders)

Parameters Type Mandatory Description
sweep_range String Yes Auto-cancelling order range must be between 0.005 (0.5%) and 0.01 (1%), incl. both numbers
sweep_ratio String Yes Auto-cancelling order rate must be between 0.01 and 1, incl. both numbers
single_limit String Yes Single order limit must be between 10 and 2,000, incl. both numbers (perpetual swap: integer between 2 and 500, incl. both numbers)
price_limit String Yes Price limit must be between 0 and 1,000,000, incl, 1,000,000
time_interval String Yes Time interval must be between 5 and 120, incl. both numbers

Return Parameters

Name Type Description
result String Parameters return result
instrument_id String Contract ID, e.g. BTC-USD-SWAP
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
algo_id String Order ID: when fail to place order, the value is -1
error_code String Error code will be 0 if the order is successfully placed, and will appear if order fails
error_message String Error message will be blank if order is successfully placed, and will appear if order fails
Example Response
{
    "result":true,
    "instrument_id":"BTC-USD-SWAP",
    "order_type":"1",
    "algo_id":"2517062038154240"
}

Cancel Algo Order

If user use “algo_id” to cancel unfulfilled orders, they can cancel a maximum of 6 iceberg/TWAP or 10 trigger/trail orders at the same time.

Rate limit:20/2s

HTTP Request

POST /api/swap/v3/cancel_algos

Example

POST/api/swap/v3/cancel_algos{“instrument_id":"BTC-USD-SWAP","order_type":“1”,"algo_ids":“198273485”}

Request Parameters

Name Type Mandatory Description
instrument_id String Yes Cancel specific types of contract
algo_ids String Yes Cancel specific order ID
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)

Return Parameters

Name Type Description
instrument_id String Cancel specific types of contract
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
algo_ids String Cancel specific order ID
result String Parameter return result

Return Parameter

Return parameter is the order ID of canceled orders. This does not mean that the orders are successfully canceled. Orders that are pending cannot be canceled, only unfulfilled orders can be canceled.

Description

This does not guarantee orders are canceled successfully. Users are advised to request the order list to confirm after using the cancelation endpoint.

Example Response
{
    "result":true,
    "instrument_id":"BTC-USD-SWAP",
    "order_type":"1",
    "algo_id":"2517062038154240"
}

Get Algo Order List

Obtaining Order List

Rate limit:20/2s

HTTP Request

GET /api/swap/v3/order_algo/<instrument_id>

Example

GET/api/swap/v3/order_algo/BTC-USD-SWAP?order_type=1&status=2

Parameters

Name Type Mandatory Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
order_type String Yes 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
status String See Description [Status and algo_ids are mandatory, select either one] Order status: (1. Pending; 2. 2. Effective; 3. Cancelled; 4. Partially effective; 5. Paused; 6. Order failed [Status 4 and 5 only applies to iceberg and TWAP orders]
algo_ids String See Description [status and algo_ids are mandatory, select either one] Enquiry specific order ID
before string No [Optional] Request page content after this ID (updated records)
after string No [Optional] Request page content before this ID (past records)
limit string No [Optional] The number of results returned by the page. Default and maximum are both 100 (see the description on page for more details)

Return Parameters

Name Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
order_type String 1. trigger order; 2. trail order; 3. iceberg order; 4. time-weighted average price (TWAP)
timestamp String Order time
rejected_at String Order expiration time
algo_id String Order ID
status String Order status: 1. Pending; 2. Effective; 3. Canceled (4. Partially effective; 5. Paused)
type String Order type (1. Open long; 2. Open short; 3. Close long; 4. Close short)
leverage String Margin leverage: value:10/20; default 10x

Trigger Orders

Parameters Type Description
trigger_price String Trigger price must be greater than 0
algo_price String Algo price must be between 0 and 1,000,000 incl. 1,000,000
size String Order amount must be an integer between 1 and 1,000,000, incl. both numbers
real_amount String Actual order amount

Trail Orders

Parameters Type Description
callback_rate String Callback rate must be between 0.001 (0.1%) and 0.05 (5%), incl. both numbers
trigger_price String Trigger price must be between 0 and 1,000,000, incl. 1,000,000
size String Order amount must be an integer between 1 and 1,000,000, incl. 1,000,000
real_amount String Actual order amount

Iceberg Orders

Parameters Type Description
algo_variance String Order depth must be between 0 and 0.01 (1%), incl. 0.01
size String Order amount must be an integer between 1 and 1,000,000, incl. 1,000,000
avg_amount String Average amount must be an integer between 2 and 500 (same for perpetual swap), incl. both numbers
price_limit String Price limit must be between 0 and 1,000,000, incl. 1,000,000
deal_value String Transacted volume

Time-weighted Average Price (TWAP)

Parameter Type Description
sweep_range String Auto-cancelling order range must be between 0.005 (0.5%) and 0.01 (1%), incl. both numbers
sweep_ratio String Auto-cancelling order rate must be between 0.01 and 1, incl. both numbers
size String Order size must be an integer between 1 and 1,000,000, incl. both numbers
single_limit String Single order limit must be between 10 and 2,000 (perpetual swap orders: integer between 2 and 500), incl. both numbers
price_limit String Price limit must be between 0 and 1,000,000, incl. 1,000,000
time_interval String Order time interval must be between 5 and 120, incl. both numbers
deal_value String Order volume
Example Response
{
    "instrument_id":"BTC-USD-SWAP",
    "order_type":"1",
    "algo_id":"2517062038154240"    
    "timestamp":"2019-03-25T03:45:17.376Z"
    "rejected_at":"2019-03-26T03:45:17.376Z"
    "status":"2"    
    "type":"3"   
    "leverage":"20"   
    "trigger_price":"2"   
    "algo_price":"2"   
    "size":"2000"  
    "real_amount":"1000"      
}

Public- Contract Information

Get market data.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments

Request Sample

GET /api/swap/v3/instruments

Return Parameters

Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
underlying_index String Trade currency, such as the BTC in BTC-USD-SWAP
quote_currency String Quote currency, such as the USD in BTC-USD-SWAP
coin String Currency of margin, such as the BTC in BTC-USD-SWAP
contract_val String Contract value
listing String Creation time
delivery String Settlement time
size_increment String Order quantity accuracy
tick_size String Order price accuracy

Return Sample

[
    {
        "instrument_id":"TESTD-USD-SWAP",
        "underlying_index":"TESTD",
        "quote_currency":"USD",
        "coin":"TESTD",
        "contract_val":"100",
        "listing":"2019-03-05T07:43:23.000Z",
        "delivery":"2019-03-25T14:00:00.000Z",
        "size_increment":"1",
        "tick_size":"0.1"
    },
    {
        "instrument_id":"BTC-USD-SWAP",
        "underlying_index":"BTC",
        "quote_currency":"USD",
        "coin":"BTC",
        "contract_val":"100",
        "listing":"2018-08-28T02:43:23.000Z",
        "delivery":"2019-03-25T14:00:00.000Z",
        "size_increment":"1",
        "tick_size":"0.1"
    },
    ...
]

Public- Order Book

Retrieve a trading pair's order book. Pagination is not supported here; the entire orderbook will be returned per request. This is publicly accessible without account authentication. WebSocket is recommended here.

Rate limit: 20 requests per 2 seconds

HTTP Request

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/depth

Example Request

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/depth?size=50

Parameters
Parameter Type Required Description
size String No Number of results per request. Maximum 200
depth String No Aggregation of the order book. e.g . 0.1, 0.001
instrument_id String No Trading pair symbol

If the size is left blank, one string of data will be returned. If size is '0', no data string will be returned. If size is larger than '200', only 200 strings of data will be returned.

Response
Parameters Type Description
asks String Selling side
bids String Buying side
timestamp String Timestamp
Explanation on the array returned

[411.8, 10, 8, 4]: 411.8 is the price; 10 is the quantity at the price; 8 is the quantity of the force-liquidated orders at the price; 4 is the number orders at the price

Example Response
{
    "asks":[
        [
            "3968.5",
            "121",
            0,
            2
        ],
        [
            "3968.6",
            "160",
            0,
            4
        ]
    ],
    "bids":[
        [
            "3968.4",
            "179",
            0,
            4
        ],
        [
            "3968",
            "914",
            0,
            3
        ]
    ],
    "time":"2019-03-25T11:12:10.601Z"
}

Public- All Tokens

Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours for all trading pairs. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/instruments/ticker

Example Request

GET /api/swap/v3/instruments/ticker

Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
best_ask String Best ask price
best_bid String best bid price
last String Last traded price
high_24h String Highest price in the past 24 hours
low_24h String Lowest price in the past 24 hours
volume_24h String 24 hour trading volume (contracts)
timestamp String Timestamp
Notes

The parameters for highest price, lowest price and trading volume are all computed based on the data in the last 24 hours.

Example Response
[
    {
        "instrument_id":"BTC-USD-SWAP",
        "last":"3968.1",
        "high_24h":"3980",
        "low_24h":"3942.6",
        "volume_24h":"264017",
        "best_ask":"3968.1",
        "best_bid":"3968",
        "timestamp":"2019-03-25T11:34:02.241Z"
    },
    {
        "instrument_id":"EOS-USD-SWAP",
        "last":"3.609",
        "high_24h":"3.665",
        "low_24h":"3.57",
        "volume_24h":"1537961",
        "best_ask":"3.609",
        "best_bid":"3.608",
        "timestamp":"2019-03-25T11:34:05.557Z"
    }
]

Public- Token Information

Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours for a particular trading pair. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/ticker

Example Request

GET /api/swap/v3/instruments/BTC-USD-SWAP/ticker

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP

The Contract ID will be verified. if the ID differs from that in the database, an error code will be returned.

Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
best_ask String Best ask price
best_bid String best bid price
last String Last traded price
high_24h String Highest price in the past 24 hours
low_24h String Lowest price in the past 24 hours
volume_24h String Trading volume of past 24 hours (Contraacts)
timestamp String Timestamp
Notes

The parameters for highest price, lowest price and trading volume are all computed based on the data in the last 24 hours.

Example Response
{
    "instrument_id":"EOS-USD-SWAP",
    "last":"3.611",
    "high_24h":"3.665",
    "low_24h":"3.57",
    "volume_24h":"1733788",
    "best_ask":"3.611",
    "best_bid":"3.61",
    "timestamp":"2019-03-25T09:16:07.501Z"
}

Public- Filled Orders

Retrieve the latest 300 entries of filled orders. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/trades

Example Request

GET /api/swap/v3/instruments/BTC-USD-SWAP/trades?after=1&limit=50

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
after String No Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String No Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Type Description
trade_id String Transaction time ID
price String Filled price
size String Filled size
side String Filled side: sell,buy
timestamp String Filled time
Notes

The side indicates the side of the order that is filled by the taker. The “taker” means actively taking the order on the order book. The buy indicates the taker is taking liquidity from the order book, so the price rises as a result, whereas the sell indicates the price falls as a result.

The trade_id is the ID referring to the filled order; it is generated incrementally and could be incomplete in some cases.

Example Response
[
    {
        "trade_id":"197610300823248897",
        "price":"3969.2",
        "size":"5",
        "side":"buy",
        "timestamp":"2019-03-25T11:55:23.569Z"
    },
    {
        "trade_id":"197608511860318209",
        "price":"3969.3",
        "size":"56",
        "side":"sell",
        "timestamp":"2019-03-25T11:51:50.308Z"
    }
]

Public- Market Data

Retrieve the candlestick charts of the trading pairs. This API can retrieve the latest 2000 entries of data. Candlesticks are returned in groups based on requested granularity.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/candles

Example Request

GET /api/swap/v3/instruments/BTC-USD-SWAP/candles?start=2019-03-24T02:31:00.000Z&end=2019-03-25T02:55:00.000Z&granularity=86400

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
start String No Start time in ISO 8601
end String NO End time in ISO 8601
granularity String No Desired time slice in seconds[60/180/300 900/1800/3600/7200/14400/21600/43200/86400/604800]

Timestamp must be in ISO 8601 format, otherwise an error be returned.

Return Parameters

Parameters Type Description
timestamp String Timestamp
open String Open price
high String Higest price
low String Lowest price
close String Close price
volume String Trading volume (contract)
currency_volume String Volume of a specific token

Notes

Both parameters will be ignored if either one of start or end are not provided. The last 200 records of data will be returned if the time range is not specified in the request.

The granularity field must be one of the following values: [60, 180, 300, 900, 1800, 3600, 7200, 14400, 43200, 86400, 604800]. Otherwise, your request will be rejected. These values correspond to timeslices representing [1 minute, 3 minutes, 5 minutes, 15 minutes, 30 minutes, 1 hour, 2 hours, 6 hours, 12 hours, 1 day, and 1 week] respectively.

The candlestick data may be incomplete, and should not be polled repeatedly.

The maximum data set is 200 candles for a single request. If the request made with the parameters start, end and granularity will result in more data than that is allowed, only 200 candles will be returned. If finer granularity over a larger time range is needed, please make multiple requests as needed.

The data returned will be arranged in an array as below: [timestamp,open,high,low,close,volume,currency_volume]

Example Response
[
    [
        "2019-03-25T16:00:00.000Z",
        "3946.6",
        "3960",
        "3860",
        "3917.7",
        "329627",
        "8434.421"
    ],
    [
        "2019-03-24T16:00:00.000Z",
        "3971.4",
        "3977.7",
        "3942.6",
        "3946.4",
        "333780",
        "8416.0873"
    ]
]

//[timestamp,open,high,low,close,volume,currency_volume]

Public- Indices

Retrieve indices of tokens. This is publicly accessible without account authentication.

Rate Limit: 20 requests per 2 seconds
HTTP Requests

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/index

Example Request

GET /api/swap/v3/instruments/BTC-USD-SWAP/index

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
index String Index price
timestamp String Timestamp
Notes

The token displayed after the hyphen “-” is the quote currency of the index.

Example Response
{
    "instrument_id":"BTC-USD-SWAP",
    "index":"3913.64749999",
    "timestamp":"2019-03-26T02:30:20.560Z"
}

Public- Exchange Rates

Retrieve the fiat exchange rates. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/rate

Example Request

GET /api/swap/v3/rate

Parameters
Parameters Type Description
instrument_id String e.g. USD_CNY
rate String Exchange rates
timestamp String Timestamp
Example Response
{
    "instrument_id":"USD_CNY",
    "rate":"6.701",
    "timestamp":"2019-03-26T02:32:52.703Z"
}

Public- Open Interest

Retrieve the total open interest of a contract on OKEx. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/open_interest

Example Request

GET /api/swap/v3/instruments/BTC-USD-SWAP/open_interest

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
amount String Total open interest
timestamp String Timestamp
Example Response
{
    "instrument_id":"BTC-USD-SWAP",
    "amount":"303613",
    "timestamp":"2019-03-26T02:36:22.703Z"
}

Public- Current Price Limits

Retrieve the ceiling of the buy price and floor of sell price of the contract. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/price_limit

Example Request

GET /api/swap/v3/instruments/BTC-USD-SWAP/price_limit

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
highest String Ceiling of buying price
lowest String Floor of selling price
timestamp String Timestamp
Example Response
{
    "instrument_id":"BTC-USD-SWAP",
    "highest":"3953.4",
    "lowest":"3875.0",
    "timestamp":"2019-03-26T02:42:38.143Z"
}

Public- Force-Liquidated Orders

Retrieve the force liquidated orders. This is publicly accessible without account authentication.

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/swap/v3/instruments/&lt;instrument_id&gt;/liquidation

Example Request

GET /api/swap/v3/instruments/BTC-USD-SWAP/liquidation?status=1&from=1&limit=2

Parameters
Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
status String Yes 0:unfilled in the recent 7 days; 1:filled orders in the recent 7 days)
from String No Request page after this pagination id (eg. 1, 2, 3, 4, 5. Setting from 4 would only return page 4, and to 4 would only return to page 3)
to String No Request page after this pagination id (eg. 1, 2, 3, 4, 5. Setting from 4 would only return page 4, and to 4 would only return to page 3)
limit String No Number of results per request in reverse chronological order (latest first). Maximum 100.
Response
Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
size String Quantity
created_at String Order creation time
loss String Loss resulted by forced liquidation
price String Order price
type String 3:Close long 4:Close short
Example Response
[
    {
        "instrument_id":"BTC-USD-SWAP",
        "size":"4",
        "created_at":"2019-03-26T02:00:40.490Z",
        "loss":"0",
        "price":"3935.1",
        "type":"4"
    },
    {
        "instrument_id":"BTC-USD-SWAP",
        "size":"193",
        "created_at":"2019-03-25T23:28:15.922Z",
        "loss":"0",
        "price":"3932.5",
        "type":"4"
    }
]

Public- Hold Amount

Get On Hold Amount for Open Orders.

Rate limit:5/2s

HTTP Requests

GET /api/swap/v3/accounts/<instrument_id>/holds

Request Sample

GET /api/swap/v3/accounts/BTC-USD-SWAP/holds

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP

Return Parameters

Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
amount String Initial margin on hold
timestamp String timestamp

Contract name will be verified. If the name differs from database, error code will be triggered.

Return Sample

{
    "instrument_id":"BTC-USD-SWAP",
    "amount":"303613",
    "timestamp":"2019-03-26T02:36:22.703Z"
}

Public- Next Settlement Time

Get the time of next settlement.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/funding_time

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/funding_time

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP

Contract name will be verified. If the name differs from database, error code will be triggered.

Return Parameters

Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
funding_time String time of current funding
funding_rate String current funding rate
estimated_rate String next estimated funding rate
settlement_time String settlement rate

Return Sample

{
  "instrument_id": "EOS-USD-SWAP",
  "funding_time": "2019-09-02T16:00:00.000Z",
  "funding_rate": "-0.00066983",
  "estimated_rate": "-0.00043662",
  "settlement_time": "2019-09-02T16:00:00.000Z"
}

Public- Mark Price

Get Mark Price.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/mark_price

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/mark_price

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
from String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
to String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)

Contract name will be verified. If the name differs from database, error code will be triggered.

Return Parameters

Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
mark_price String Mark Price
timestamp String Timestamp

Return Sample


{
    "instrument_id":"BTC-USD-SWAP",
    "mark_price":"3914.3",
    "timestamp":"2019-03-26T03:33:50.064Z"
}

Public- Funding Rate History

Get Funding Rate History,This API can retrieve data in the last 7 days.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/historical_funding_rate

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/historical_funding_rate?after=1&limit=2

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
from String No request page after this pagination id (eg. 1, 2, 3, 4, 5. There is only a 4 "from 4" and only a 3 "to 4")
to String No request page after this pagination id (eg. 1, 2, 3, 4, 5. There is only a 4 "from 4" and only a 3 "to 4")
limit String No number of results per request in chronological order (latest at the front). Maximum 100.

Contract name will be verified. If the name differs from database, error code will be triggered.

If from and to are both sent, from prevails.

Return Parameters

Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
funding_rate String current funding rate
realized_rate String Actual funding rate
interest_rate String Interest
funding_time String Settlement time

Return Sample

[
    {
        "instrument_id":"BTC-USD-SWAP",
        "funding_rate":"-0.00007116",
        "realized_rate":"-0.00007116",
        "interest_rate":"0.00000000",
        "funding_time":"2019-03-26T02:00:00.000Z"
    },
    {
        "instrument_id":"BTC-USD-SWAP",
        "funding_rate":"-0.00010248",
        "realized_rate":"-0.00010248",
        "interest_rate":"0.00000000",
        "funding_time":"2019-03-25T14:00:00.000Z"
    }
]

INDEX API

Rest API public index

Public- Index Content

get constituents of index

Rate limit: 20 /2s
HTTP Requests

GET/api/index/v3/<instrument_id>/constituents

End Certificate Request Sample

GET /api/index/v3/BTC-USD/constituents

Request Parameters
参数名 参数类型 是否必须 描述
instrument_id String Yes trading pair of index ,such as:BTC-USD
Return Parameters
参数名 参数类型 描述
last String Latest Index Price
original_price Price Original Price
weight String Weights
usd_price String Convert to USD Price
exchange String Name of Exchange
instrument_id String Index Trading Pairs, i.e. BTC index is BTC-USD
timestamp String timestamp
symbol String Names of Exchange Trading Pairs, e.g. BTC-USD
Return Sample
{
  "code": 0,
  "data": {
    "last": "5562.42250000",
    "constituents": [
      {
        "symbol": "BTC-USD",
        "original_price": "5562.75",
        "weight": "0.25",
        "usd_price": "5562.75",
        "exchange": "GEMINI"
      },
      {
        "symbol": "BTC-USD",
        "original_price": "5562.44",
        "weight": "0.25",
        "usd_price": "5562.44",
        "exchange": "Coinbase"
      },
      {
        "symbol": "BTC-USD",
        "original_price": "5564.5",
        "weight": "0.25",
        "usd_price": "5564.5",
        "exchange": "Bitstamp"
      },
      {
        "symbol": "BTC-USD",
        "original_price": "5560",
        "weight": "0.25",
        "usd_price": "5560",
        "exchange": "kraken"
      }
    ],
    "instrument_id": "BTC-USD",
    "timestamp": "2019-04-23T12:13:03.848Z"
  },
  "detailMsg": "",
  "msg": ""
}

This is RestAPI Error Codes.

Common Error Codes

Error codes of v3 API start from 30000.

Common error codes include the signatures and error codes of all business lines.

Error Message Error Codes http Status Code
successful,when the order placement / cancellation / operation is successful 0 200
no data received in 30s 4001 400
Buffer full. cannot write data 4002 400
request header "OK_ACCESS_KEY" cannot be blank 30001 400
request header "OK_ACCESS_SIGN" cannot be blank 30002 400
request header "OK_ACCESS_TIMESTAMP" cannot be blank 30003 400
request header "OK_ACCESS_PASSPHRASE" cannot be blank 30004 400
invalid OK_ACCESS_TIMESTAMP 30005 400
invalid OK_ACCESS_KEY 30006 400
invalid Content_Type, please use "application/json" format 30007 400
timestamp request expired 30008 400
system error 30009 500
API validation failed 30010 401
invalid IP 30011 400
invalid authorization 30012 401
invalid sign 30013 401
request too frequent 30014 429
request header "OK_ACCESS_PASSPHRASE" incorrect 30015 400
you are using v1 apiKey, please use v1 endpoint. If you would like to use v3 endpoint, please subscribe to v3 apiKey 30016 400
apikey's broker id does not match 30017 400
apikey's domain does not match 30018 400
Api is offline or unavailable 30019 400
Json data format error 30021 400
Api has been frozen 30022 400
body cannot be blank,body cannot be blank 30020 400
json data format error, json data format error 30021 400
{0} parameter cannot be blank; required parameter cannot be blank,parameters returned respectively 30023 400
{0} parameter value error,parameters returned respectively 30024 400
{0} parameter category error,parameter category error 30025 400
requested too frequent; endpoint limit exceeded 30026 429
login failure,operating orders of other users 30027 401
unauthorized execution 30028 400
account suspended 30029 400
endpoint request failed. Please try again 30030 400
token does not exist 30031 400
pair does not exist 30032 400
exchange domain does not exist 30033 400
exchange ID does not exist,the error returned when the exchange ID for the apikey validation is not filled 30034 400
trading is not supported in this website,the error returned when the exchange is closed 30035 400
no relevant data, no relevant data when enquiring the endpoint 30036 400
user does not exist 30038 400
endpoint is offline or unavailable 30037 400

Contract Delivery Error Codes

Error Messages Error Codes http Status Code
futures account suspended(when the futures account is suspended ) 32001 400
futures account does not exist(when futures trading is not enabled for the account) 32002 400
canceling, please wait(When the user repeatedly withdraws the order) 32003 400
you have no unfilled orders(when the user check the unfilled orders ) 32004 400
max order quantity(when the user placed an order exceeding the quantity limit) 32005 400
the order price or trigger price exceeds USD 1 million(when the user placed and order with price or trigger price over USD 1 million) 32006 400
leverage level must be the same for orders on the same side of the contract(when the user has open positions with 10x leverage and trying to open a 20x leverage order) 32007 400
Max. positions to open (cross margin) 32008 400
Max. positions to open (fixed margin) 32009 400
leverage cannot be changed with open positions(if an user holds a short position with 10x leverage, he/she will not be able to change the leverage to 20x) 32010 400
futures status error(contract expired) 32011 400
Network error. Order couldn’t cancel. 32012 400
token type is blank 32013 400
your String of contracts closing is larger than the String of contracts available 32014 400
margin ratio is lower than 100% before opening positions 32015 400
margin ratio is lower than 100% after opening position 32016 400
no BBO 32017 400 no BBO
the order quantity is less than 1, please try again 32018 400
the order price deviates from the price of the previous minute by more than 3% 32019 400
the price is not in the range of the price limit 32020 400
leverage error(leverage is not set as 10x or 20x ) 32021 400
this function is not supported in your country or region according to the regulations,futures trading not supported in certain regions 32022 400
this account has outstanding loan 32023 400
order cannot be placed during delivery 32024 400
order cannot be placed during settlement 32025 400
your account is restricted from opening positions 32026 400
cancelled over 20 orders,order cancellation limit reached 32027 400
Account frozen due to liquidation 32028 400
Only fill in either parameter client_oid or order_id only. 32029 400
The order cannot be cancelled 32030 400
client_oid or order_id is required. 32031 400
User does not exist 32038 400
User have open contract orders or position 32040 400
String of commission over 1 million 32045 400
Each user can hold up to 10 trade plans at the same time 32046 400
system error 32047 400
Order strategy track range error 32048 400
Each user can hold up to 10 track plans at the same time 32049 400
Order strategy rang error 32050 400
Order strategy ice depth error 32051 400
String of commission over 100 thousand 32052 400
Each user can hold up to 6 ice plans at the same time 32053 400
The order price is zero. Market-close-all function cannot be executed 32057 400
Trade not allow 32054 400
cancel order error 32055 400
iceberg per order average should between {0}-{1} contracts 32056 400
The order price is zero. Market-close-all function cannot be executed 32057 400
Each user can hold up to 6 initiative plans at the same time 32058 400
Total amount should exceed per order amount 32059 400
Order strategy type error 32060 400
Order strategy initiative limit error 32061 400
Order strategy initiative range error 32062 400
Order strategy initiative rate error 32063 400
Time Stringerval of orders should set between 5-120s 32064 400
Close amount exceeds the limit of Market-close-all 32065 400
You have open orders. Please cancel all open orders before changing your leverage level. 32066 400
Account equity < required margin in this setting. Please adjust your leverage level again. 32067 400
The margin for this position will fall short of the required margin in this setting. Please adjust your leverage level or increase your margin to proceed. 32068 400
Target leverage level too low. Your account balance is insufficient to cover the margin required. Please adjust the leverage level again. 32069 400
Please check open position or unfilled order 32070 400
Your current forced-liquidation mode does not support this action. 32071 400
The highest available margin for your order’s tier is {0}. Please edit your margin and place a new order. 32072 400
The action does not apply to the token 32073 400
The number of contracts of your position, open orders, and the current order has exceeded the maximum order limit of this asset. 32074 400
Account risk rate breach 32075 400
Liquidation of the holding position(s) at market price will require cancellation of all pending close orders of the contracts. 32076 400
Your margin for this asset in futures account is insufficient and the position has been taken over for forced liquidation. (You will not be able to place orders, close positions, transfer funds, or add margin during this period of time. Your account will be restored after the liquidation is complete.) 32077 400
Please cancel all open orders before switching the liquidation mode(Please cancel all open orders before switching the liquidation mode) 32078 400
Your open positions are at high risk.(Please add margin or reduce positions before switching the mode) 32079 400
Funds cannot be transferred out within 30 minutes after futures settlement 32080 400

Token and margin error codes

Error Messages Error Codes http Status Code
margin account for this pair is not enabled yet, the service must be enabled before trading 33001 400
margin account for this pair is suspended,margin account suspended 33002 400
no loan balance(insufficient balance for loan) 33003 400
loan amount cannot be smaller than the minimum limit(minimum loan amount limit not reached) 33004 400
repayment amount must exceed 0(invalid repayment amount) 33005 400
loan order not found(loan order not found) 33006 400
status not found(status unchanged) 33007 400
loan amount cannot exceed the maximum limit(invalid loan amount) 33008 400
user ID is blank(user ID not provided) 33009 400
you cannot cancel an order during session 2 of call auction(order cancellation not allowed during call auction) 33010 400
no new market data (no market data) 33011 400
order cancellation failed(order cancellation failed) 33012 400
order placement failed(order placement failed) 33013 400
order does not exist( order canceled already. Invalid order number) 33014 400
exceeded maximum limit(exceeded maximum limit during multiple-order placement) 33015 400
margin trading is not open for this token( insufficient balance for order placement) 33016 400
insufficient balance ( margin trading not supported for this pair ) 33017 400
this parameter must be smaller than 1 ( invalid parameter for getting market data) 33018 400
request not supported(margin trading not supported for some exchanges) 33020 400
token and the pair do not match(incorrect token for the token pair during repayment) 33021 400
pair and the order do not match( incorrect token for the order during repayment) 33022 400
you can only place market orders during call auction(you can only place market orders during call auction) 33023 400
trading amount too small(invalid trading amount) 33024 400
base token amount is blank(settings not completed during order placement) 33025 400
transaction completed( cancel limited when the transaction completed) 33026 400
cancelled order or order cancelling(cancel limited when the order is cancelling or cancelled) 33027 400
the decimal places of the trading price exceeded the limit(order endpoint: The decimal places of the trading price exceeded the limit) 33028 400
the decimal places of the trading size exceeded the limit(order endpoint::The decimal places of the trading size exceeded the limit) 33029 400
client_oid or order_id is required 33059 400
Only fill in either parameter client_oid or order_id 33060 400
You can only place limit order after Call Auction has started 33034 400
This type of order cannot be canceled(This type of order cannot be canceled) 33035 400
Exceeding the limit of entrust order 33036 400
The buy order price should be lower than 130% of the trigger price 33037 400
The sell order price should be higher than 70% of the trigger price 33038 400
The limit of callback rate is 0 < x <= 5% 33039 400
The trigger price of a buy order should be lower than the latest transaction price 33040 400
The trigger price of a sell order should be higher than the latest transaction price 33041 400
The limit of price variance is 0 < x <= 1% 33042 400
The total amount must be larger than 0 33043 400
The average amount should be 1/1000 * total amount <= x <= total amount 33044 400
The price should not be 0, including trigger price, order price, and price limit 33045 400
Price variance should be 0 < x <= 1% 33046 400
Sweep ratio should be 0 < x <= 100% 33047 400
Per order limit: 1/1000 < x <= Total amount 33048 400
Total amount should be X > 0 33049 400
Time interval should be 5 <= x <= 120s 33050 400
cancel order number not higher limit: plan and track entrust no more than 10, ice and time entrust no more than 6 33051 400
client_oid or order_id is required 33059 400
Only fill in either parameter client_oid or order_id 33060 400

Funding Account error codes

Business Error Messages Business Error Codes http Status Code
withdrawal suspended(withdrawal endpoint: account suspended) 34001 400
please add a withdrawal address(withdrawal endpoint: address required) 34002 400
sorry, this token cannot be withdrawn to xx at the moment(withdrawal endpoint: incorrect address) 34003 400
withdrawal fee is smaller than minimum limit(withdrawal endpoint: incorrect fee) 34004 400
withdrawal fee exceeds the maximum limit(withdrawal endpoint: incorrect withdrawal fee) 34005 400
withdrawal amount is lower than the minimum limit(minimum withdrawal amount%} endpoint: incorrect amount) 34006 400
withdrawal amount exceeds the maximum limit(maximum withdrawal amount endpoint: incorrect amount) 34007 400
insufficient balance(transfer & withdrawal endpoint: insufficient balance) 34008 400
your withdrawal amount exceeds the daily limit(withdrawal endpoint: withdrawal limit exceeded) 34009 400
transfer amount must be larger than 0(transfer endpoint: incorrect amount) 34010 400
conditions not met(transfer & withdrawal endpoint: conditions not met, e.g. KYC level) 34011 400
the minimum withdrawal amount for NEO is 1, and the amount must be an integer(withdrawal endpoint: special requirements ) 34012 400
please transfer(transfer endpoint: Token margin trading instrument ID required) 34013 400
transfer limited(transfer endpoint:Transfer limited) 34014 400
subaccount does not exist(transfer endpoint: subaccount does not exist) 34015 400
transfer suspended(transfer endpoint: either end of the account does not authorize the transfer) 34016 400
account suspended(transfer & withdrawal endpoint: either end of the account does not authorize the transfer) 34017 400
incorrect trades password(incorrect trades password) 34018 400
please bind your email before withdrawal(withdrawal endpoint : email required) 34019 400
please bind your funds password before withdrawal(withdrawal endpoint : funds password required) 34020 400
Not verified address(withdrawal endpoint) 34021 400
Withdrawals are not available for sub accounts(withdrawal endpoint) 34022 400
token does not exist(token requested does not exist) 30031 400
Please enable futures trading before transferring your funds(Please enable futures trading before transferring your funds) 34023 400
transfer too frequently(transfer too frequently) 34026 400
Funds cannot be transferred out within 30 minutes after swap settlement(Funds cannot be transferred out within 30 minutes after swap settlement) 21009 400

Swap error codes

Error Codes

Example

Error Message Error Codes http Status Code
System error, Invalid parameter in url normally 1 400
Contract does not exist, Contract subscribing does not exist 35001 400
Contract settling, Contract is being settled 35002
Contract paused,Contract is being paused 35003 400
Contract pending settlement,Pending contract settlement 35004 400
User does not exist,Perpetual swap trading is not enabled 35005 400
Risk ratio too high,Margin ratio too low when placing order 35008 400
Position closing too large,Closing position size larger than available size 35010 400
Incorrect order size,Placing an order with less than 1 contract 35012 400
Order price is not within limit,Order size is not in acceptable range 35014 400
Invalid leverage level,Leverage level unavailable 35015 400
Open orders exist, Changing leverage level 35017
Order size too large ,Order size exceeds limit 35019 400
Order price too high,Order price exceeds limit 35020 400
Order size exceeded current tier limit,Order size exceeds limit of the current tier 35021 400
Contract status error,Contract is paused or closed 35022 400
Contract not initialized 35024 400
No account balance 35025 400
Contract settings not initialized 35026 400
Order does not exist 35029 400
Order size too large,Place multiple orders 35030 400
Cancel order size too large,Cancel multiple orders 35031 400
Invalid user status 35032 400
Open order quantity exceeds limit 35039 400
invalid order type,When posting orders at best bid price, order_type can only be 0 (regular order) 35040 400
Order is completed and cannot be canceled. 35044 400
Negative account balance 35046 400
Insufficient account balance 35047 400
User contract is frozen and liquidating 35048 400
Invalid order type 35049 400
Position settings are blank 35050 400
Insufficient cross margin 35052 400
Account risk too high 35053 400
Insufficient account balance 35055 400
No last traded price 35057 400
No limit 35058 400
Required parameters cannot be blank,Required parameters not filled 30023 400
Invalid parameters ,Parameters are invalid 30024 400
Invalid instrument_id,Invalid instrument_id 35061 400
client_oid or order_id is required 35059 400
Only fill in either parameter client_oid or order_id 35060 400
Invalid match_price 35062 400
Invalid order_size 35063 400
Invalid client_oid 35064 400
Order interval error 35066 400
Time-weighted order ratio error 35067 400
Time-weighted order range error 35068 400
Time-weighted single transaction limit error 35069 400
Algo order type error 35070 400
Order total must be larger than single order limit 35071 400
Maximum 6 unfulfilled time-weighted orders can be held at the same time 35072 400
Order price is 0. Market-close-all not available 35073 400
Iceberg order single transaction average error 35074 400
Failed to cancel order 35075 400
LTC 20x leverage. Not allowed to open position 35076 400
Maximum 6 unfulfilled iceberg orders can be held at the same time 35077 400
Order amount exceeded 100,000 35078 400
Iceberg order price variance error 35079 400
Callback rate error 35080 400
Maximum 10 unfulfilled trail orders can be held at the same time 35081 400
Trail order callback rate error 35082 400
Each user can only hold a maximum of 10 unfulfilled stop-limit orders at the same time 35083 400
Order amount exceeded 1 million 35084 400
Order amount is not in the correct range 35085 400
Price exceeds 100 thousand 35086 400
Price exceeds 100 thousand 35087 400
Average amount error 35088 400
Price exceeds 100 thousand 35089 400
No stop-limit orders available for cancelation 35090 400
No trail orders available for cancellation 35091 400
No iceberg orders available for cancellation 35092 400
No trail orders available for cancellation 35093 400
Stop-limit order last traded price error 35094 400
Instrument_id error 35095 400
Algo order status error 35096 400
Order status and order ID cannot exist at the same time 35097 400
An order status or order ID must exist 35098 400
Algo order ID error 35099 400

WebsocketAPI

Spot&Margin

This is the V3 Websocket API for spot and margin users. Except for the separate Account Channel, data of all channels are applicable to both spot and margin users.

General

ebsocket is a new HTML5 Protocol. It achieves full-duplex data transmission between the client and the server, allowing data to be transferred effectively in both directions. With just only one handshake, the connection between the client and the server is established. The server will then be able to push data to the client according to preset rules. Its advantages include:

  • The Websocket request header for data transmission between client and server is only approximately 2 bytes
  • Either the client or server can initiate a data transmission
  • As there is no need to create and delete TCP connection repeatedly, it saves resources for both bandwidth and server

We strongly recommend developers to use Websocket API to retrieve market data and order book depth.

Notes:

All the messages returning from Websocket API will be optimized by Deflate compression. All users will be required to decompress the messages by themselves with the methods they find most appropriate. Please refer to our demo.

The connection will break automatically if subscription is not established or data has not been pushed for more than 30s.

url:wss://real.okex.com:8443/ws/v3

Command Format

Request format:

{"op": "<value>", "args": ["<value1>","<value2>"]}

the value of op 1-- subscribe 2--unsubscribe 3--login

args: the value is the channel name, which can be one or more channels

Successful response format:

  {"event": "<value>","channel":"<value>"}
  {"table":"channel","data":"[{"<value1>","<value2>"}]"}

In the spot/depth channel, the return formats for distinguishing between the first full amount and the subsequent incremental data are:


{"table":"channel", "action":"<value>","data":"[{"<value1>","<value2>"}]"}

Failure response format:

{"event":"error","message":"<error_message>","errorCode":"<errorCode>"}

Subscription

Users may subscribe to one or more channels,The total length of multiple channels should not exceed 4,096 bytes.

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

Note: the value of <op> is subscribe

The array content of <args> is channel names:<channelname>:<filter>

The <channelname> is composed of business/channel

The value of business is 'spot', and channel is the specific data name of the aforementioned business. If a <channelname> consists of more than one words, they will be connected with an underscore " _ ".

Example:

"spot/ticker:ETH-USDT"or "spot/margin_account:ETH-USDT"

<Filter>> is data filterable. For details, please refer to the description of each channel

Example :

send:

{"op": "subscribe", "args": ["spot/ticker:ETH-USDT","spot/candle60s:ETH-USDT"]}

response:

 {"event":"subscribe","channel":"spot/ticker:ETH-USDT"}

 {"event":"subscribe","channel":"spot/candle60s:ETH-USDT"}

 {"table":"spot/ticker","data":[{"instrument_id":"ETH-USDT","last":"8.8","best_bid":"3","best_ask":"8.1","open_24h":"5.1","high_24h":"8.8","low_24h":"3","base_volume_24h":"13.77340909",
 "quote_volume_24h":"78.49886361","timestamp":"2018-12-20T03:13:41.664Z"}]}

 {"table":"spot/candle60s","data":[{"candle":["2018-12-20T06:18:00.000Z","8.8","8.8","8.8","8.8","0"],"instrument_id":"ETH-USDT"}]}

Unsubscription

Users can cancel one or more channels.

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

send:

{"op": "unsubscribe", "args": ["spot/ticker:BTC-USDT", "spot/candle60s:BTC-USDT"]}

response:

{"event":"unsubscribe","channel":"spot/ticker:BTC-USDT"}
{"event":"unsubscribe","channel":"spot/candle60s:BTC-USDT"}

Login

Please refer to the Authentication section to understand how a valid authenticated sign is made with requests.

Login subscription format:

{"op":"login","args":["<api_key>","<passphrase>","<timestamp>","<sign>"]

Response:

{"event":"login","success":"true"}

Example:

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

api_key:'api_key' is apply 'apiKey' for users

passphrase:The passphrase entered when creating the API key

timestamp: Must be number of seconds since unix-epoch in UTC Decimal values are allowed. The timestamp will expire for every 30 seconds. It is recommended to use the time endpoint to retrieve the server time if you find a large discrepancy between your server time and the API server.

sign:It is the authentication string. the description of generating a valid sign can be referred to in the Authentication section.

Example of timestamp:const timestamp = '' + Date.now() / 1000

Example of sign : sign=CryptoJS.enc.Base64.Stringify(CryptoJS.HmacSHA256(timestamp +'GET'+ '/users/self/verify', secret))

methodis preset as'GET'。

requestPath is preset as '/users/self/verify'

If the login fails, the connection will be automatically cut.

Connect limit

Connection limit:once per second

Subscription limit:240 times per hour

If there is no data returned after connection to Websocket is established, the connection will break in 30 seconds. Users are advised to do the followings:

  • Set a timer each time that a response message is received.
  • If the timer is triggered, which means that no new message is received within N seconds, send the string 'ping'.
  • Expect a ‘pong’ as response message. If the response message is not received within 5 seconds, please signal an error alert or reconnect.

The connection will be cut if there happens a network problem.

Checksum

This function helps users verify the accuracy of depth data.

Every time when depth data is pushed, a timestamp and a checksum value are returned together. A total of 200 entries of depth data will be returned after the subscription is successfully established. And the depth data afterwards is incremental. Each time the incremental data is pushed, the crc 32 value comprised of the first 25 string of latest 200 depth data should be calculated by the users. And the result should be compared with the Checksum value provided together with the latest incremental data. If the Checksum are the same, the connection is correctly established, otherwise please re-subscribe the channel.

The notes of depth aggregation: A total of 200 entries of depth data will be returned after the subscription is successfully established, the depth data received afterwards is incremental. Then the 200 entries of the price of ask & bid array shall be traversed with the incremental data. If the prices match, look at the quantity. If the quantity is 0, then delete the depth data; if the quantity has changed, replace the original data; if the price cannot be matched, sort the entry by the price.

Calculation Description: The value of checksum is a signed integer (32 bit)

1,The following data is aligned with bid and ask, the checksum String will be bid:ask:bid:ask:....


"data": [{
        "instrument_id": "BTC-USDT",
        "asks": [["3366.8", "9", 10],[ "3368","8",3]],
        "bids": [
            ["3366.1", "7", 0],[ "3366","6",3 ]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1881014294
    }]

The checksum string of this example will be 3366.1:7:3366.8:9:3366:6:3368:8

2,If bid and ask data does not align , the checksum String will be bid:ask:ask:ask:....

"data": [{
        "instrument_id": "BTC-USDT",
        "asks": [["3366.8", "9", 10],[ "3368","8",3],[ "3372","8",3 ]],
        "bids": [
            ["3366.1", "7", 0]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": 831078360
    }]

The checksum String of this example will be 3366.1:7:3366.8:9:3368:8:3372:8

The pushed data of depth channel that user receives are:

First 200 entries


{
    "table": "spot/depth",
    "action": "partial",
    "data": [{
        "instrument_id": "ETH-USDT",
        "asks": [
            ["8.8", "96.99999966", 1],
            ["9", "39", 3],
            ["9.5", "100", 1],
            ["12", "12", 1],
            ["95", "0.42973686", 3],
            ["11111", "1003.99999795", 1]
        ],
        "bids": [
            ["5", "7", 4],
            ["3", "5", 3],
            ["2.5", "100", 2],
            ["1.5", "100", 1],
            ["1.1", "100", 1],
            ["1", "1004.9998", 1]
        ],
        "timestamp": "2018-12-18T07:27:13.655Z",
        "checksum": 468410539
    }]
}

Increment:

{
    "table": "spot/depth",
    "action": "update",
    "data": [{
        "instrument_id": "BTC-USDT",
        "asks": [],
        "bids": [
            ["3983", "789", 0, 3]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1200119424
    }]
}

Channel List

Channels that don't require login authentication includes: channels of market data, candlestick line, transaction data, fee rate, limit price spectrum, order book depth and mark price.

Channels that require login authentication includes: channels of account information, transaction information and positions.

Channels that don't require login

spot/ticker // ticker channel

spot/candle60s // 1mins candlestick

spot/trade // trade information

spot/depth //depth information,200 bids & asks for the first time, followed by incremental data

spot/depth5 //depth information, the best 5 bids & asks each time the request is returned

Channels that require login

spot/account //User's account information

spot/margin_account //User's margin account information

spot/order //User's order information

User Spot Account

Retrieve the user's spot account information (login authentication required).

send examples
{"op": "subscribe", "args": ["spot/account:BTC"]}

spot/account is the channel name,BTC is the currency

Response
Parameters type Description
currency String Token symbol
balance String Remaining balance
hold String Amount on hold(not available)
available String Available amount for trading or transfer
response examples
{
    "table": "spot/account",
    "data": [{
        "balance": "881.5011237890123457",
        "available": "868.4011237890123457",
        "currency": "USDT",
        "hold": "13.1"
    }]
}

User Margin Account

Retrieve the user's margin account information (login authentication required).

send example
{"op": "subscribe", "args": ["spot/margin_account:ETH-USDT"]}

spot/margin_account is channel nameETH-USDT is instrument_id

response parameters
Parameters Parameters type Description
instrument_id String Trading pair
balance String Remaining balance
hold String Amount on hold(not available)
available String Available amount for trading or transfer
borrowed String Borrowed tokens (unpaid))
lending_fee String Interest (unpaid)
response example
{
    "table":"spot/margin_account",
    "data":[
        {
            "currency:USDT":{
                "available":"95.4675",
                "balance":"100",
                "borrowed":"0",
                "hold":"4.5325",
                "lending_fee":"0"
            },
            "currency:BTC":{
                "available":"0",
                "balance":"0",
                "borrowed":"0",
                "hold":"0",
                "lending_fee":"0"
            },
            "instrument_id":"BTC-USDT"
        }
    ]
}

User Orders

Retrieve the user's transaction information (login authentication required).

Example send
{"op": "subscribe", "args": ["spot/order:LTC-USDT"]}

spot/order is channel nameLTC-USDT is instrument_id

Response
Parameters Type Description
order_id String Order ID
client_oid String Client supplied order ID
price String Price
size String Size of the order in the unit of the quote currency
notional String The amount allocated for buying. Returned for market orders
instrument_id String Trading pair
side String Buy or sell
type String limit,market(defaulted as limit)
timestamp String Time of order creation
filled_size String Quantity of order filled
filled_notional String Amount of order filled
margin_trading String 1 spot order. 2 margin order
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
last_fill_px String Latest Filled Price. '0' will be returned if the data is empty
last_fill_qty String Latest Filled Volume. '0' will be returned if the data is empty.
last_fill_time String Latest Filled Time. The '1970-01-01T00:00:00.000Z' will be returned if the data is empty.
state String Order Status(-2:Failed,-1:Canceled,0:Open ,1:Partially Filled, 2:Fully Filled,3:Submitting,4:Cancelling,)
Notes

The status is the older version of the state and is interchangeable in the short term. It is recommended to switch to state.

Example Response
{
    "table":"spot/order",
    "data":[
        {
            "client_oid":"oktspot5",
            "filled_notional":"0",
            "filled_size":"0",
            "instrument_id":"BTC-USDT",
            "last_fill_px":"0",
            "last_fill_qty":"0",
            "last_fill_time":"1970-01-01T00:00:00.000Z",
            "margin_trading":"2",
            "notional":"",
            "order_id":"2666285202473984",
            "order_type":"3",
            "price":"4535.8",
            "side":"buy",
            "size":"0.001",
            "state":"cancelled",
            "timestamp":"2019-04-16T13:11:23.000Z",
            "type":"limit"
        }
    ]
}

Public-Ticker

Retrieve the latest price, best bid & offer and 24-hours trading volume of a single contract.

Example Sends:
{"op": "subscribe", "args": ["spot/ticker:ETH-USDT"]}

spot/ticker is channel name ,ETH-USDT is instrument_id

Response
Parameter Type Description
instrument_id String Contract ID, e.g., BTC-USD-170310
last String Lst price
best_bid String Best bid price
best_ask String Best ask price
open_24h String 24-hour open
high_24h String 24-hour high
low_24h String 24-hour low
base_volume_24h String 24-hour trading volume of the base currency
quote_volume_24h String 24-hour trading volume of the quote currency
timestamp String Timestamp
response examples
{
    "table": "spot/ticker",
    "data": [{
        "instrument_id": "ETH-USDT",
        "last": "8.8",
        "best_bid": "5",
        "best_ask": "8.8",
        "open_24h": "6.6",
        "high_24h": "8.8",
        "low_24h": "4",
        "base_volume_24h": "85.68492053",
        "quote_volume_24h": "570.14238013",
        "timestamp": "2018-12-17T12:28:29.250Z"
    }]
}

Public-Candlesticks

Retrieve the candlestick data

channel lists:

spot/candle60s // 1mins candlestick

spot/candle180s // 3mins candlestick

spot/candle300s // 5mins candlestick

spot/candle900s // 15mins candlestick

spot/candle1800s // 30mins candlestick

spot/candle3600s // 1hour candlestick

spot/candle7200s // 2hour candlestick

spot/candle14400s // 4hour candlestick

spot/candle21600 // 6hour candlestick

spot/candle43200s // 12hour candlestick

spot/candle86400s // 1day candlestick

spot/candle604800s // 1week candlestick

send examples
{"op": "subscribe", "args": ["spot/candle60s:ETH-USDT"]}

spot/candle60s is channel name,ETH-USDT is instrument_id

response parameters
Parameters Parameters Types Description
timestamp String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
currency_volume String The trading volume in a specific token
instrument_id String Trading pair
response examples
{
    "table":"spot/candle60s",
    "data":[
        {
            "candle":[
                "2019-04-16T10:49:00.000Z",
                "162.03",
                "162.04",
                "161.96",
                "161.98",
                "336.452694"
            ],
            "instrument_id":"ETH-USDT"
        }
    ]
}

Public-Trade

Get the filled orders data

Example Send
{"op": "subscribe", "args": ["spot/trade:ETH-USDT"]}

spot/trade is the channel nameETH-USDT is instrument_id

response parameters
Parameters Parameters Types Description
trade_id String Transaction id
price String Filled price
size String Filled size
side String Filled side (buy/sell)
timestamp String Filled time
instrument_id String Trading pair
Example Response

{
        ”table”: "spot/trade”,
        ”data”: [
                [{
                        ”instrument_id”: "ETH-USDT”,
                        ”price”: "22888”,
                        ”side”: "buy”,
                        ”size”: "7”,
                        ”timestamp”: "2018-11-22T03:58:57.709Z”,
                        ”trade_id”: "108223090144493569”
               }]
        ]
}

Public-Depth5

Back to the previous five entries of depth data,This data is snapshot data per 100 milliseconds.For every 100 milliseconds, we will snapshot and push 5 entries of market depth data of the current order book.

Example Send
{"op": "subscribe", "args": ["spot/depth5:ETH-USDT"]}

spot/depth5 is channel nameETH-USDT is instrument_id

response parameters
Parameter Type Description
price String price
size String Size
timestamp String timestamp
num_orders String total orders in the book
instrument_id String trading pair

bids and asks value example: In [“411.8”,”10”,8”], 411.8 is price depth, 10 is price amount, 8 is the orders depth.

response examples

{
    "table":"spot/depth5",
    "data":[
        {
            "asks":[
                [
                    "161.96",
                    "7.37567",
                    3
                ],
                [
                    "161.97",
                    "1.308",
                    1
                ],
                [
                    "161.98",
                    "2.463509",
                    1
                ],
                [
                    "161.99",
                    "5.185",
                    2
                ],
                [
                    "162",
                    "29.184592",
                    5
                ]
            ],
            "bids":[
                [
                    "161.94",
                    "4.552355",
                    1
                ],
                [
                    "161.91",
                    "7.949",
                    3
                ],
                [
                    "161.9",
                    "2.213",
                    1
                ],
                [
                    "161.89",
                    "11.999998",
                    1
                ],
                [
                    "161.88",
                    "6.585142",
                    3
                ]
            ],
            "instrument_id":"ETH-USDT",
            "timestamp":"2019-04-16T11:03:03.712Z"
        }
    ]
}

Public-Depth

After subscription, 200 entries of market depth data of the order book will first be pushed. Subsequently every 100 milliseconds we will snapshot and push entries that have changed during this time.

send examples
{"op": "subscribe", "args": ["spot/depth:ETH-USDT"]}

spot/depth is channel nameETH-USDT is trading pair

Response
Parameter Types Description
price String price
size String Size
timestamp String Timestamp
num_orders String Total orders in the book
instrument_id String Trading pair
checksum String Checksum

bids and asks value example: In [“411.8”,”10”,8”], 411.8 is price depth, 10 is price amount, 8 is the orders depth.

Example Response
 First 200 entries 


{
    "table":"spot/depth",
    "action":"partial",
    "data":[
        {
            "instrument_id":"ETH-USDT",
            "asks":[
                [
                    "162.5",
                    "14.29884",
                    2
                ],
                [
                    "162.51",
                    "2.084362",
                    1
                ],
               ...

                [
                    "168.51",
                    "7.760755",
                    2
                ],
                [
                    "168.57",
                    "0.02",
                    1
                ]
            ],
            "bids":[
                [
                    "162.49",
                    "1.556106",
                    3
                ],
                [
                    "162.47",
                    "0.00913",
                    1
                ],
               ...

                [
                    "155.15",
                    "70",
                    1
                ],
                [
                    "155.13",
                    "3",
                    1
                ]
            ],
            "timestamp":"2019-04-16T10:17:28.507Z",
            "checksum":1141851215
        }
    ]
}

Increment:

{
    "table":"spot/depth",
    "action":"update",
    "data":[
        {
            "instrument_id":"ETH-USDT",
            "asks":[
                [
                    "162.5",
                    "0",
                    0
                ],
                [
                    "162.51",
                    "0",
                    0
                ],
                [
                    "162.52",
                    "0",
                    0
                ],
                [
                    "162.53",
                    "232.105791",
                    1
                ],
                [
                    "162.59",
                    "8",
                    1
                ],
                [
                    "168.66",
                    "0.0016",
                    1
                ],
                [
                    "168.69",
                    "0.006",
                    1
                ],
                [
                    "168.73",
                    "0.002082",
                    1
                ]
            ],
            "bids":[
                [
                    "162.49",
                    "1.512544",
                    2
                ],
                [
                    "162.47",
                    "0.05333",
                    2
                ],
                [
                    "162.3",
                    "5.353085",
                    5
                ],
                [
                    "162.29",
                    "6.569261",
                    12
                ],
                [
                    "162.25",
                    "8.308575",
                    3
                ]
            ],
            "timestamp":"2019-04-16T10:17:29.045Z",
            "checksum":227291232
        }
    ]
}

Futures

This is the V3 Websocket API for Futures.

General

WebSocket protocol is a new HTML5 protocol, which provides full-duplex communication between web browsers and web servers. Connection can be established after one handshake. Web server can then push business logic data to web browsers.Advantages:

Request header is small in size (around 2 bytes) during communication Since there is no need to create and delete TCP connection repeatedly, it saves resources We strongly recommend developers to use Websocket API to access market related information and trading depth. Should you have any questions, feel free to contact our support team.

We strongly recommend developers to use Websocket API to access market related information and trading depth.

All the messages returning from WebSocket API will be optimized by Deflate compression. All users will be required to decompress the messages by themselves with the methods they find most appropriate. Please refer to our demo

The connection will break automatically when a network problem occurs

url:wss://real.okex.com:8443/ws/v3

Command Format

send format:

{"op": "<value>", "args": ["<value1>","<value2>"]}

the value of op 1-- subscribe 2--unsubscribe 3--login

args: the value is the channel name, which can be one or more channels

Successful response format:

  {"event": "<value>","channel":"<value>"}
  {"table":"channel","data":"[{"<value1>","<value2>"}]"}

In the futures/depth channel, the return formats for distinguishing between the first full amount and the subsequent incremental are:


{"table":"channel", "action":"<value>","data":"[{"<value1>","<value2>"}]"}

Failure response format:

{"event":"error","message":"<error_message>","errorCode":"<errorCode>"}

Subscription

Users may subscribe to one or more channels,The total length of multiple channels should not exceed 4,096 bytes. ,

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

Description : the value of op is subscribe

args :The array content is channel names :<channelname>:<filter>

The channelname is composed of business/channel

futures push business is futures, channel for each specific name under this business, If a channel name consists of two separate words, they will be connected with an underscore " _ "

Example:

"futures/ticker:BTC-USD-170310"or "futures/price_range:BTC-USD-170310"

Filter is filterable data. For details, please refer to the description of each channel

Example :

send:

{"op": "subscribe", "args": ["futures/ticker:BTC-USD-170310", "futures/candle60s:BTC-USD-170310"]}

response:

{"event":"subscribe","channel":"futures/ticker:BTC-USD-170310"}

{"event":"subscribe","channel":"futures/candle60s:BTC-USD-170310"}

{"table":"futures/ticker","data":[{"last":3916.9594,"best_bid":3916.508,"high_24h":3918.1759,"low_24h":3916.508,
"volume_24h":234,"best_ask":3916.9614,"instrument_id":"BTC-USD-170310","timestamp":"2018-12-20T02:33:01.448Z"}]}

{"table":"futures/candle60s","data":[{"candle":["2018-12-20T02:35:00.000Z","3916.9594","3916.9594",
"3916.9594","3916.9594","0","0.0"],"instrument_id":"BTC-USD-170310"}]}

Unsubscription

Users can cancel one or more channels.

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

send:

{"op": "unsubscribe", "args": ["futures/ticker:BTC-USD-170310", "futures/candle60s:BTC-USD-170310"]}

response:

{"event":"unsubscribe","channel":"futures/ticker:BTC-USD-170310"}
{"event":"unsubscribe","channel":"futures/candle60s:BTC-USD-170310"}

Login

The login method description can be found in the verification part in the API overview

Login subscription format:

{"op":"login","args":["<api_key>","<passphrase>","<timestamp>","<sign>"]}

Response:

{"event":"login","success":"true"}

Example:

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

api_key:'api_key' is apply 'apiKey' for users

passphrase:The passphrase entered when subscribing the apikey

timestamp: Must be number of seconds since unix-epoch in UTC Decimal values are allowed,your timestamp must be within 30 seconds of the api service time or your request will be considered expired and rejected, We recommend using the time endpoint to query for the API server time if you believe there many be time skew between your server and the API servers.

sign:is a signing String. The signing rules can be seen in the request description (API overview and validation part).A passphrase should be filled when applying for v3 API

Example of timestamp:const timestamp = '' + Date.now() / 1000

Example of sign : sign=CryptoJS.enc.Base64.Stringify(CryptoJS.HmacSHA256(timestamp +'GET'+ '/users/self/verify', secret))

methodis preset as'GET'。

requestPath is preset as '/users/self/verify'

If the login fails, the link will be automatically disconnected.

Connect limit

Connection limit:1 times/s

Subscription limit:240 times/hour

if there is no data return after connecting to ws, the connection will break in 30s.Users are advised to do the followings:

Set a timer after receiving a message. If the timer is triggered (no new message received within N seconds) send the String 'ping'.Expect a text String 'pong' as a response. If you do not receive it within 5 seconds, please issue an error or reconnect.

Checksum

This function can help users verify the accuracy of depth data.

Checksum rule: Every time when depth data is pushed, a timestamp and a checksum check are added. Take the price and quantity in the first 25 entries of bids and asks data out of the 200 entries of depth data after each data merge, and use the crc32 value of the String comprised of the price and number connected by a colon. User can compare the value of their checksum with the checksum value of the subscription. If there is no match, the users can re-subscribe. This function can help users verify the accuracy of depth data.

Instructions of depth merge: 200 entries of depth data for the first time, Then take the data of each increment and scan the prices in the asks and bids in the 200 entries. If the prices match, look at the quantity. If the quantity is 0, then delete the depth data; if the quantity has changed, replace the original data; if the price cannot be matched, sort the entry by the price.

Calculation Description: A checksum message will be sent every book iteration,where CHECKSUM is a signed integer (32-bit)

1,The following data is aligned with bid and ask, the checksum String will be bid:ask:bid:ask:....

(see the following example)


"data": [{
        "instrument_id": "BTC-USD-170310",
        "asks": [[3366.8, 9, 10, 3],[ 3368,8,3,4 ]],
        "bids": [
            [3366.1, 7, 0, 3],[ 3366,6,3,4 ]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1881014294
    }]

The checksum String of this example will be 3366.1:7:3366.8:9:3366:6:3368:8

2,If bid and ask data does not align , the checksum String will be bid:ask:ask:ask:.... (see the following example)

"data": [{
        "instrument_id": BTC-USD-170310,
        "asks": [[3366.8, 9, 10, 3],[ 3368,8,3,4 ],[ 3372,8,3,4 ]],
        "bids": [
            [3366.1, 7, 0, 3]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": 831078360
    }]

The checksum String of this example will be 3366.1:7:3366.8:9:3368:8:3372:8

The push data depth channel users receive is:

First 200 amount


{
    "table": "futures/depth",
    "action": "partial",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "asks": [[3983, 888, 10, 3],....],
        "bids": [
            [3983, 789, 0, 3],....
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": 200119424
    }]
}

Increment:

{
    "table": "futures/depth",
    "action": "update",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "asks": [],
        "bids": [
            [3983, 789, 0, 3]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1200119424
    }]
}

Channel List

Channels that don't require login

futures/ticker // ticker

futures/candle60s // 1mins kline channel

futures/trade // trade information

futures/estimated_price // estimated price

futures/price_range //price range

swap/depth //depth information , 200 entries of depth data for the first time, then increment data

swap/depth5 //depth information, the previous five entries of depth data

swap/mark_price // mark price

Channels that require login

swap/account //User's account information

swap/position //User's position information

swap/order //User's order information

User Position

Get the information of holding positions of a contract. require login

send examples
{"op": "subscribe", "args":["futures/position:EOS-USD-190628"]}

futures/position is channel name ,BTC-USD-170317 is instrument_id

response parameters
fixed Parameters Parameters Types Description
margin_mode String Account Types: fixed
long_qty String Quantity of long positions
long_avail_qty String Available positions to be closed for long positions
long_margin String Margin for long positions
long_liqui_price String Forced liquidation price for long positions
long_pnl_ratio String Profit and loss ratio of long positions
long_avg_cost String Average price for opening positions
long_settlement_price String Standard settlement price
realized_pnl String Realized profits of long positions
long_leverage String Leverage for long positions
short_qty String Quantity of short positions
short_avail_qty String Available positions to be closed for short positions
short_margin String Margin for short positions
short_liqui_price String Forced liquidation price for short positions
short_pnl_ratio String Profit and loss ratio of short positions
short_avg_cost String Average price for opening positions
short_settlement_price String Standard settlement price
short_leverage String Leverage for short positions
instrument_id String Contract ID, e.g.BTC-USDT-180909
created_at String Creation date
updated_at String Last adjusting time
short_margin_ratio String Margin ratio of short positions
short_maint_margin_ratio String Maintenance margin ratio of short positions
short_pnl String Profit of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
short_open_outstanding string Number of Frozen Short Positions
short_settled_pnl String Realized Profit of Short Positions
long_margin_ratio String Margin ratio of long positions
long_maint_margin_ratio String Maintenance margin ratio of long positions
long_pnl String Profit of long positions
long_unrealised_pnl String Unrealized profits and losses of long positions
long_open_outstanding string Number of Frozen Long Positions
long_settled_pnl String Realized Profit of Long Positions
last String Last traded price
timestamp String Order status timestamp changed
response examples

{
    "table": "futures/position",
    "data": [{
        "long_qty": "0",
        "long_avail_qty": "0",
        "long_margin": "0",
        "long_liqui_price": "0",
        "long_pnl_ratio": "0.18941511",
        "long_avg_cost": "4.56388409",
        "long_settlement_price": "4.56388409",
        "realised_pnl": "-0.00064488",
        "short_qty": "1",
        "short_avail_qty": "1",
        "short_margin": "0.21496131",
        "short_liqui_price": "5.112",
        "short_pnl_ratio": "0",
        "short_avg_cost": "4.652",
        "short_settlement_price": "4.652",
        "instrument_id": "EOS-USD-190628",
        "long_leverage": "10",
        "short_leverage": "10",
        "created_at": "2019-04-01T11:33:52.000Z",
        "updated_at": "2019-05-06T07:48:09.000Z",
        "margin_mode": "fixed"
    }]
}
response parameters
crossed parameter parameter type Description
margin_mode String Account Type: crossed
liquidation_price String Estimated liquidation price
long_qty String Quantity of long positions
long_avail_qty String Available positions to be closed for long positions
long_avg_cost String Average price for opening positions
long_settlement_price String Standard settlement price for long positions
realized_pnl String Realized profits of long positions
leverage String Leverage
short_qty String Quantity of short positions
short_avail_qty String Available positions to be closed for short positions
short_avg_cost String Average price for opening positions
short_settlement_price String Standard settlement price for short positions
instrument_id String Contract ID, e.g. BTC-USDT-180213
created_at String Creation date
updated_at String Last adjusting time
short_margin String Margin for short positions
short_pnl String Profit of short positions
short_pnl_ratio String Profit rate of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
long_margin String Margin for long positions
long_pnl String Profit of long positions
long_pnl_ratio String Profit rate of long positions
long_unrealised_pnl String Unrealized profits and losses of long positions
long_open_outstanding string Number of Frozen Long Positions
short_open_outstanding string Number of Frozen Short Positions
last String Last traded price
Explanation

Timestamp will return the relevant creation time, transaction time, cancelation time, etc. according to the order status changes. For detailed status, users can refer to the “state” parameter.

response examples
{
    "table":"futures/position",
    "data":[
        {
            "long_qty":"1",
            "long_avail_qty":"1",
            "long_avg_cost":"3175.115",
            "long_settlement_price":"3175.115",
            "realised_pnl":"0.007",
            "short_qty":"18",
            "short_avail_qty":"18",
            "short_avg_cost":"4275.449",
            "short_settlement_price":"4275.449",
            "liquidation_price":"0.0",
            "instrument_id":"BTC-USD-170317",
            "leverage":"10",
            "created_at":"2018-12-14T06:09:37.000Z",
            "updated_at":"2018-12-19T07:16:19.000Z",
            "margin_mode":"crossed",
            "last":"67.905"            
        }
    ]
}

User Account

Get the user's account information , require login.

send examples
{"op": "subscribe", "args":["futures/account:EOS"]}

futures/account is channel name ,BTC is token

Response Parameters
Cross_margin Parameters Parameters Types Description
currency String Token, eg."BTC”
margin_mode String Account Type: crossed
equity String Equity of the account
total_avail_balance String Balance of the account (Static benefits of an account)
margin String Margin for positions
realized_pnl String Realized profit and loss
unrealized_pnl String Unrealized profit and loss
margin_ratio String Margin ratio
margin_frozen String Position margin
margin_for_unfilled String Margin on hold for open orders
maint_margin_ratio String Maintenance Margin Ratio
liqui_mode string Liquidation mode: tier(partial)
available string Available margin
open_max string Maximum Number of Positions Available
timestamp String Order status timestamp changed
Explanation

Timestamp will return the relevant creation time, transaction time, cancelation time, etc. according to the order status changes. For detailed status, users can refer to the “state” parameter.

Cross_margin
{
    "table": "futures/account",
    "data": [{
        "BTC": {
            "equity": "102.38162222",
            "margin": "3.773884998",
            "margin_mode": "crossed",
            "margin_ratio": "27.129",
            "realized_pnl": "-34.53829072",
            "total_avail_balance": "135.54",
            "unrealized_pnl": "1.37991294"
        }
    }]
}
Response Parameters
Fixed_margin Parameters Parameters Types Description
currency String Token, e.g. "btc”
margin_mode String Account Types: fixed
fixed_balance String Account balance
available_qty String Available quantity
margin_frozen String required after the funds are put on hold
margin_for_unfilled String Assets on hold
realized_pnl String Realized profit and loss
unrealized_pnl String Unrealized profit and loss
equity String Equity of the account(Dynamic benefits of an account)
total_avail_balance String Balance of the account(Static benefits of an account)
liqui_mode string Liquidation mode: tier(partial), legacy(full)
long_open_max string Available margin
short_open_max string Maximum Number of Positions Available
available string Available margin
can_withdraw string transferrable amount
timestamp String Order status timestamp changed
Explanation

Timestamp will return the relevant creation time, transaction time, cancelation time, etc. according to the order status changes. For detailed status, users can refer to the “state” parameter.

Fixed margin

{
    "table": "futures/account",
    "data": [{
        "EOS": {
            "contracts": [{
                "available_qty": "1.42897151",
                "fixed_balance": "0",
                "instrument_id": "EOS-USD-190628",
                "margin_for_unfilled": "0.21496131",
                "margin_frozen": "0",
                "realized_pnl": "0",
                "unrealized_pnl": "0"
            }],
            "equity": "1.64393282",
            "margin_mode": "fixed",
            "total_avail_balance": "1.64393282"
        }
    }]
}

User Orders

Get user's order information , require login .

send examples
{"op": "subscribe", "args":["futures/order:EOS-USD-190628"]}

futures/order is channel name ,BTC-USD-170317 is instrument_id

response parameters
Parameters Parameters type Description
instrument_id String Contract ID, e.g. BTC-USD-170317
client_oid String the order ID customised by yourself
size String Quantity
timestamp String Order status timestamp changed
filled_qty String Filled quantity
fee String Fees
order_id String Order ID
price String Order price
price_avg String Average price
type String 1:open long 2:open short 3:close long 4:close short
contract_val String Contract value
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
last_fill_px String Last transaction price (if none, push 0))
last_fill_qty String Last transaction amount (if none, push 0)
last_fill_time String Last transaction time (if none, push 0)
state String Order state("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling,"6": Incomplete(open+partially filled),"7":Complete(cancelled+fully filled))
trade_id String Bill ID
Explanation

Timestamp will return the relevant creation time, transaction time, cancelation time, etc. according to the order status changes. For detailed status, users can refer to the “state” parameter.

"status" is the older version of the "state" parameter and is compatible in the short term. It is recommended to switch to "state".

response examples

{
    "table": "futures/order",
    "data": [{
        "leverage": "10",
        "last_fill_time": "2019-05-06T07:48:09.451Z",
        "filled_qty": "1",
        "fee": "-0.00064488",
        "price_avg": "4.652",
        "type": "2",
        "client_oid": "",
        "last_fill_qty": "1",
        "instrument_id": "EOS-USD-190628",
        "last_fill_px": "4.652",
        "size": "1",
        "price": "4.652",
        "state": "2",
        "contract_val": "10",
        "order_id": "2778260402355200",
        "order_type": "0",
        "timestamp": "2019-05-06T07:48:09.000Z",
        "state": "2"
    }]
}

Public-Full Contract Updates Subscription Channel

Full Contract Updates Subscription Channel

When a new contract is available for trading after settlement, full contract data of all currency will be pushed in this channel ,no login required.

send examples

{"op": "subscribe", "args": ["futures/instruments"]}

futures/instruments is channel name

response parameters
Parameters Parameters Types Description
instrument_id String Contract ID, e.g. “BTC-USD-190322”
underlying_index String Trade currency, such as BTC in BTC-USD-190322
quote_currency String Quote currency,such as USD in BTC-USD-190322
contract_val String Contract value (USD)
listing String Listing date
delivery String Delivery date
tick_size String Order price accuracy
trade_increment String Order quantity accuracy
alias String this_week next_week quarter
response examples
{
    "table": "futures/instruments",
    "data": [
        [
            {
                "instrument_id": "BTC-USD-190809",
                "underlying_index": "BTC",
                "quote_currency": "USD",
                "tick_size": "0.01",
                "contract_val": "100",
                "listing": "2019-07-26",
                "delivery": "2019-08-09",
                "trade_increment": "1",
                "alias": "next_week"
            },
            {
                "instrument_id": "BTC-USD-190927",
                "underlying_index": "BTC",
                "quote_currency": "USD",
                "tick_size": "0.01",
                "contract_val": "100",
                "listing": "2019-06-14",
                "delivery": "2019-09-27",
                "trade_increment": "1",
                "alias": "quarter"
            }
        ]
    ]
}

Public-Ticker

To capture the latest traded price, best-bid price, best-ask price, and 24-hour trading volume of all futures contracts on the platform.

send examples:
{"op": "subscribe", "args":["futures/ticker:BTC-USD-190628"]}

futures/ticker is channel name ,BTC-USD-170310 is instrument_id

response parameters
Parameters Parameters types Description
instrument_id String Contract ID,e.g .BTC-USD-170310
last String Last traded price
best_ask String best ask price
best_bid String best bid price
high_24h String 24 hour high
low_24h String 24 hour low
volume_24h String 24 hour trading volume (contracts)
timestamp String timestamp
open_interest String Open Position
open_24h String 24-Hour Opening Price
volume_token_24h String Trading Volume (Token)
response examples

{
    "table": "futures/ticker",
    "data": [{
        "last": "5556.91",
        "best_bid": "5556.81",
        "high_24h": "5729",
        "low_24h": "5519.58",
        "volume_24h": "4936686",
        "best_ask": "5556.91",
        "instrument_id": "BTC-USD-190628",
        "timestamp": "2019-05-06T07:19:37.790Z"
    }]
}

Public-Candlesticks

Kline information for futures business

channel lists:

futures/candle60s // 1mins kline channel

futures/candle180s // 3mins kline channel

futures/candle300s // 5mins kline channel

futures/candle900s // 15mins kline channel

futures/candle1800s // 30mins kline channel

futures/candle3600s // 1hour kline channel

futures/candle7200s // 2hour kline channel

futures/candle14400s // 4hour kline channel

futures/candle21600 // 6hour kline channel

futures/candle43200s // 12hour kline channel

futures/candle86400s // 1day kline channel

futures/candle604800s // 1week kline channel

send examples
{"op": "subscribe", "args":["futures/candle180s:BTC-USD-190628"]}

swap/candle60s is channel name,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Types Description
timestamp String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
currency_volume String The trading volume in a specific token
instrument_id String Contract ID e.g.BTC-USD-170310
response examples

{
    "table": "futures/candle180s",
    "data": [{
        "candle": ["2019-05-06T07:18:00.000Z", "5564.04", "5564.04", "5556.91", "5556.91", "4646", "83.56385328"],
        "instrument_id": "BTC-USD-190628"
    }]
}

Public-Trade

Get the filled orders data

send examples
{"op": "subscribe", "args":["futures/trade:BTC-USD-190628"]}

swap/trade is channel name ,BTC-USD-170310 is instrument_id

response parameters
Parameters Parameters Types Description
trade_id String Transaction id
price String Filled price
qty String Filled size
side String Filled side (buy/sell)
timestamp String Filled time
instrument_id String Contract ID e.g.BTC-USD-170310
response examples


{
    "table": "futures/trade",
    "data": [{
        "side": "buy",
        "trade_id": "2778148208082945",
        "price": "5556.91",
        "qty": "5",
        "instrument_id": "BTC-USD-190628",
        "timestamp": "2019-05-06T07:19:37.496Z"
    }]
}

Public-Price Range

The maximum buying price and the minimum selling price of the contract.

send examples
{"op": "subscribe", "args":["futures/price_range:BTC-USD-190628"]}

futures/price_range is channel name ,BTC-USD-170310 is instrument_id

response parameters
Parameters Parameters Types Description
timestamp String timestamp
lowest String Minimum buying price
instrument_id String Contract ID, e.g. BTC-USD-170310
highest String Maximum buying price
response examples


{
    "table": "futures/price_range",
    "data": [{
        "highest": "5729.32",
        "lowest": "5392.32",
        "instrument_id": "BTC-USD-190628",
        "timestamp": "2019-05-06T07:19:35.004Z"
    }]
}

Public-Estimated price

Get estimated price

send examples
{"op": "subscribe", "args": ["futures/estimated_price:BTC-USD-170310"]}

futures/estimated_price is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-170310
settlement_price String Estimated delivery price
timestamp String Timestamp
response examples
{
        ”table”: "futures/estimated_price”,
        ”data”: [{
                ”instrument_id”: "BTC-USD-170310”,
                ”settlement_price”: "22616.58”,
                ”timestamp”: "2018-11-22T10:09:31.541Z”
        }]
}

Public-Depth5

The latest 5 entries of the market depth data is snapshooted and pushed every 100 milliseconds.

send examples
{"op": "subscribe", "args":["futures/depth5:BTC-USD-190628"]}

futures/depth5 is channel name ,BTC-USD-170310 is instrument_id

response parameters
Parameters Parameters Types Description
asks String Selling side
bids String Buying side
timestamp String System time stamp
instrument_id String Contract ID,e.g .BTC-USD-170310

[411.8,6,8,4][String ,int ,int ,int] 411.8 is the price, 6 is the size of the price, 8 is the number of force-liquidated orders, 4 is the number of orders of the price,timestamp is the timestamp of the orderbook.

response examples


{
    "table": "futures/depth5",
    "data": [{
        "asks": [
            ["5556.82", "11", "0", "1"],
            ["5556.84", "98", "0", "4"],
            ["5556.92", "1", "0", "1"],
            ["5557.6", "4", "0", "1"],
            ["5557.85", "2", "0", "1"]
        ],
        "bids": [
            ["5556.81", "1", "0", "1"],
            ["5556.8", "2", "0", "1"],
            ["5556.79", "1", "0", "1"],
            ["5556.19", "100", "0", "1"],
            ["5556.08", "2", "0", "1"]
        ],
        "instrument_id": "BTC-USD-190628",
        "timestamp": "2019-05-06T07:19:39.348Z"
    }]
}

Public-Depth

After subscription, 200 entries of market depth data of the order book will first be pushed. Subsequently every 100 milliseconds we will snapshot and push entries that have changed during this time.

send examples
{"op": "subscribe", "args":["futures/depth:BTC-USD-190628"]}

futures/depth is channel name ,BTC-USD-170310 is instrument_id

response parameters
Parameters Parameters Types Description
asks String Selling side
bids String Buying side
timestamp String System time stamp
instrument_id String Contract ID,e.g .BTC-USD-170310
checksum String checksum

[411.8,6,8,4] [String ,int ,int ,int] 411.8 is the price, 6 is the size of the price, 8 is the number of force-liquidated orders, 4 is the number of orders of the price,timestamp is the timestamp of the orderbook.

response examples
 First 200 entries 


{
    "table": "futures/depth",
    "action": "partial",
    "data": [{
        "instrument_id": "BTC-USD-190628",
        "asks": [
            ["5572.12", "0", "0", "0"],
            ["5572.91", "0", "0", "0"],
            ["5575.66", "0", "0", "0"],
            ["5576.12", "0", "0", "0"],
            ["5576.58", "50", "0", "1"],
            ["5577.04", "50", "0", "1"],
            ["5597.5", "894", "0", "1"],
            ["5598.23", "20", "0", "2"],
            ["5603.99", "1", "0", "1"],
            ["5604.65", "70", "0", "1"]
        ],
        "bids": [
            ["5556.82", "0", "0", "0"],
            ["5555.4", "0", "0", "0"],
            ["5555.15", "33", "0", "1"],
            ["5554.95", "0", "0", "0"],
            ["5554.93", "10", "0", "1"],
            ["5554.92", "12", "0", "1"],
            ["5554.82", "0", "0", "0"],
            ["5554.79", "0", "0", "0"],
            ["5554.71", "0", "0", "0"],
            ["5554.69", "17", "0", "1"],
        ],
        "timestamp": "2019-05-06T07:19:39.348Z",
        "checksum": -855196043
    }]
}

Public-Mark Price

Get the mark price

send examples
{"op": "subscribe", "args":["futures/mark_price:LTC-USD-190628"]}

futures/mark_price is channel name ,BTC-USD-170310 is instrument_id

response parameters
Parameters Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-170310
mark_price String Mark Price
timestamp String Timestamp

In order to avoid price fluctuation of futures caused by market manipulation, we set the mark price based on the spot index and a reasonable basis.

response examples

{
    "table": "futures/mark_price",
    "data": [{
        "instrument_id": "LTC-USD-190628",
        "mark_price": "70.557",
        "timestamp": "2019-05-06T07:19:39.835Z"
    }]
}

Perpetual Swap

This is the V3 Websocket API for Perpetual Swap.

Refer to SDK(Please see here for details)

General

WebSocket protocol is a new HTML5 protocol, which provides full-duplex communication between web browsers and web servers. Connection can be established after one handshake. Web server can then push business logic data to web browsers.Advantages:

Request header is small in size (around 2 bytes) during communication Since there is no need to create and delete TCP connection repeatedly, it saves resources We strongly recommend developers to use Websocket API to access market related information and trading depth. Should you have any questions, feel free to contact our support team.

We strongly recommend developers to use Websocket API to access market related information and trading depth.

All the messages returning from WebSocket API will be optimized by Deflate compression. All users will be required to decompress the messages by themselves with the methods they find most appropriate. Please refer to ourdemo

The connection will break automatically when a network problem occurs

url:wss://real.okex.com:8443/ws/v3

Command Format

send format:

{"op": "<value>", "args": ["<value1>","<value2>"]}

the value of op 1-- subscribe 2--unsubscribe 3--login

args: the value is the channel name, which can be one or more channels

Successful response format:

  {"event":"<value>","channel":"<value>"}
  {"table":"channel","data":"[{"<value1>","<value2>"}]"}

Only in the swap/depth channel, the return formats for distinguishing between the first full amount and the subsequent incremental are:


{"table":"channel", "action":"<value>","data":"[{"<value1>","<value2>"}]"}

Failure response format:

{"event":"error","message":"<error_message>","errorCode":"<errorCode>"}

Subscription

Users may subscribe to one or more channels,The total length of multiple channels should not exceed 4,096 bytes. ,

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

Description : the value of op is subscribe

args :The array content is channel names :<channelname>:<filter>

The channelname is composed of business/channel

Perpetual push business business is swap, channel for each specific name under this business, If a channel name consists of two separate words, they will be connected with an underscore " _ "

Example:

"swap/ticker:BTC-USD-SWAP"or "swap/price_range:BTC-USD-SWAP"

Filter is filterable data. For details, please refer to the description of each channel

Example :

send:

{"op": "subscribe", "args": ["swap/ticker:BTC-USD-SWAP", "swap/candle60s:BTC-USD-SWAP"]}

response:

 {"event": subscribe,"channel":"swap/ticker:BTC-USD-SWAP"}

 {"event": subscribe,"channel":"swap/candle60s:BTC-USD-SWAP"}

 {"table":"swap/ticker","data":[{"high_24h":"3369","instrument_id":"BTC-USD-SWAP","last":"3299",
 "low_24h":"3112","timestamp":"2018-12-09T08:12:04.659Z","volume_24h":"8389225"}]}

 {"table":"swap/candle60s","data":[{"instrument_id":"BTC-USD-SWAP","candle":["2018-12-09T08:12:00.000Z",
 "3299.8","3299.8","3299","3299","82","2.4854"]}]}

Unsubscription

Users can cancel one or more channels.

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

send:

{"op": "unsubscribe", "args": ["swap/ticker:BTC-USD-SWAP", "swap/candle60s:BTC-USD-SWAP"]}

response:

{"event":"unsubscribe","channel":"swap/ticker:BTC-USD-SWAP"}
{"event":"unsubscribe","channel":"swap/candle60s:BTC-USD-SWAP"}

Login

The login method description can be found in the verification part in the API overview

Login subscription format:

{"op":"login","args":["<api_key>","<passphrase>","<timestamp>","<sign>"]

Response:

{"event":"login","success":"true"}

Example:

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

api_key:'api_key' is apply 'apiKey' for users

passphrase:The passphrase entered when subscribing the apikey

timestamp: Must be number of seconds since unix-epoch in UTC Decimal values are allowed,your timestamp must be within 30 seconds of the api service time or your request will be considered expired and rejected, We recommend using the time endpoint to query for the API server time if you believe there many be time skew between your server and the API servers.

sign:is a signing String. The signing rules can be seen in the request description (API overview and validation part).A passphrase should be filled when applying for v3 API

Example of timestamp:const timestamp = '' + Date.now() / 1000

Example of sign : sign=CryptoJS.enc.Base64.Stringify(CryptoJS.HmacSHA256(timestamp +'GET'+ '/users/self/verify', secret))

methodis preset as'GET'。

requestPath is preset as '/users/self/verify'

If the login fails, the link will be automatically disconnected.

Connect limit

Connection limit:1 times/s

Subscription limit:240 times/hour

if there is no data return after connecting to ws, the connection will break in 30s.Users are advised to do the followings:

Set a timer after receiving a message. If the timer is triggered (no new message received within N seconds) send the String 'ping'.Expect a text String 'pong' as a response. If you do not receive it within 5 seconds, please issue an error or reconnect.

Checksum

This function can help users verify the accuracy of depth data.

Checksum rule: Every time when depth data is pushed, a timestamp and a checksum check are added. Take the price and quantity in the first 25 entries of bids and asks data out of the 200 entries of depth data after each data merge, and use the crc32 value of the String comprised of the price and number connected by a colon. User can compare the value of their checksum with the checksum value of the subscription. If there is no match, the users can re-subscribe. This function can help users verify the accuracy of depth data.

Instructions of depth merge: 200 entries of depth data for the first time, Then take the data of each increment and scan the prices in the asks and bids in the 200 entries. If the prices match, look at the quantity. If the quantity is 0, then delete the depth data; if the quantity has changed, replace the original data; if the price cannot be matched, sort the entry by the price.

Calculation Description: A checksum message will be sent every book iteration,where CHECKSUM is a signed integer(32-bit)

1,The following data is aligned with bid and ask, the checksum String will be bid:ask:bid:ask:....

(see the following example)


"data": [{
        "instrument_id": "BTC-USD-SWAP",
        "asks": [["3366.8", "9", 10, 3],[ "3368","8",3,4 ],....],
        "bids": [
            ["3366.1", "7", 0, 3],[ "3366","6",3,4 ]....
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1881014294
    }]

The checksum String of this example will be 3366.1:7:3366.8:9:3366:6:3368:8

2,If bid and ask data does not align , the checksum String will be bid:ask:ask:ask:.... (see the following example)

"data": [{
        "instrument_id": "BTC-USD-SWAP",
        "asks": [["3366.8", "9", 10, 3],[ "3368","8",3,4 ],[ "3372","8",3,4 ]],
        "bids": [
            ["3366.1", "7", 0, 3]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": 831078360
    }]

The checksum String of this example will be 3366.1:7:3366.8:9:3368:8:3372:8

The push data depth channel users receive is:

First 200 amount


{
    "table": "swap/depth",
    "action": "partial",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "asks": [["3983", "888", 10, 3],....],
        "bids": [
            ["3983", "789", 0, 3],....
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": 200119424
    }]
}

Increment:

{
    "table": "swap/depth",
    "action": "update",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "asks": [],
        "bids": [
            ["3983", "789", 0, 3]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1200119424
    }]
}

Channel List

Channels that don't require login

swap/ticker // ticker

swap/candle60s // 1mins kline channel

swap/trade // trade information

swap/funding_rate//funding rate

swap/price_range//price range

swap/depth //depth information,200 entries of depth data for the first time, then increment data

swap/depth5 //depth information, the previous five entries of depth data

swap/mark_price// mark price

Channels that require login

swap/account //User's account information

swap/position //User's position information

swap/order //User's order information

User Position

Get the information of holding positions of a contract. require login

send examples
{"op": "subscribe", "args":["swap/position:XRP-USD-SWAP"]}

swap/position is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Types Description
liquidation_price String liquidation price
position String Positions
avail_position String Positions available to be closed
avg_cost String Avg. position price
settlement_price String Settlement price
instrument_id String Contract ID, e.g. BTC-USD-SWAP
leverage String Leverage level
realized_pnl String Realized PnL
side String Side(long/short)
timestamp String Creation time
margin String Margin
margin_mode String Margin mode (fixed/crossed)
settled_pnl String Realized Profit of Positions
last String Last traded price
response examples


{
    "table": "swap/position",
    "data": [{
        "holding": [{
            "avail_position": "1",
            "avg_cost": "0.2985",
            "leverage": "5",
            "liquidation_price": "0.0136",
            "margin": "6.8129",
            "position": "1",
            "realized_pnl": "-0.0239",
            "settlement_price": "0.2941",
            "side": "long",
            "timestamp": "2019-05-06T07:12:25.733Z",
            "last":"67.905"
        }, {
            "avail_position": "1",
            "avg_cost": "0.2935",
            "leverage": "5",
            "liquidation_price": "0.0136",
            "margin": "6.8129",
            "position": "1",
            "realized_pnl": "-0.0239",
            "settlement_price": "0.2935",
            "side": "short",
            "timestamp": "2019-05-06T07:12:25.733Z",
            "last":"67.905"
        }],
        "instrument_id": "XRP-USD-SWAP",
        "margin_mode": "crossed"
    }]
}

User Account

Get the user's account information , require login.

send examples
{"op": "subscribe", "args":["swap/account:XRP-USD-SWAP"]}

swap/account is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters type Description
equity String Equity of the account (Dynamic benefits of an account)
instrument_id String Contract ID e.g.BTC-USD-SWAP
margin String Margin for open positions
margin_frozen String Initial margin on hold
margin_ratio String Margin Ratio
realized_pnl String Realized profits and losses
timestamp String Creat time
total_avail_balance String Balance of the account
unrealized_pnl String Unrealized profits and losses
fixed_balance String Balance of the account (Static benefits of an account)
margin_mode String Margin Mode: crossed/fixed
response examples

{
    "table": "swap/account",
    "data": [{
        "equity": "21.9334",
        "fixed_balance": "0.0000",
        "instrument_id": "XRP-USD-SWAP",
        "margin": "6.8129",
        "margin_frozen": "6.8143",
        "margin_mode": "crossed",
        "margin_ratio": "0.3219",
        "realized_pnl": "0.0000",
        "timestamp": "2019-05-06T07:12:25.677Z",
        "total_avail_balance": "22.0043",
        "unrealized_pnl": "-0.0710"
    }]
}

User Orders

Get user's order information , require login

send examples
{"op": "subscribe", "args":["swap/order:XRP-USD-SWAP"]}

swap/order is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
size String Quantity
timestamp String Creation time
filled_qty String Filled quantity
fee String Fees
order_id String Order price
client_oid String the order ID customized by yourself
price String Order price
price_avg String Average price
type String 1:open long 2:open short 3:close long 4:close short
contract_val String Contract value
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
last_fill_px String Last transaction price (if none, push 0))
last_fill_qty String Last transaction amount (if none, push 0)
last_fill_time String Last transaction time (if none, push 0)
state String Order state("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling,)
Explanation

"status" is the older version of the "state" parameter and is compatible in the short term. It is recommended to switch to "state".

response examples

{
    "table": "swap/order",
    "data": [{
        "last_fill_time": "1970-01-01T00:00:00.000Z",
        "filled_qty": "0",
        "fee": "0.000000",
        "client_oid": "",
        "last_fill_qty": "0",
        "price_avg": "0.0000",
        "type": "2",
        "instrument_id": "XRP-USD-SWAP",
        "last_fill_px": "0",
        "size": "1",
        "price": "0.2935",
        "error_code": "0",
        "contract_val": "10",
        "state": "0",
        "order_id": "6c-a-625f6f638-0",
        "order_type": "0",
        "state": "0",
        "timestamp": "2019-05-06T07:12:25.679Z"
    }]
}

User Algo Orders

Users must login to obtain trading data.

Send – example:

{"op": "subscribe", "args": ["swap/order_algo:LTC-USDT-SWAP"]}

Of which “swap/order_algo” is the channel name and “LTC-USDT-SWAP” is the instrument_id

Return Parameters

Parameter Type Description
algo_id string Order ID
order_type string 1. Trigger order; 2. Trail order; 3. Iceberg order; 4. Time-weighted average price (TWAP)
leverage String Leverage
size string Order size
instrument_id string Token
type String Order type (1. Open long; 2. Open short; 3. Close long; 4. Close short)
timestamp string Order time
status string Order status: 1. Pending; 2. Effective; 3. Canceled; 4. Partially effective; 5. Paused; 6. Failed [Status 4 and 5 only applies to iceberg and TWAP orders]

Trigger Orders

Parameters Type Description
algo_price string Order price
trigger_price string Trigger price
real_amount String Actual order amount

Trail Orders

Parameters Type Description
callback_rate string Callback rate
trigger_price string Trigger price
real_amount String Actual order amount

Iceberg Orders

Parameters Type Description
algo_variance string Order depth
avg_amount string Single order average price
price_limit string Price limit
deal_value string Order amount
返回示例
{

    "instrument_id":"BTC-USD-SWAP",
    "order_type":"1",
    "algo_id":"2517062038154240"    
    "timestamp":"2019-03-25T03:45:17.376Z"
    "rejected_at":"2019-03-26T03:45:17.376Z"
    "status":"2"    
    "type":"3"   
    "leverage":"20"   
    "trigger_price":"2"   
    "algo_price":"2"   
    "size":"2000"  
    "real_amount":"1000"   

}

Public-Ticker

To capture the latest traded price, best-bid price, best-ask price, and 24-hour trading volume of all perpetual swap contracts on the platform.

send examples:
{"op": "subscribe", "args":["swap/ticker:BTC-USD-SWAP"]}

swap/ticker is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters types Description
instrument_id String Contract ID,e.g .BTC-USD-SWAP
best_bid String best bid
best_ask String best ask
last String Last traded price
high_24h String 24 hour high
low_24h String 24 hour low
volume_24h String 24 hour trading volume (contracts)
timestamp String timestamp
open_interest string holding volume
open_24h string 24-hour open price
volume_token_24h String 24 hour trading volume (token)
response examples

{
    "table": "swap/ticker",
    "data": [{
        "best_ask": "5603.5",
        "best_bid": "5600.1",
        "high_24h": "5773.7",
        "instrument_id": "BTC-USD-SWAP",
        "last": "5603.3",
        "low_24h": "5566",
        "timestamp": "2019-05-06T06:45:56.716Z",
        "volume_24h": "1538076"
    }]
}

Public-Candlesticks

Kline information for swap business

channel lists:

swap/candle60s // 1mins kline channel

swap/candle180s // 3mins kline channel

swap/candle300s // 5mins kline channel

swap/candle900s // 15mins kline channel

swap/candle1800s // 30mins kline channel

swap/candle3600s // 1hour kline channel

swap/candle7200s // 2hour kline channel

swap/candle14400s // 4hour kline channel

swap/candle21600 // 6hour kline channel

swap/candle43200s // 12hour kline channel

swap/candle86400s // 1day kline channel

swap/candle604800s // 1week kline channel

send examples
{"op": "subscribe", "args":["swap/candle60s:BTC-USD-SWAP"]}

swap/candle60s is channel name,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Types Description
timestamp String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
currency_volume String The trading volume in a specific token
instrument_id String Contract ID e.g.BTC-USD-SWAP
response examples


{
    "table": "swap/candle60s",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "candle": ["2019-05-06T06:51:00.000Z", "5613", "5613", "5611.9", "5611.9", "1218", "21.7009"]
    }]
}

Public-Trade

Get the filled orders data

send examples
{"op": "subscribe", “args":["swap/trade:BTC-USD-SWAP"]}

swap/trade is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Types Description
trade_id String Transaction id
price String Filled price
size String Filled size
side String Filled side (buy/sell)
timestamp String Filled time
instrument_id String Contract ID, e.g. BTC-USD-SWAP
response examples



{
    "table": "swap/trade",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "price": "5611.9",
        "side": "buy",
        "size": "2",
        "timestamp": "2019-05-06T06:51:24.389Z",
        "trade_id": "227897880202387456"
    }]}

Public-Funding Rate

Get the funding rate information

send examples
{"op": "subscribe", "args":["swap/funding_rate:BTC-USD-SWAP"]}

swap/funding_rate is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Types Description
interest_rate String interest rate
instrument_id String Contract ID , eg: BTC-USD-SWAP
funding_time String Current funding time
funding_rate String Current funding rate
estimated_rate String next estimated funding rate
response examples


{
    "table": "swap/funding_rate",
    "data": [{
        "funding_rate": "-0.00067",
        "estimated_rate": "-0.00067809",
        "funding_time": "2019-05-06T14:00:00.000Z",
        "instrument_id": "BTC-USD-SWAP",
        "interest_rate": "0"
    }]
}

Public-Price Range

The maximum buying price and the minimum selling price of the contract.

send examples
{"op": "subscribe", "args":["swap/price_range:BTC-USD-SWAP"]}

swap/price_range is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Types Description
timestamp String timestamp
lowest String Minimum buying price
instrument_id String Contract ID, e.g. BTC-USD-SWAP
highest String Maximum buying price
response examples

{
    "table": "swap/price_range",
    "data": [{
        "highest": "5665.9",
        "instrument_id": "BTC-USD-SWAP",
        "lowest": "5553.6",
        "timestamp": "2019-05-06T06:51:20.012Z"
    }]
}

Public-Depth5

The latest 5 entries of the market depth data is snapshooted and pushed every 100 milliseconds.

send examples
{"op": "subscribe", "args":["swap/depth5:BTC-USD-SWAP"]}

swap/depth5 is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Types Description
asks String Selling side
bids String Buying side
timestamp String System time stamp
instrument_id String Contract ID,e.g .BTC-USD-SWAP

["411.8","6",8,4] [String,String,int,int]411.8 is the price, 6 is the size of the price, 8 is the number of force-liquidated orders, 4 is the number of orders of the price,timestamp is the timestamp of the order book.

response examples


{
    "table": "swap/depth5",
    "data": [{
        "asks": [
            ["5621.7", "58", “0”, “2”],
            ["5621.8", "125", “0”, “5”],
            ["5622", "84", “0”, “2”],
            ["5622.5", "6", “0”, “1”],
            ["5623", "1", “0”, “1”]
        ],
        "bids": [
            ["5621.3", "287", “0”, ”8”],
            ["5621.2", "41", “0”, “1”],
            ["5621.1", "2", “0”, “1”],
            ["5621", "26", “0”, “2”],
            ["5620.9", "640", “0”, “1”]
        ],
        "instrument_id": "BTC-USD-SWAP",
        "timestamp": "2019-05-06T07:03:33.048Z"
    }]
}

Public-Depth

The 200 entries of market depth data of the order book that return for the first time after subscription will be pushed. Then for every 100 milliseconds, we will snapshot and push entries that have been changed during this time.

send examples

{"op": "subscribe", "args":["swap/depth:BTC-USD-SWAP"]}

swap/depth is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Types Description
asks String Selling side
bids String Buying side
timestamp String System timestamp
instrument_id String Contract ID,e.g .BTC-USD-SWAP
checksum String checksum

["411.8","6",8,4] 411.8 is the price, 6 is the size of the price, 8 is the number of force-liquidated orders, 4 is the number of orders of the price,timestamp is the timestamp of the order book.

response examples
 First 200 entries 

{
    "table": "swap/depth",
    "action": "update",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "asks": [
            ["5621.7", "58", "0", "2"],
            ["5621.8", "125", "0", "5"],
            ["5621.9", "0", "0", "0"],
            ["5622", "84", "0", "2"],
            ["5623.5", "0", "0", "0"],
            ["5624.2", "4", "0", "1"],
            ["5625.1", "0", "0", "0"],
            ["5625.9", "0", "0", "0"],
            ["5629.3", "2", "0", "1"],
            ["5650", "187", "0", "8"],
            ["5789", "1", "0", "1"]
        ],
        "bids": [
            ["5621.3", "287", "0", "8"],
            ["5621.2", "41", "0", "1"],
            ["5621.1", "2", "0", "1"],
            ["5621", "26", "0", "2"],
            ["5620.8", "194", "0", "2"],
            ["5620", "2", "0", "1"],
            ["5618.8", "204", "0", "2"],
            ["5618.4", "0", "0", "0"],
            ["5617.2", "2", "0", "1"],
            ["5609.9", "0", "0", "0"],
            ["5433", "0", "0", "0"],
            ["5430", "0", "0", "0"]
        ],
        "timestamp": "2019-05-06T07:03:33.048Z",
        "checksum": -186865074
    }]

Public-Mark Price

Get the mark price

send examples

{"op": "subscribe", "args":["swap/mark_price:BTC-USD-SWAP"]}

swap/mark_price is channel name ,BTC-USD-SWAP is instrument_id

response parameters
Parameters Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
mark_price String Mark Price
timestamp String Timestamp

In order to avoid price fluctuation of futures caused by market manipulation, we set the mark price based on the spot index and a reasonable basis.

response examples

{
    "table": "swap/mark_price",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "mark_price": "5620.9",
        "timestamp": "2019-05-06T07:03:33.799Z"
    }]
}

WS Public Index

websocket API public index channel

Ticker

This channel is a public index channel that includes the k-lines and tickers for indices. It can be taken reference to for futures and spot trading.

The indices currently available are all USD-denominated. The asset list includes: BTC, LTC, ETH, ETC, XRP, EOS, BTG.

Get the public index ticker data

send examples
{"op": "subscribe", "args": ["index/ticker:BTC-USD"]}

index/ticker is channel name ,BTC-USD is token index

response parameters
Parameters Parameters Description
instrument_id String e.g. BTC-USD
last String Last traded price
high_24h String 24 hour high
low_24h String 24 hour low
timestamp String timestamp
open_24h String 24 hour open
response examples
{"table":"index/ticker","data":[{"last":"3649.76","high_24h":"3955.4","low_24h":"10","instrument_id":"BTC-USD","open_24h":"3888.68","timestamp":"2018-11-27T10:01:23.341Z"}]}

Kline

Get the kline information

Channel list:

index/candle60s // 1mins kline channel

index/candle180s // 3mins kline channel

index/candle300s // 5mins kline channel

index/candle900s // 15mins kline channel

index/candle1800s // 30mins kline channel

index/candle3600s // 1hour kline channel

index/candle7200s // 2hour kline channel

index/candle14400s // 4hour kline channel

index/candle21600 // 6hour kline channel

index/candle43200s // 12hour kline channel

index/candle86400s // 1day kline channel

index/candle604800s // 1week kline channel

send examples
{"op": "subscribe", "args": ["index/candle60s:BTC-USD"]}

index/candle60s is channel name ,BTC-USD is token index

response parameters
Parameters Parameters Types Description
timestamp String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
currency_volume String The trading volume in a specific token
instrument_id String e.g.BTC-USD
response examples

{"table":"index/candle60s","data":[{"instrument_id":"BTC-USD","candle":["2018-11-27T10:01:23.341Z","3811.31","3811.31","3811.31","3811.31","0"]}]}

error code

error message format:

{"event”:”error”,” message”:” ",”errorCode”:”"}

Example
Description Code
Url pass error Url path error 30000
OK_ACCESS_KEY cannot be blank 30001
OK_ACCESS_SIGN cannot be blank 30002
OK_ACCESS_PASSPHRASE cannot be blank 30004
Invalid OK_ACCESS_TIMESTAMP 30005
Invalid OK_ACCESS_KEY 30006
Timestamp request expired 30008
Invalid sign 30013
Requested too frequent; endpoint limit exceeded 30026
Login failure 30027
Unrecognized request 30039
{0} Channel : {1} doesn't exist 30040
User not logged in / User must be logged in 30041
Already logged in 30042
Internal system error 30043

Change Log

【2019-4-28】

Spot trading order status fetch is not available.

Spot, margin, futures and perpetual swap

rest: Get Order List, Get All Open Orders, Get Order Details, Add Parameters state String Order Status("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling, "6": Incomplete (open + partially filled), "7":Complete (cancelled + fully filled) )

ws:order add parameters state String Order Status("-2":Failed,"-1":Cancelled,"0":Open,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling, )

【2019-04-26】

futures:The return parameters in the ticker channel, estimated_price channel,depth channel,depth5 channel,trade channel, and price_range channel of Futures websocket will be unified into the String type.

spot:The return parameters in the depth channel,depth5 channel,trade channel of spot websocket will be unified into the String type.

perpetual swap:The return parameters in the depth channel,depth5 channel of perpetual swap websocket will be unified into the String type.

【2019-04-24】

public error_code and error_message add:

30019 400 Api is offline or unavailable 30021 400 Json data format error 30022 401 Api has been frozen

【2019-04-12】

futures add:Setting up contract token account mode

【2019-01-21】

futures Modification: modified the return value format for kline endpoints

【2019-3-27】

For spot and margin trading, use client_oid to cancel multiple orders. The order cancelation function has been upgraded from 1 order per trading pairs to 10 orders per trading pairs. Request example after the launch: 2018-10-12T07:30:49.664ZPOST/api/spot/v3/cancel_batch_orders[{"instrument_id":"btc-usdt","client_oids”:[“A1600593327162368”,”A1600593327162369”]},{“instrument_id":"ltc-usdt","client_oids”:[“A243464”,”A234465”]}]

Spot, margin, futures and perpetual swap

New parameters added in web socket order channel: "last_fill_px”, ”last_fill_qty”, and “last_fill_time”

【2019-01-21】

Spot, margin, futures and perpetual swap Modification: modified the return value format for kline endpoints

Scheduled Updates

The following updates are scheduled to launch in Sep. Users please take necessary measures beforehand.

  1. Added “fee” in return data for spot and margin trading order API

Endpoint:

GET /api/spot/v3/orders/

GET /api/margin/v3/orders/

{"op": "subscribe", "args": ["spot/order:LTC-USDT"]}

Return Parameters

Parameters Parameters Types Description
fee String The transaction fees charged by the platform are shown in negative numbers, e.g. -0.01
rebate String The rewards that the platform offers to users for having reached a certain trading tier with order placement bonus (rebate) are shown in positive numbers, e.g. 0.5. “0” if no rebate available.
  1. Added “transferrable amount” for perpetual account details API and WS account details channel.

Endpoint:

GET /api/futures/v3/accounts/{currency}

GET /api/futures/v3/accounts,

{"op": "subscribe", "args": ["swap/account:BTC-USD-SWAP"]}

Return Parameters

Parameters Parameters Types Description
can_withdraw String Available transfer amount

3.The “id” of V3 spot account data API is disabled.

Endpoint:

GET /api/spot/v3/accounts/

GET /api/spot/v3/accounts

{"op": "subscribe", "args": ["spot/account:BTC"]}

返回参数

Parameters Parameters Types Description
id String User Id

4.Added “forced-liquidation” for obtaining all/single account data API for futures contracts.

Endpoint:

GET /api/futures/v3/accounts/

GET /api/futures/v3/accounts

Return Parameters

Parameters Parameters Types Description
liqui_fee_rate string forced-liquidation fee

5.Perpetual swap WebSocket ticker channel added “holding volume” and “24-hour open price”:

Endpoint:

{"op": "subscribe", "args": ["swap/ticker:BTC-USD-SWAP"]}

Return Parameters

Parameters Parameters Types Description
open_interest string holding volume
open_24h string 24-hour open price

6.1)restAPi: Perpetual swap open positions API GET /api/swap/v3//position GET /api/swap/v3/position

2)wsAPI: Perpetual swap open positions channel {"op": "subscribe", "args": ["swap/position:BTC-USD-SWAP"]}

3)rest: Obtaining perpetual swap order list (algo orders) GET /api/swap/v3/order_algo

Returned leverage: Previously it returned integers. Now it can return numbers with decimals. Previous leverage: “20", present leverage: ”20.00"

2019-08-31

  1. Added “withdraw_id” for request and return parameters

Endpoint:

GET /api/account/v3/withdrawal/history/

prarmeters:

Parameters Parameters Types Required Description
withdraw_id String No Withdrawal ID

Transfer currency only, return all withdrawal record of this trading pair.

Return the specified withdrawal record after sending currency and withdraw_id

Return Parameters

Parameters Parameters Types Description
withdraw_id String Withdrawal ID
  1. Request withdrawal record for all tokens. Added “withdraw_id” for return parameter.

Endpoint:

GET /api/account/v3/withdrawal/history

Return Parameters

Parameters Parameters Types Description
withdraw_id String Withdrawal ID
  1. The parameter “order_id” of spot, futures and perpetual swap APIs for obtaining transaction details is now optional.

Endpoint:

GET /api/spot/v3/fills,GET /api/futures/v3/fills,GET /api/swap/v3/fills

prarmeters:

Parameters Parameters Types Required Description
order_id String No Order ID
  1. For futures order placement, leverage request parameter (leverage) is now optional. The documentation is now unavailable.

Endpoint:

POST /api/futures/v3/order

POST /api/futures/v3/orders

prarmeters:

Parameters Parameters Types Required Description
leverage String No leverage
  1. Request parameter added “depth” for futures and perpetual swap depth API.

Endpoint:

GET /api/futures/v3/instruments//book

GET /api/swap/v3/instruments//depth

prarmeters:

Parameters Parameters Types Required Description
depth String No Aggregation of the order book. e.g . 0.1, 0.001
  1. Obtain forced-close details of futures through API

Endpoint:

GET /api/futures/v3/accounts//ledger

prarmeters:

Parameters Parameters Types Required Description
type String No 20.Partially-closed Short 21.Partially-closed Long
  1. Add “Realized profit of long/short positions” for futures single token holding API, all holding APIs, and WebSocket user holding channels.

Endpoint:

GET /api/futures/v3//position

GET /api/futures/v3/position

{"op": "subscribe", "args": ["futures/position:BTC-USD-170317"]}

Return Parameters

Parameters Parameters Types Description
long_settled_pnl String Realized profit of long positions
short_settled_pnl String Realized profit of short positions
  1. Add “Realized profit of positions” for swap single token holding API, all holding APIs, and WebSocket user holding channels.

Endpoint:

GET /api/swap/v3//position

GET /api/swap/v3/position

{"op": "subscribe", "args": ["swap/position:BTC-USD-SWAP"]}

Return Parameters

Parameters Parameters Types Description
settled_pnl String Realized profit of positions

9.API Adjustment of swap:

1) Restful: public-next perpetual swap settlement time capture endpoint

Endpoint:

GET /api/swap/v3/instruments//funding_time

Return Parameters

Parameters Parameters Types Description
funding_rate String current funding rate
estimated_rate String next estimated funding rate
settlement_time String settlement rate

2)Websocket:public-funding rate channel(swap/funding_rate)

Return Parameters

Parameters Parameters Types Description
estimated_rate String next estimated funding rate

3) The value of the current parameter funding_rate in V3 API will be changed from “funding rate” to “estimated funding rate”

2019-07-31

The following updates are scheduled to launch in July. Users please take necessary measures beforehand.

1、ftures and swap add parameter:Realized Profit of Positions

Endpoint:

GET /api/futures/v3/position

GET /api/futures/v3/<instrument_id>/position

ws-futures/position

GET /api/swap/v3/position

GET /api/swap/v3/<instrument_id>/position

ws-swap/position

具体接口:

POST /api/futures/v3/order

POST /api/futures/v3/orders

2019-06-30

The following updates are scheduled to launch in June. Users please take necessary measures beforehand.

1、Pagination

OKEx uses cursor pagination for some REST requests which return arrays.

Cursor pagination allows for fetching results before and after the current page of results and is well suited for realtime data. Endpoints like /trades, /fills, /orders, return the latest items by default. To retrieve more results subsequent requests should specify which direction to paginate based on the data previously returned.

before and after cursors are available via response headers OK-BEFORE and OK-AFTER. Your requests should use these cursor values when making requests for pages after the initial request.

EXAMPLE

GET /api/spot/v3/orders?before=2&limit=30

Parameters Parameters Types Required Description
after String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
before String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)

BEFORE AND AFTER CURSORS

The before cursor references the first item in a results page and the after cursor references the last item in a set of results.

The response will contain a OK-BEFORE header which will return the cursor id to use in your next request for the page before the current one. The page before is a newer page and not one that happened before in chronological time.

The response will also contain a OK-AFTER header which will return the cursor id to use in your next request for the page after this one. The page after is an older page and not one that happened after this one in chronological time.

Endpoint:

GET /api/futures/v3/accounts/<currency>/ledger

GET /api/futures/v3/orders/<instrument_id>

GET /api/futures/v3/fills

GET /api/futures/v3/instruments/<instrument_id>/trades

GET /api/spot/v3/orders_pending

GET /api/account/v3/ledger

GET /api/futures/v3/accounts/<currency>/ledger

GET /api/futures/v3/orders/<instrument_id>

GET /api/futures/v3/fills

GET /api/futures/v3/instruments/<instrument_id>/trades

GET /api/swap/v3/accounts/<instrument_id>/ledger

GET /api/swap/v3/orders/<instrument_id>

GET /api/swap/v3/fills

GET /api/swap/v3/instruments/<instrument_id>/trades

2、

When ‘from’ or ‘to’ is 0, sub account parameter is required.

When ‘from’ is 0, ‘to’ is only can be 6 (that is, the funding account of the sub-account can only be transferred to the funding account of the main account).

When ‘from’ or ‘to’ is 5, instrument_id is required.

"to" is specified to 1-9, and when "sub_account" is filled with a sub-account ID, user may transfer fund from the main account to the sub-account's corresponding spot or derivative account directly.

Request Sample

POST /api/account/v3/transfer

Request Parameters
Parameters Parameters Types Required Description
currency String Yes Token
amount String Yes Transfer amount
from String Yes the remitting account (0: sub account 1: spot 3: futures 4:C2C 5: margin 6: Funding Account 8:PiggyBank 9:swap)
to String Yes the beneficiary account(0: sub account 1:spot 3: futures 4:C2C 5: margin 6: Funding Account 8:PiggyBank 9 :swap)
sub_account String No sub account name
instrument_id String No Margin trading pair transferred out, for supported pairs only
to_instrument_id String No Margin trading pair transferred in, for supported pairs only
Return Parameters
Parameters Parameters Types Description
transfer_id String Transfer ID
currency String Token to be transferred
from String The remitting account
amount String Transfer amount
to String The beneficiary account
result Boolean Transfer result. An error code will be displayed if it failed.

2019-05-31

The following updates are scheduled to launch in May. Users please take necessary measures beforehand.

1.OKEx uses cursor pagination for all REST requests which return arrays. Cursor pagination allows for fetching results before and after the current page of results and is well suited for realtime data. Endpoints like /trades, /fills, /orders, return the latest items by default. To retrieve more results subsequent requests should specify which direction to paginate based on the data previously returned.

from and to cursors are available via response headers OK-FROM and OK-TO. Your requests should use these cursor values when making requests for pages after the initial request.

The from cursor references the first item in a results page and the after cursor references the last item in a set of results.

To request a page of records before the current one, use the before query parameter. Your initial request can omit this parameter to get the default first page.

Example

If the ID’s of the returned results are: 111, 112, 113, 114, 115, 116, 117, 118, 119, 120

Then they will be ordered in: 120, 119, 118, 117, 116, 115, 114, 113, 112, 111

The OK-FROM ID is now 120, and the OK-TO ID is now 111. If you want to access to updated data such as data after 120, then you will have to use the before parameters. For example: orders?before=120&limit=5 will return the 5 strings of data after 120, which is 125, 124, 123, 122, 121

prarmeters:

Parameters Parameters Types Required Description
from String No Request page before (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
to String No Request page after (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)

Endpoint:

GET /api/account/v3/ledger

GET /api/futures/v3/accounts//ledger

GET /api/futures/v3/orders/

GET /api/futures/v3/fills

GET /api/futures/v3/instruments//trades

GET /api/swap/v3/accounts//ledger

GET /api/swap/v3/orders/

GET /api/swap/v3/fills

GET /api/swap/v3/instruments//trades

  1. Add a channel for pushing full contract:When new contract is live, full contract data will be pushed once;
  1. [Functionality Optimization] The return parameter of billing statement request API of perpetual swap will include “details”, “currency”, and “balance” (to show statement types)

| currency | String | Token, “btc” | | details | String | If the type is generated by transaction, the "order_id" and "instrument_id" will be included in details | | balance | String |balance: String of contracts of open and closed positions (positive for open positions; negative for closed positions; when type is fee, balance is 0) |

Market involved: Perpetual Swap

API involved – REST API:

GET /api/swap/v3/accounts//ledger

  1. [Functionality Optimization] The return parameter of obtain order list and obtain order details of spot and margin trading will include average transaction price “price_avg”

| price_avg | String | Average price |

Markets involved: Token Trading, Spot Margin

API involved – REST API:

GET /api/spot/v3/orders

GET /api/spot/v3/orders/

GET /api/margin/v3/orders

GET /api/margin/v3/orders/

  1. [Functionality Optimization] The request and return parameters of spot and margin trading, futures, and perpetual swap will include user ID “client_oid” parameter. “order_id” will be optional. Users can obtain all trading details of the current trading pair.

| client_oid | String | No | the order ID customized by yourself , The client_oid type should be comprised of alphabets + Strings or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported | | order_id | String | No |Order ID. If order placement fails, this value will be -1. |

Markets involved: Spot, margin, futures, perpetual swap

API involved – REST API:

GET /api/spot/v3/fills

GET /api/margin/v3/fills

GET /api/futures/v3/fills

GET /api/swap/v3/fills

  1. [Functionality Optimization] Bulk order placement API of spot trading, margin trading, futures, and perpetual swap

a) For spot and margin trading bulk order placement return, the underscore “_” in trading pairs will be changed to hyphen “-“ ; For example: "btc_usdt" will be changed to ”btc-usdt".

b) When spot and margin trading bulk order placement return shows “error_code 33017”, or futures and perpetual swap bulk order placement return shows “error_code 32015”, the http status code should return to “400“;

c) When placing multiple orders and only some of the orders show insufficient balance error, http status code should also be “400“.

Markets involved: Spot, margin, futures, perpetual swap

API involved – REST API:

POST/api/spot/v3/batch_orders

POST/api/margin/v3/batch_orders

POST/api/futures/v3/batch_orders

POST/api/swap/v3/batch_orders

7.[Functionality Optimization] The billing statement API request parameter of spot trading, futures, and perpetual swap will include statement type “type”

Markets involved: Spot, futures, perpetual swap

API involved – REST API:

GET /api/spot/v3/accounts//ledger

GET /api/futures/v3/accounts//ledger

GET /api/swap/v3/accounts//ledger

V1 API Update--For Tiered Margin Upgrade on Futures

Updated on: 08:00 May 15, 2019 (CET, UTC+1)

Updates:

Push

1)ok_sub_futureusd_positions Futures position data channel

a. Fixed-margin Mode Return Format Update:

Before Update: long and short directions, return 10x and 20x leverage open position information, push 0 if no data;

After Update: long and short directions, return n times and m times leverage open position information; push 0 if no data;

Old format before update:

[
    {
        "binary":0,
        "channel":"ok_sub_futureusd_positions",
        "data":{
            "symbol":"eos_usd",
            "user_id":7669455,
            "positions":[
                {
                    "lever_rate":10,
                    "avgprice":4.849,
                    "contract_id":201906280200053,
                    "hold_amount":1,
                    "contract_name":"EOS0628",
                    "costprice":4.849,
                    "forcedprice":4.44862378,
                    "bondfreez":0,
                    "eveningup":1,
                    "fixmargin":0.20622809,
                    "balance":0.20684677,
                    "position":1,
                    "profitreal":-0.00061868,
                    "position_id":2517385395344384
                },
                {
                    "lever_rate":10,
                    "avgprice":0,
                    "contract_id":201906280200053,
                    "hold_amount":0,
                    "contract_name":"EOS0628",
                    "costprice":0,
                    "forcedprice":0,
                    "bondfreez":0,
                    "eveningup":0,
                    "fixmargin":0,
                    "balance":0.20684677,
                    "position":2,
                    "profitreal":-0.00061868,
                    "position_id":2517385395344384
                },
                {
                    "lever_rate":20,
                    "avgprice":0,
                    "contract_id":201906280200053,
                    "hold_amount":0,
                    "contract_name":"EOS0628",
                    "costprice":0,
                    "forcedprice":0,
                    "bondfreez":0,
                    "eveningup":0,
                    "fixmargin":0,
                    "balance":0.20684677,
                    "position":1,
                    "profitreal":-0.00061868,
                    "position_id":2517385395344384
                },
                {
                    "lever_rate":20,
                    "avgprice":5.423,
                    "contract_id":201906280200053,
                    "hold_amount":0,
                    "contract_name":"EOS0628",
                    "costprice":5.423,
                    "forcedprice":0,
                    "bondfreez":0,
                    "eveningup":0,
                    "fixmargin":0,
                    "balance":0.20684677,
                    "position":2,
                    "profitreal":-0.00061868,
                    "position_id":2517385395344384
                }
            ]
        }
    }
]

New format after update:

[
    {
        "binary":0,
        "channel":"ok_sub_futureusd_positions",
        "data":{
    "symbol":"etc_usd",
    "user_id":36203808,
    "positions":[
        {
            "lever_rate":5,
            "avgprice":56.89655172,
            "contract_id":20170310446,
            "hold_amount":10,
            "contract_name":"ETC0310",
            "costprice":56.89655172,
            "forcedprice":52.5,
            "bondfreez":0,
            "eveningup":5,
            "fixmargin":0.17575758,
            "balance":0.2067697,
            "position":1,
            "longMaintainenceRatio":"0.015",
            "profitreal":-0.00070909,
            "position_id":2778972475169792
        },
        {
            "lever_rate":25,
            "avgprice":33,
            "contract_id":20170310446,
            "hold_amount":2,
            "contract_name":"ETC0310",
            "costprice":33,
            "forcedprice":34.2157,
            "bondfreez":0,
            "eveningup":1,
            "fixmargin":0.03030303,
            "balance":0.2067697,
            "shortMaintainenceRatio":"0.015",
            "position":2,
            "profitreal":-0.00070909,
            "position_id":2778972475169792
        }
    ]
}

b. New Return Parameters:

Fixed-margin Mode

|longMaintainenceRatio |String |Maintenance Margin Ratio for Long Position |

|shortMaintainenceRatio |String | Maintenance Margin Ratio for Short Position |

2)ok_sub_futureusd_userinfo Futures Account Information Channel

New Return Parameters:

Fixed-margin Mode

| bannerFrozen |String |Frozen |

Cross-margin Mode

|bannerFrozen |String |Frozen |

| maintainenceRatio |String |Maintenance Margin Ratio |

2019-05-15

  1. Liquidation Mode Settings

You can choose the liquidation mode for futures trading. Please note that you would not be able to switch between the modes if you have any open position.

Speed Limit: 5 times / 2s

HTTP Request

POST /api/futures/v3/accounts/liqui_mode

Request Sample

POST /api/futures/v3/accounts/liqui_mode{"currency":"btc","liqui_mode":"tier"}

Request Parameters
Parameters Parameters Types Required Description
currency String Yes token
liqui_mode string Yes Liquidation mode: tier (partial), legacy(full)
Return Parameters
Parameters Parameters Types Description
liqui_mode string Liquidation mode: tier (partial), legacy(full)
currency String token
result String result, Error message will be returned if the setting failed.
  1. Cross-margin Mode: Added API to get:

a.maintenance margin ratio

b.current liquidation mode

Fixed Margin Mode: Added API to get current liquidation mode.

Account information for all tokens (same for single token)

The processing time for getting futures account information of all tokens can be long. You are recommended to get the information separately by choosing one token at a time.

Speed Limit: 1 time /10s

HTTP Requests

GET /api/futures/v3/accounts

Request Sample

GET/api/futures/v3/accounts

Return Parameters

Cross-margin Mode

Parameters Parameters Types Description
maint_margin_ratio String Maintenance Margin Ratio
liqui_mode string Liquidation mode: tier(partial), legacy(full)

Fixed Margin Mode

Parameters Parameters Types Description
liqui_mode string Liquidation mode: tier(partial), legacy(full)
  1. Position Information

Cross-margin Mode: margin, profit, profit rate, unrealized profits and losses

Fixed Margin Mode: margin ratio, maintenance margin ratio, profit, unrealized profits and losses

Futures Position Information

The processing time for getting futures account information of all tokens can be long. You are recommended to get the information separately by choosing one token at a time.

Speed Limit: 5 times /2s

HTTP Requests

GET /api/futures/v3/position

Request Sample

GET/api/futures/v3/position

Return Parameters

Cross-margin Mode

Parameters Parameters Types Description
short_margin String Margin for short positions
short_pnl String Profit of short positions
short_pnl_ratio String Profit rate of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
long_margin String Margin for long positions
long_pnl String Profit of long positions
long_pnl_ratio String Profit rate of long positions
long_unrealised_pnl String Unrealized profits and losses of long positions

Fixed Margin Mode

Parameters Parameters Types Description
short_margin_ratio String Margin ratio of short positions
short_maint_margin_ratio String Maintenance margin ratio of short positions
short_pnl String Profit of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
long_margin_ratio String Margin ratio of long positions
long_maint_margin_ratio String Maintenance margin ratio of long positions
long_pnl String Profit of long positions
long_unrealised_pnl String Unrealized profits and losses of long positions
  1. Leverage (1-100x; adjustable for open positions)

Set the leverage level for futures contracts

Set the leverage level for futures account. You will not be able to adjust the leverage level if you have any open orders.

Speed Limit: 5 times /2s

HTTP Requests

POST /api/futures/v3/accounts//leverage

Request Sample

POST/api/futures/v3/accounts/btc/leverage{"leverage":"10"}(cross-margin mode sample)

POST/api/futures/v3/accounts/btc/leverage{"instrument_id":"BTC-USD-180213","direction":"long","leverage":"10"}(fixed margin mode sample)

Request Parameters

Cross-margin Mode

Parameters Parameters Types Required Description
leverage Number Yes 1-100x
currency String Yes Token. E.g. BTC

Fixed Margin Mode

Parameters Parameters Types Required Description
currency String Yes Token. E.g. BTC
instrument_id String Yes Contract ID. E.g. BTC-USD-180213
direction String Yes Side (long or short)
leverage Number Yes 1-100x

Error message:

32040: (error message:“EOS-USD-180213") You have open positions or orders.

32060: Insufficient margin. Unable to adjust leverage.

WEBSOCKET:

1.Account channel

Cross-margin Mode: Added API to get:

a.maintenance margin ratio

b.current liquidation mode

Fixed Margin Mode: Added API to get current liquidation mode.

Get the user's account information (Login required)

Example:

{"op": "subscribe", "args":["futures/account:EOS"]}

futures/account is channel name ,BTC is token

Response Parameters

Parameters Parameters Types Description
maint_margin_ratio String Maintenance Margin Ratio
liqui_mode string Liquidation Mode: tier(partial), legacy(full)
Parameters Parameters Types Description
liqui_mode string Liquidation Mode: tier(partial), legacy(full)
  1. Position Information Channel

Cross-margin Mode: margin, profit, profit rate, unrealized profits and losses

Fixed Margin Mode: margin ratio, maintenance margin ratio, profit, unrealized profits and losses

send examples

{"op": "subscribe", "args":["futures/position:EOS-USD-190628"]}

futures/position is channel name ,BTC-USD-170317 is instrument_id

response parameters:

Cross-margin Mode

Parameters Parameters Types Description
short_margin String Margin for short positions
short_pnl String Profit of short positions
short_pnl_ratio String Profit ratio of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
long_margin String Margin for long positions
long_pnl String Profit of long positions
long_pnl_ratio String Profit ratio of long positions
long_unrealised_pnl String Unrealized profits and losses of long positions

Fixed Margin Mode

Parameters Parameters Types Description
short_margin_ratio String Margin ratio of short positions
short_maint_margin_ratio String Maintenance margin ratio of short positions
short_pnl String Profit of short positions
short_unrealised_pnl String Unrealized profits and losses of short positions
long_margin_ratio String Margin ratio of long positions
long_maint_margin_ratio String Maintenance margin ratio of long positions
long_pnl String Profit of long positions
long_unrealised_pnl String Unrealized profits and losses of long positions

2019-04-28

【2019-4-28】 Change 1

【Feature disabled】The multi-state query function for spot market has been disabled. Multi-state query will no longer be supported.

Involved markets: Spot

Involved API: Rest API GET/api/spot/v3/orders

Change 2

【Functionality Improvement】: New parameter “state” added (indicating order status) to unify the order status definitions in spot, margin, futures, and perpetual swap markets.

Description: "state" is the newly added field functions equivalently to the existing "status" field. The "status" and "state" parameters are compatible in the short term. It is recommended to switch to "state" as soon as possible. An announcement will be made prior to the disablement of "status". "state" state set description: "-2": failure, "-1": Order canceled successfully, "0": Pending for fulfilment, "1": Partially fulfilled, "2": Fully fulfilled, "3": Placing order , "4": Canceling order, "6": Incomplete (Pending for fulfilment + partial fulfilment), "7": Complete (Order canceled + full fulfilment)

Involved markets: Spot, margin, futures, perpetual swap

Involved rest API:

GET /api/spot/v3/orders;

GET /api/spot/v3/orders_pending;

GET /api/spot/v3/orders/

GET /api/margin/v3/orders;

GET /api/margin/v3/orders/

GET /api/margin/v3/orders_pending;

GET /api/futures/v3/orders/

GET /api/futures/v3/orders//

GET /api/swap/v3/orders/

GET /api/swap/v3/orders//

Involved WS API:

spot/order

futures/order

swap/order

2019-04-26

【Functionality Improvement】: The data types of all API return parameters (except for Boolean) are all unified to "String" type.

Involved markets: Spot, margin, futures, perpetual swap

Involved API: There are many APIs involved. It is recommended that users run a check on all APIs, both REST and WS.

2019-04-24

【New API added】3 public error code added

Involved markets: Spot, margin, futures, perpetual swap

Details of the 3 new error codes are as follows:

Error Message Error Codes http Status Code
Api is offline or unavailable 30019 400
Json data format error 30021 400
Api has been frozen 30022 400

2019-04-12

【New API added】Perpetual swap added: Perpetual swap account mode setting API

Involved market: Perpetual swap

Involved API: POST /api/futures/v3/accounts/margin_mode

For setting perpetual swap account mode. Accounts with open positions or open orders are not allowed to change mode.

Limit: 5 times / 2s
HTTP Requests

POST /api/futures/v3/accounts/margin_mode

Request Sample

POST /api/futures/v3/accounts/margin_mode{"currency":"btc","margin_mode":"crossed"}

Request Parameters
Parameters Parameters Types Required Description
currency String Yes Asset type, e.g. btc
margin_mode String Yes Margin mode: cross / fixed
Return Parameters
Parameters Parameters Types Description
currency String Asset type, e.g. btc
margin_mode String Margin mode: cross / fixed
result String Return to pre-set result
error_code String Error code for order placement. Success = 0. Failure = error code
error_message String It will be blank if order placement is success. Error message will be returned if order placement fails.
Return Sample

{
    "result":true,
    "error_message":"",
    "error_code":"0",
    "currency":"btc",
    "margin_mode":"crossed"
}

2019-03-27

Change 1

【Improvement】: client_oid can be used for bulk order cancelation, changing from one order per trading pair to 10 orders per trading pair.

Involved markets: Spot, margin

Involved REST API:

POST /api/spot/v3/cancel_batch_orders

POST /api/margin/v3/cancel_batch_orders

Change 2

【Improvement】: "Latest Trading Price", "Latest Trading Volume", "Latest Trading Time" are added to the return parameters of websocket order channel.

| last_fill_px | String | Latest Trading Price (If none, display 0) | | last_fill_qty | String | Latest Trading Volume (If none, display 0) | | last_fill_time | String | Latest Trading Time (If none, display 1970-01-01T00:00:00.000Z) |

Involved markets: Spot, margin, futures, perpetual swap

Involved REST API:

swap/order

futures/order

spot/order

2019-01-21

【Improvement】: K chart API return format is unified into an array 【Time, Open, High, Low, Close, Transaction Volume】.

Involved markets: Spot, margin, futures, perpeptual swap

Involved REST APIs:

GET /api/spot/v3/instruments//candles

GET /api/futures/v3/instruments//candles

GET /api/swap/v3/instruments//candles

Involved WS APIs:

swap/candle

futures/candle

spot/candle

FAQ


 1、How do I withdraw tokens from my sub account to an external address?

First, transfer your tokens to your sub account’s Funding Account, you can then transfer them to your main account Funding Account through the fund transfer port and withdraw your tokens there.

2、Is there any limit on the numbers of API order cancellation?

There are no limitations.

3、How did Http status code 429 happen?

Your visit frequency is too high. Please lower the frequency.

4、My API v3 account generated a new key. Do I have to use API v3 to send requests?

Yes, v1 and v3 are independent APIs. You must use a V1 key for a v1 API and v3 key for v3 API.

5、Why I cannot check on order details using the order ID returned from a canceled order?

Only the history of the canceled unfulfilled orders in the last 2 hours are kept in our system.

6、Can I use v3 key with okex.me?

The API address on our documents has always been “www.okex.com”. The domain name “www.okex.me” was only created to allow mainland Chinese users to access our website without VPN. There are no contradictions in the two addresses. Please fill in your request address according to our documents.

7、Can I use the API of the main account to check the balance of my sub account?


No, main accounts and sub accounts use independent APIs.

8、How many API keys can I apply for an account?

50.

9、How many entries of historical data can the K charts API obtain?

The K charts API can only obtain the most recent 2,000 entries of data.

10、Can I change the leverage level of my perpetual swap and futures contracts through API?

Yes, you can.

11、Are the return data different when using different keys in the same account?

The data is the same as they point at the same account.


12、What is the order unit when using v3 to make an order?

The order unit is 1, or multiples of 1.

13、Do I have to fill in my IP address when creating an API v3 key?

No, it’s not mandatory to enter your IP address, but we suggest you do so to make your account more secure.

14、Can I trade on C2C market with API v3?

No, API is not supported in our C2C market.


15、Can I increase margin with v3 API?

No, you can only do so on the website.


16、What is the WSS address for OKEx perpetual swap?

wss://real.okex.com:8443/ws/v3

17、Will my IP address be banned if the API exceeds the visit frequency? How long will it be banned?

No, you won’t be banned. You only have to lower your visit frequency.

18、Why did my API timeout?

Your network has timeout. Please check your network and use the Hong Kong Alibaba Cloud server instead.

19、What is the OKEx API visit frequency limit based on?

The limit for public data is based on IP, and that for individual data is based on User ID.

Questions And Feedback

If you have any questions or suggestions regarding our API, you are more than welcome to give us feedback via this link: (please indicate API v3). We will respond as soon as possible.

results matching ""

    No results matching ""