README


Welcome to OKEx developer documentation. Please note that the current version of this document is v3 and it will be updated regularly. Traders are advised to check this document from time to time for latest updates.

OKEx offers powerful APIs for you to tailor to your needs with different permissions. There are three categories: account, trading, and market trends. After creating an account on OKEx, developers can create APIs of different permissions according to their needs and perform automated trading as well as withdrawal. Our API trading permissions enable you to instantly capture market trends and trade, check available and locked balance, view pending orders, buy, sell, and cancel orders. All market data endpoints are public.

Instructions

If a developer would like to request the API, please subscribe to our v3 API key via this link. API trading instructions and settings are all included in this document. Should you encounter any problems during your use of the API or have any suggestions for improvement, please feel free to contact us.

Endpoints Configurations

OKEx offers two types of endpoints, developers may select either one to suit their needs of viewing market data, trading, or withdrawal. Refer to SDK(Please see here for details)

REST API

REST, Representational State Transfer, is one of the most used architectural style 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 kind of resource;
  • The representational state of transferring the resource between client and server;
  • Actualization of REST by using 4 HTTP instructions from the client to operate the resources in the server. We highly recommend developers to use REST API to perform spot trading and withdrawal.
WebSocket API

WebSocket is a new Protocol of HTML5. It achieved full-duplex data transmission between the client and the server, allowing data to transmit effectively in both directions. Through only one simple handshake, the connection between the client and the server is established, and the server can push information to the client according to the 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;
  • Avoided the multiple-creation and killing of TCP request, saving network and server resources. We highly recommend developers to use REST API to perform spot trading and withdrawal.
Contact

Please feel free to join our API community on Telegram (https://t.me/okexofficial_en). Our tech experts will help to answer all your questions and you can share your experiences with all other users.

API Summarize

Market overview and general information.

Matching Engine

This chapter explains the matching engine in the following four aspects:

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

Filled Price

OKEx’s matching engine operates at a first-come, first-serve basis. Orders are executed in price-time priority as received by the matching engine.

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

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

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

Order Life Cycle

Valid orders sent to the matching engine are in "unfilled" state. If the order executes against another order, it is considered "filled". An order can be "partially filled" and stays in the orders matching queue. If an open order is recalled, it is considered "cancelled". All cancelled or filled orders will be removed from the matching queue.

Token Trading Price Limit Rules

A new Fill-or-kill feature is now available in spot token trading. It is designed to prevent execution errors which may lead to unnecessary loss when placing orders.

Should an order would be filled, regardless its filled quantity, at the price of ±30% from best bid & offer by the time it executed in the order book, the order would be entirely cancelled. Otherwise, the order would be executed and matched normally.

Example A user placed a market order to buy 100BTC in XRP/BTC. The best offer price at that time is 0.00012. If the order does entirely execute in the market, the market price would be driven up to 0.0002. Based of the calculation (0.0002-0.00012)/0.00012=66.7%>30%), the potential filled price would be deviated >30% from the current best offer. Therefore, the system would cancel the mentioned market order entirely.

Futures Trading Price Limit Rules

Mark price is designed to safeguard users from unnecessary liquidation triggered by large and deliberate market manipulation. Without mark price, some of the traders may be able to use a small amount of funds but high leverage level to manipulate the futures market price. However, the mark price must be constructed carefully to maintain a vibrant futures market, differentiating itself from the spot market. Unfortunately, for the sake of better risk management, we cannot disclose the details of the mark price rules. Generally speaking, we will consider the market's trading volume, open interest, and a lot more parameters to calculate the risks and construct the mark price, at the same time without sacrificing the smooth trading experience of our users.

These rules apply to all contract in futures trading. First 10mins of all newly listed futures: Upper limit = Index price (1+5%) Lower limit = Index price (1-5%) Newly listed futures price limit after 10min: Upper limit = Avg. premium (or discount) within last 10 min + index price(1+3%) Lower limit = Avg. premium (or discount) within last 10 min + index price(1-3%) Premium (or discount) = Contract price - index price If the calculated upper limit is below 0 or deviates from the index price larger than 25%:

Upper limit=index price*(1+25%)

If the calculated lower limit is below 0 or deviates from the index price larger than 25%:

Lower limit=index price*(1-25%) Open Position: Order would be blocked in case of opening a long position should the order price sent is higher than the upper limit. Order would be blocked in case of opening a short position should the order price sent is lower than the lower limit. Close position: To prevent manipulative actions based on irresponsible behaviors, when closing a long position, if the order price is lower than the lower limit, the order cannot be placed; when closing a short position, if the order price is higher than the upper limit, the order cannot be placed.

Fees

This chapter explains the fee details in the following two aspects:

  • Trading Fees
  • Deposit/Withdrawal Fees

Trading Fees

To encourage more order placement and liquidity, OKEx adopts a marker-taker fee schedule, which the maker fee is lower than the taker fee. The fee schedule is volume-based, to be eligible for a tier, you are required to meet the minimum trading volume requirements. The higher the tier you are in, the lower the fees you can enjoy. Aside from tiered-volume fees discount, our 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 OKEx and OKCoin.

Data Centers

The database and servers of OKEx are based in Hong Kong. To lower the API latency, we suggest you to use an ISP that can communicate smoothly with Hong Kong.

Request

This chapter explains the request details in the following three aspects:

  • Introduction
  • Errors
  • Success

Introduction

REST API provides account management, market data, and transactions features. REST API Terminal URL https://www.okex.com/api We also provide WebSocket-stream. Subscribe to our WebSocket and you can get our market data push.

All requested are based on https protocol. Please set the contentType of the request message to: “application/json”

Errors

Unless otherwise stated, errors to bad requests will respond with HTTP 4xx or status codes. The body will also contain a message parameter indicating the cause. Your language’s 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 contain an optional body. If the response has a body it will be documented under each resource below.

Pagination

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 real time 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-BEFORE and OK-AFTER. 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 from query parameter. Your initial request can omit this parameter to get the default first page.

The response will contain a OK-FROM 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-To 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.

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?from=120&limit=5 will return the 5 strings of data after 120, which is 125, 124, 123, 122, 121

Parameters
Parameters Description
from Request page from (newer) this pagination id.(Example: 1,2,3,4,5. From 4 we only have 5, to 4 we have 1,2,3)
to Request page to (older) this pagination id.
limit Number of results per request. Maximum 100. (default 100)
Example

GET /orders?from=2&limit=30

Rules

This chapter explains the standard specifications in the following three aspects:

  • Timestamps
  • Numbers
  • IDs

Timestamps

Unless otherwise specified, all timestamps from API are returned in ISO 8601 with millisecond. Make sure you can parse the following ISO 8601 format. 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 platforms. When making a request, it is recommended that you also convert your numbers to strings to avoid truncation and precision errors.

Integer numbers (like trade id and sequence) are unquoted.

IDs

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

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

Endpoints

This chapter explains the details of endpoint types in the following two aspects:

  • Public Endpoints
  • Private Endpoints

Public Endpoints

Public APIs are available for acquiring information and market data. Public requests do not require any verifications.

Private Endpoints

Private endpoints are available for order management, and account management. Every private request must be signed using the described authentication scheme.

Private endpoints require authentication using your API key. You can generate API keys.

Rate Limits

This chapter explains the details of access restriction in the following two aspects:

  • REST API
  • WebSocket

When a rate limit is exceeded, a status of ‘429: Too Many Requests’ will be returned.

REST API

We use user id for rate limiting if you have a valid API key. If not, we use the public IP for rate limiting.

Rate limit: Each interface on the separate instructions, if there is no general interface of speed for 6 times per second.

WebSocket

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

Authentication

This chapter explains the details of authentication in the following five aspects:

  • Generating an API Key
  • Creating a Request
  • Signing a Message
  • Timestamp
  • Getting Server Time

Generating an API Key

Before being able to sign any requests, you must create an API key via the OKEx website. 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 verification, but cannot recover the passphrase if you forget it.

Creating a Request

All 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 a Message).

OK-ACCESS-TIMESTAMP A timestamp for your request.

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

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

Signing a Message

The OK-ACCESS-SIGN header is generated by creating a sha256 HMAC using the base64-decoded secret key on the prehash string timestamp + method + requestPath + body (where + represents string concatenation), secretKey and base64-encode the output. For 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 and nanometer precision.

The method should be UPPER CASE, like GET/POST.

requestPath is the path of requesting an endpoint, such as:/orders?before=2&limit=30.

The body is the request body string or omitted if there is no request body (typically for GET requests). For example:{"product_id":"BTC-USD-0309","order_id":"377454671037440"}

secretKey is generated when a user is subscribing to an Apikey. Prehash string:2018-03-08T10:59:25.789ZPOST/orders?before=2&limit=30{"product_id":"BTC-USD-0309","order_id":"377454671037440"}

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.

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.

Getting Server Time

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

HTTP Requests

GET /api/general/v3/time

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

}

Wallet API

The Wallet API endpoints include transfer between main account, sub accounts and various trading accounts, getting deposit addresses, withdrawal functions and more.

Get Currencies

This endpoint retrieves a list of all tokens. Not all tokens can be used for trading. Tokens which have or had no representation in ISO 4217 may use a custom code.

HTTP Requests

GET /api/account/v3/currencies

Request Sample

GET /api/account/v3/currencies

Return Parameters
Parameters Parameters Types Description
currency String Token code
name String Token name
can_deposit number availability of depositing, 0 = not available,1 = available
can_withdraw number availability of withdrawal,0 = not available,1 = available
min_withdrawal number the minimum withdrawal limit
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":""
     }

Wallet Information

This endpoint retrieves a list of all assets, including the information about the balances of all tokens, the token amount on hold/available.

HTTP Requests

GET /api/account/v3/wallet

Request Sample

GET /api/account/v3/wallet

Return Parameters
Parameters Parameters Types Description
currency String Token
balance number Amount remaining in the account
hold number Amount on hold
available number Available amount
Return Sample

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

Wallet of a Currency

This endpoint retrieves the information about a single token, including the remaining balance, the token amount on hold/available.

HTTP Requests

GET /api/account/v3/wallet/<currency>

Request Sample

GET /api/account/v3/wallet/XMR

Request Parameters
Parameters Parameters Types Required Description
currency String Yes token
Return Parameters
Parameters Parameters Types Description
balance number Remaining balance
hold number Amount on hold
available number Available amount
currency String Token
Return Sample
{
    "currency":"XMR",
    "available":0.00049136,
    "balance":0.00049136,
    "hold":0
}

Funds Transfer

This endpoint supports the transfer of funds between wallet, trading accounts, main account and sub accounts.

Limit: 3 times / s
HTTP Requests

POST /api/account/v3/transfer

Request Sample

POST /api/account/v3/transfer

Request Parameters
Parameters Parameters Types Required Description
currency String Yes Token
amount number Yes Transfer amount
from number Yes the remitting account (0: sub account 1: spot 3: futures 4:C2C 5: margin 6: wallet 7:ETT 8:PiggyBank 9:swap)
to number Yes the beneficiary account(0: sub account 1:spot 3: futures 4:C2C 5: margin 6: wallet 7:ETT 8:PiggyBank 9 :swap)
sub_account String No sub account name
instrument_id number No margin token pair ID, for supported pairs only
Return Parameters
Parameters Parameters Types Description
transfer_id number Transfer ID
currency String Token to be transferred
from number The remitting account
amount number Transfer amount
to number The beneficiary account
result boolean Transfer result. An error code will be displayed if it failed.
Explanation

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

When ‘from’ or ‘to’ is 5, instrument_id is required.

OK06ETT can only be transferred between ETT and spot accounts

Return Sample
{
    "transfer_id": 754147,
    "currency”:"ETC”
    "from": 6,
    "amount": 0.1,
    "to”: 1,
    "result": true
}

Withdrawal

This endpoint supports the withdrawal of tokens to OKCoin International, other OKEx accounts or other addresses.

HTTP Requests

POST /api/account/v3/withdrawal

Request Sample

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
amount number Yes withdrawal amount
destination number Yes withdrawal address(2:OKCoin International 3:OKEx 4:others)
to_address String Yes verified digital asset address, email or mobile number,some digital asset address format is address+tag , eg: "ARDOR-7JF3-8F2E-QUWZ-CAN7F:123456"
trade_pwd String Yes fund password
fee number Yes Network transaction fee≥0. Withdrawals to OKCoin or OKEx are fee-free, please set as 0. Withdrawal to external digital asset address requires network transaction fee.
Return Parameters
Parameters Parameters Types Description
currency String token
amount number withdrawal amount
withdraw_id number withdrawal ID
result boolean withdrawal result. An error code will be displayed if it failed.
Return Sample
{
    "amount":0.1,
    "withdrawal_id":67485,
    "currency":"btc",
    "result":true
}

Withdrawal Fees

This endpoint retrieves the information about the recommended network transaction fee for withdrawals to digital asset addresses. The higher the fees are, the sooner the confirmations you will get.

HTTP Requests

GET /api/account/v3/withdrawal/fee

Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
currency String No token, information of all tokens will be returned if the field is left blank
Return Parameters
Parameters Parameters Types Description
currency String token
min_fee number minimum withdrawal fee
max_fee number maximum withdrawal fee
Return Sample
{
    {
        "currency":"BTC",
        "max_fee":0.02,
        "min_fee":0.0005
    }
}

Recent Withdrawal History

This endpoint retrieves all recent withdrawal records,100 recent records will be returned at maximum.

HTTP Requests

GET /api/account/v3/withdrawal/history

Request Sample

GET /api/account/v3/withdrawal/history

Return Parameters
Parameters Parameters Types Description
currency String token
amount number amount
timestamp String withdrawal request creation date
from String remitting address(OKEx account will be shown for OKEx address)
to String beneficiary address
tag String tag is required for some tokens. Please leave the field blank if not required
payment_id String payment ID is required for some tokens. Please leave the field blank if it is not required
txid String the txid for withdrawals (leave it blank for internal transfer)
fee String withdrawal fee
status number -3:pending cancel; -2: cancelled; -1: failed; 0 :pending; 1 :sending; 2:sent; 3 :email confirmation; 4 :manual confirmation; 5:awaiting identity confirmation
Explanation

The remitting account is an OKEx account, it does not represent the actual address on the blockchain. If the beneficiary account is also an OKEx account, the txid will not be returned. 100 recent withdrawal records will be returned at maximum. For more records, please request the record of a specific token instead. Please note that the transactions shown here may not be recorded on the blockchain yet. Please be patient if the funds haven’t been credited yet.

Return Sample

    {
        "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
    }

Recent Withdrawal History of a Currency

This endpoint retrieves the withdrawal history of a specific token.

HTTP Request

GET /api/account/v3/withdrawal/history/<currency>

Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
currency String Yes token
Return Parameters
Parameters Parameters Types Description
currency String Token
amount number amount
timestamp String withdrawal request creation date
from String remitting address(OKEx account will be shown for OKEx address)
to String beneficiary address
tag String tag is required for some tokens. Please leave the field blank if not required
payment_id String payment ID is required for some tokens. Please leave the field blank if it is not required
txid String the txid for withdrawals (leave it blank for internal transfer)
fee String withdrawal fee
status String -3:pending cancel; -2: cancelled; -1: failed; 0 :pending; 1 :sending; 2:sent; 3 :email confirmation; 4 :manual confirmation; 5:awaiting identity confirmation
Explanation

The remitting account is an OKEx account, it does not represent the actual address on the blockchain. If the beneficiary account is also an OKEx account, the txid will not be returned. 100 recent withdrawal records will be returned at maximum. For more records, please request the record of a specific token instead. Please note that the transactions shown here may not be recorded on the blockchain yet. Please be patient if the funds haven’t been credited yet.

Return Sample
    {
        "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 wallet. 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. 3 months recent records will be returned at maximum

HTTP Requests

GET /api/account/v3/ledger

Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
currency String No token ,information of all tokens will be returned if the field is left blank
type number 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
from number No you would request pages after this page.
to number No you would request pages before this page
limit number No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
ledger_id number bill ID
currency String token
balance number remaining balance
amount number quantity
typename String type of bills
fee number service fees
timestamp String creation time
Return Sample
{
        "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"
    }

Get Deposit Address

This endpoint retrieves the deposit addresses of different tokens, including previously used addresses.

HTTP Requests

GET /api/account/v3/deposit/address

Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
currency String Yes token
Return Parameters
Parameters Parameters Types Description
address String deposit address
tag String Deposit tag (This string will not be returned if the token does not require a deposit tag)
payment_id String Deposit payment_id (This string will not be returned if the token does not require a payment_id)
currency String token
Explanation

IOTA deposit address cannot be reused! Depositing into a previously used IOTA address will not be confirmed and credited.

Tag or payment ID is required for some tokens. Please fill in the values to ensure the arrival of your funds.

Return Sample

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

Get Deposit History of All Currencies

This endpoint retrieves the deposit history of all tokens.100 recent records will be returned at maximum

HTTP Requests

GET /api/account/v3/deposit/history

Request Sample

GET /api/account/v3/deposit/history

Return Parameters
Parameters Parameters Types Description
currency String token
amount number deposit amount
to String deposit address
txid String TXID
timestamp String deposit arrival date
status number The status of withdrawals (0: waiting for confirmation; 1: confirmation account; 2: recharge success);
Return Sample
{
        "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 endpoint retrieves the deposit history of a token. 100 recent records will be returned at maximum

HTTP Requests

GET /api/account/v3/deposit/history/<currency>

Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
currency String Yes token
Return Parameters
Parameters Parameters Types Description
amount number deposit amount
to String deposit address
txid String TXID
timestamp String deposit arrival date
currency String token
status number The status of withdrawals (0: waiting for confirmation; 1: confirmation account; 2: recharge success);
Return Sample
[{
 "amount": 2,
 "currency":"USDT",
 "to”:”[0x9edfe04c866d636526828e523a60501a37daf8f6](https://etherscan.io/address/0x9edfe04c866d636526828e523a60501a37daf8f6)", 
 "txid”:"0xf1fb12a03c483f475fc33abcb5bf42a765c7131e2f955025aec706be3f616da4”,
  "status":2,
 "timestamp": "2018-09-20T09:21:26.528Z"
}]

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

Token Trading API

Token trading API includes endpoints relating to retrieving market data, account information, orders operations, order enquiry and bills details of spot account.

Description: in order to integrate with the old version, some of the API return parameters may be redundant.

Please refer to the parameter description in the documentation,For example, the returned parameters of frozen, hold are the same with holds of spot trading account, take hold as the criterion. The returned parameters of repay_amount are the same with the parameters of returned_amount, repay_interest and paid_interest. The returned parameters of product_id and instrument_id are the same.

Spot Trading Account

This endpoint supports getting the list of assets(only show pairs with balance larger than 0), the balances, amount available/on hold in spot accounts.

Rate limit: 20 /2s
HTTP Requests

GET /api/spot/v3/accounts

End Certificate Request Sample

2018-09-12T07:27:58.996ZGET/api/spot/v3/accounts

Return Parameters
Parameters Parameters Types Description
currency string token
balance string balance
hold string amount on hold(not available)
available string available amount
id string account ID
Explanation

After you placed an order, the amount of the order will be put on hold. This amount will not be available for transfer or using in other orders until the order is completed or cancelled.

Return Sample
[
    {
        "frozen":"0",
        "hold":"0",
        "id":"9150707",
        "currency":"BTC",
        "balance":"0.0049925",
        "available":"0.0049925",
        "holds":"0"
    },
    {
        "frozen":"0",
        "hold":"0",
        "id":"9150707",
        "currency":"USDT",
        "balance":"226.74061435",
        "available":"226.74061435",
        "holds":"0"
    },
    {
        "frozen":"0",
        "hold":"0",
        "id":"9150707",
        "currency":"EOS",
        "balance":"0.4925",
        "available":"0.4925",
        "holds":"0"
    }
]

Spot Trading Account of a Currency

This endpoint supports getting the balance, amount available/on hold of a token in spot account.

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/accounts/<currency>

End Certificate Request Sample

2018-09-12T07:28:43.497ZGET/api/spot/v3/accounts/btc

Requests Parameters
Parameters Parameters Types Description
currency string [required]token
Return Parameters
Parameters Parameters Types Description
currency string token
balance string balance
hold string amount on hold(not available)
available string available amount
id string account id
Return Sample

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

Bills Details

All 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/spot/v3/accounts/<currency>/ledger

End Certificate Request Sample

2018-03-13T11:46:19.435ZGET/api/spot/v3/accounts/btc/ledger?limit=3&from=2&to=4

Parameters Parameters Types Description
from string [optional]request page before(newer) this id.
to string [optional]request page after(older) this id.
limit string [optional]number of results per request. Maximum 100.(default 100)
currency string [required] token
Return Parameters
Parameters Parameters Types Description
ledger_id string bill ID
balance string balance
currency string token
amount string amount
type string type of bills
timestamp string creation time
details string if the type is trade or fee, order details will be included under this
order_id string order ID
instrument_id string trading pair
Explanation

The following is the enumeration value for the parameters types

Type value Description
transfer funds transfer
trade funds moved as a result of a trade
fee fee as a result of a trade
rebate fee rebate as per our fee schedule
Return Sample
[
    {
        "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 an Order

OKEx token trading 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.

Rate limit: 100/2s
HTTP Requests

POST /api/spot/v3/orders

End Certificate Request Sample

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

Limit Order: 2018-09-12T07:46:47.098ZPOST/api/spot/v3/orders{"client_oid":"T20180728","order_type”:”1”,"instrument_id":"btc-usdt","side":"buy","type":"limit","size":"0.1","price":"100","margin_trading ":"1"}

Request Parameters
Parameters Parameters Types Required Description
client_oid string No the order ID customized 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
type string No limit / market(default: limit)
side string Yes buy or sell
instrument_id string Yes trading pair
margin_trading byte Yes order type (The request value is 1)
order_type string No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Limit Order Parameters
Parameters Parameters Types Required Description
price string Yes price
size string Yes quantity bought or sold
Market Order Parameters
Parameters Parameters Types Required Description
size string Yes quantity sold. (for orders sold at market price only)
notional string Yes amount bought. (for orders bought at market price only)
Return Parameters
Parameters Parameters Types Description
order_id string order ID
client_oid string the order ID customised by yourself
result boolean result of the order. Error message will be returned if the order failed.
Explanation

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 and canceled .

instrument_id

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

client_oid

The optional client_oid field must be a UUID generated by your trading application. This field value will be broadcast in the public feed for received messages. You can use this field to identify your orders in the public feed.

The client_oid is different than the server-assigned order id. If you are consuming the public feed and see a received message with your client_oid, you should record the server-assigned order_id as it will be used for future order status updates. The client_oid will NOT be used after the received message is sent.

type

When placing an order, you can specify the order type. The order type you specify will influence which other order parameters are required 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 orders are both the default and basic order type. A limit order requires specifying a price and size. The size is the number of tokens to buy or sell, and the price is the price per bitcoin. The limit order will be filled at the price specified or better. A sell order can be filled at the specified price per token or a higher price per token and a buy order can be filled at the specified price or a lower price depending on market conditions. If market conditions cannot fill the limit order immediately, then the limit order will become part of the open order book until filled by another incoming order or cancelled by the user.

market orders differ from limit orders in that they provide no pricing guarantees. They however do provide a way to buy or sell specific amounts of tokens without having to specify the price. Market orders execute immediately and no part of the market order will go on the open order book. Market orders are always considered takers and incur taker fees. When placing a market order you can specify funds and/or size. Funds will limit how much of your quote currency account balance is used and size will limit the token amount transacted.

price

The price must be specified in quote_increment product units. The quote increment is the smallest unit of price. This value can be acquired via the /instrument endpoint.

size

Size is the quantity of buying or selling and must be larger than the base_min_size. Base_increment is the minimum increment size. The above parameters can be acquired via the /instrument endpoint.

Example: If the base_min_size of OKB/USDT is 10 and the base_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 quote currency when placing market orders, it is required for market orders. For example, a market buy for BTC-USDT with funds specified as 5000 will spend 5000 USDT to buy BTC.

hold

For limit buy order, we will freeze the quote currency, of which the amount on hold = specific price x buying size. For limit sell orders, we will freeze the currency you want to sell, of which the amount equals to the amount you want to sell. For market buy orders, the quantity of funds in quote currency will be on hold. For market sell orders, the quantity of size will be on hold. Cancelling an open order releases the amount on hold.

Order Lifecycle

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 done 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 being filled or cancelled.

Return Sample
{
    "client_oid":"oktspot79",
    "error_code":0,
    "error_message":"",
    "order_id":"2510789768709120",
    "result":true
}

Place Multiple Orders

This endpoint supports placing multiple orders for specific trading pairs( up to 4 trading pairs, Maximum 10 orders can be placed at a time for each trading pair).

Rate limit: 50/2s
HTTP Requests

POST /api/spot/v3/batch_orders

End Certificate Request Sample

Limit Order: 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"}]

Request Parameters
Parameters Parameters Types Required Description
client_oid string No the order ID customized by yourself ,The type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, Both uppercase and lowercase letters are supported
type string Yes limit / market(default: limit)
side string Yes buy or sell
instrument_id string Yes trading pair
margin_trading string Yes order type (The request value is 1)
order_type string No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Limit Order Parameters
Parameters Parameters Types Required Description
price string Yes price
size string Yes quantity bought or sold
Market Order Parameters
Parameters Parameters Types Required Description
size string No quantity sold. (for orders sold at market price only)
notional string No amount bought. (for orders bought at market price only)
Return Parameters
Parameters Parameters Types Description
order_id long order ID
client_oid string the order ID customised by yourself
result boolean result of the order. Error message will be returned if the order failed.
Explanation

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 and 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" after using the "Cancel multiple orders" endpoint to confirm the cancellation of orders.

Return Sample
{
    "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 an Order

Cancelling an unfilled order.

Rate limit: 100/2s
HTTP Requests

POST /api/spot/v3/cancel_orders/<order_id>

or

POST /api/spot/v3/cancel_orders/<client_oid>

End Certificate Request Sample

2018-10-12T07:32:56.512ZPOST/api/spot/v3/cancel_orders/1611729012263936{"instrument_id":"btc-usdt"}

or

2018-10-12T07:32:56.512ZPOST/api/spot/v3/cancel_orders/1e29012263936{"instrument_id":"btc-usdt"}

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 back to error code.
client_oid string Yes 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 Yes order ID
Return Parameters
Parameters Parameters Types Description
order_id string order ID
client_oid string the order ID created by yourself
result boolean order cancellation result. Error code will be returned if it failed
Explanation

Only fill in either parameter client_oid or order_id

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":"",
        "order_id":[    
            "2510832677225473",
            "2510832677225472",
            "2510832677159936"
        ]
    }
}

Cancel All Orders

With best effort, this endpoints supports cancelling all open orders for a specific trading pair or several trading pairs. Maximum 10 orders can be cancelled at a time for each trading pair

Rate limit: 20/2s
HTTP Requests

POST /api/spot/v3/cancel_batch_orders

End Certificate Request Sample

2018-10-12T07:30:49.664ZPOST/api/spot/v3/cancel_batch_orders[{"instrument_id":"btc-usdt","order_ids":[1600593327162368,1600593327162369]},{"instrument_id":"ltc-usdt","order_ids":[16593327162368,16005927162369]}]

OR

2018-10-12T07:30:49.664ZPOST/api/spot/v3/cancel_batch_orders[{"instrument_id":"btc-usdt","client_oid":"16ee593327162368"},{"instrument_id":"ltc-usdt","client_oid":"243464oo234465"}]

Request Parameters
Parameters Parameters Types Required Description
order_ids list<long> Yes order ID. You may cancel up to 4 orders of a trading pair
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 Yes 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 list<string> order ID
client_oid string the order ID created by yourself
result boolean order cancellation result. Error code will be returned if it failed
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" after using the "Cancel multiple orders" endpoint to confirm the cancellation of orders.

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

Get Order List

List your orders. Cursor pagination is used. All 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/spot/v3/orders

End Certificate Request Sample

2019-03-18T07:49:43.306ZGET/api/spot/v3/orders?instrument_id=BTC-USDT&status=filled%7Copen&limit=2&from=1&to=2

Request Parameters
Parameters Parameters Types Description
status string [required] list the status of all orders (all, open, part_filled, canceling, filled, cancelled,ordering,failure)
instrument_id string [required] list the orders of specific trading pairs
from string [optional]request page after this id (latest information) (eg. 1, 2, 3, 4, 5. There is only a 5 "from 4", while there are 1, 2, 3 "to 4")
to string [optional]request page after (older) this id.
limit string [optional]number of results per request. Maximum 100. (default 100)

(Multiple status separated by '|',and '|' need encode to ' %7C')

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 quantity
notional string the total buying amount. This value will be returned for market orders
instrument_id string trading pair
type string limit,market(defaulted as limit)
side string buy or sell
timestamp string trading pair
filled_size string quantity filled
filled_notional string amount filled
status string order status
order_type string 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Explanation

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, the record may be removed. This indicates that this order cannot be retrieved with this endpoint.

Unfilled orders’ status may change depending on the market between the time of request creation and server response.

Return Sample
[
    [
        {
            "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",
            "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",
            "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",
            "timestamp":"2019-03-18T07:08:24.000Z",
            "type":"limit"
        }
    ],
    {
        "before":"2500723297813504",
        "after":"2500650881647616"
    }
]

Get All Open Orders

List all your current open orders. Cursor pagination is used. All 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/spot/v3/orders_pending

End Certificate Request Sample

2018-09-12T07:51:51.138ZGET/api/spot/v3/orders_pending?limit=2&instrument_id=Btc-usdT&from=2&to=4

Request Parameters
Parameters Parameters Types Description
from string [optional]request page after this id (latest information) (eg. 1, 2, 3, 4, 5. There is only a 5 "from 4", while there are 1, 2, 3 "to 4")
to string [optional]request page after (older) this id.
limit string [optional]number of results per request. Maximum 100. (default 100)
instrument_id string [optional]trading pair ,information of all trading pair will be returned if the field is left blank
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 quantity
notional string the total buying amount. This value will be returned for market orders
instrument_id string trading pair
side string buy or sell
type string limit,market(defaulted as limit)
timestamp string order creation date
filled_size string quantity filled
filled_notional string amount filled
status string order status(all, open, part_filled, canceling, filled, cancelled, ordering,failure )
Explanation

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 .

This endpoint can provide the filled orders and the cancelled orders.

Unfilled orders’ status may change depending on the market between the time of request creation and server response.

Return Sample
[
    [
        {
            "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",
            "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",
            "timestamp":"2019-03-20T03:28:10.000Z",
            "type":"limit"
        }
    ],
    {
        "before":"2511109744100352",
        "after":"2511109459543040"
    }

Get Order Details

Get order details by order ID.

Rate limit: 20/2s
HTTP Requests

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

or

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

End Certificate Request Sample

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

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 description 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 buy or sell
type string limit,market(defaulted as limit)
timestamp string order creation date
filled_size string size filled
filled_notional string amount filled
status string order status(all, open, part_filled, canceling, filled, cancelled,ordering,failure )
order_type string 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Explanation

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.

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

Return Sample
{
    "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",
    "timestamp":"2019-03-15T02:52:56.000Z",
    "type":"limit"
}

Get Transaction Details

Get details of the recent filled orders. Cursor pagination is used. All 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/spot/v3/fills

End Certificate Request Sample

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

Requests Parameters
Parameters ParametersTypes Description
order_id string [required]list all transaction details of this order_id.
instrument_id string [required]list all transaction details of this instrument_id.
from string [optional]request page after this id (latest information) (eg. 1, 2, 3, 4, 5. There is only a 5 "from 4", while there are 1, 2, 3 "to 4")
to string [optional]request page after (older) this id.
limit string [optional]number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
ledger_id string bill ID
instrument_id string trading pair
price string price
size string quantity
order_id string order ID
timestamp string create date
exec_type string liquidity side (T or M)
fee string liquidity side
side string bills side(buy ,sell or points_fee)
Explanation

Fees

If the value of "side" is "settle with loyalty points", then the value of "fee" should be the fee amount settled by loyalty points.

Liquidity

The parameter exec_type shows whether the order is maker or taker. (M=Maker, T=Taker)

Pagination

Ledger_id are listed in a descending order, from biggest to smallest. The first ledger_id can be found under OK-FROM, so it would be easier to acquire a larger ledger_id (new bills) by using OK-FROM in the future.

Return Sample
[
    [
        {
            "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"
    }
]

Get Token Pair Details

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

List trading pairs and get the trading limit, price, and more information of different trading pairs.

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/instruments

End Certificate Request Sample

2018-09-12T07:56:45.645ZGET/api/spot/v3/instruments

Return Parameters
Parameters Parameters Types Description
instrument_id string trading pair
base_currency string base currency
quote_currency string quote currency
min_size string minimum trading size
size_increment string minimum increment size
tick_size string trading price increment
Explanation

Min_size is the quantity of buying or selling and must be larger than the base_min_size and also mean the minimum loan amount. Base_increment is the minimum increment size. If the base_increment is 0.000001, entering a size of 0.0.0000126 will be adjusted to 0.000012.

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.0001, entering a price of 0.02237 will be adjusted to 0.0223 instead.

Return Sample
[
    {
        "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"
    }
]

Get Order Book

Getting the order book of a trading pair. Pagination is not supported here. The whole book will be returned for one request. WebSocket is recommended here.

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/instruments/<instrument_id>/book

End Certificate Request Sample

2019-03-20T07:48:09.130ZGET/api/spot/v3/instruments/BTC-USDT/book?size=5&depth=0.2

Requests Parameters
Parameters Parameters Types Description
size string [optional]number of results per request. Maximum 200
depth string [optional]the aggregation of the book. e.g . 0.1,0.001
instrument_id string [required] trading pairs
Return Parameters
Parameters Parameters Types Description
price string price
size string Size
num_orders integer total orders in the book
timestamp string timestamp
Explanation

Aggregation (depth) is the formation of a certain price range into a cluster.

Return Sample
{
    "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"
}

Get All Token Pairs Information

Get the last traded price, best bid/ask price, 24 hour trading volume and more info of all trading pairs.

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/instruments/ticker

End Certificate Request Sample

2018-09-12T07:57:26.537ZGET/api/spot/v3/instruments/ticker

Return Parameters
Parameters Parameters Types Description
instrument_id string trading pair
last string last traded 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 trading volume of the base currency
quote_volume_24h string 24 trading volume of the quote currency
timestamp string timestamp
Explanation

The high, low and trading volume are all computed based on the data in the last 24 hours.

The 24 hour open is the price of the minute before the last 24 hours.

Return Sample
[
    {
        "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"
    }
]

Get a Token Pair Information

Get the last traded price, best bid/ask price, 24 hour trading volume and more info of a trading pair.

Rate limit: 20 / 2s
HTTP Requests

GET /api/spot/v3/instruments/<instrument_id>/ticker

End Certificate Request Sample

2019-03-13T11:42:09.849ZGET/api/spot/v3/instruments/BTC-USDT/ticker

Requests Parameters
Parameters Parameters Types Description
instrument_id string [required]trading pair
Return Parameters
Parameters Parameters Types Description
instrument_id string trading pair
last string last traded 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 trading volume of the base currency
quote_volume_24h string 24 trading volume of the quote currency
timestamp string timestamp
Explanation

The high, low and trading volume are all computed based on the data in the last 24 hours.

The 24 hour open is the price of the minute before the last 24 hours.

Return Sample
{
  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
}

Get Filled Orders Information

Get the recent 60 transactions of all trading pairs. Cursor pagination is used. All 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/spot/v3/instruments/<instrument_id>/trades

End Certificate Request Sample

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

Requests Parameters
Parameters Parameters Types Description
from string [optional]request page after this id (latest information) (eg. 1, 2, 3, 4, 5. There is only a 5 "from 4", while there are 1, 2, 3 "to 4")
to string [optional]request page after (older) this id.
limit string [optional]number of results per request. Maximum 100. (default 100)
instrument_id string [required] trading pairs
Return Parameters
Parameters Parameters Types Description
timestamp string filled time
trade_id string transaction time ID
price string filled price
size string filled size
side string filled side
Explanation

The filled side is the order side of the Taker. Taker is the one who actively take the order on the book. Buying indicates the taker is taking liquidity from the book, so the price is rising. While selling indicates the price is falling.

trade_id is the increasing ID of the filled orders (could be incomplete).

Return Sample
{
    "best_ask":"3998.5",
    "best_bid":"3998",
    "instrument_id":"BTC-USDT",
    "product_id":"BTC-USDT",
    "last":"3998.5",
    "ask":"3998.5",
    "bid":"3998",
    "open_24h":"3980.4",
    "high_24h":"4031.9",
    "low_24h":"3975.1",
    "base_volume_24h":"30685.44764123",
    "timestamp":"2019-03-20T05:38:27.748Z",
    "quote_volume_24h":"122685441.8"
}

Get Market Data

Get the charts of the trading pairs. Charts are returned in grouped buckets based on requested granularity.

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/instruments/<instrument_id>/candles

End Certificate Request Sample

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

Requests Parameters
Parameters Parameters Types Description
start string [optional]start time in ISO 8601
end string [optional] end time in ISO 8601
granularity integer [optional] desired timeslice in seconds
instrument_id string [required] trading pairs
Return Parameters
Parameters Parameters Types 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
Explanation

If either one of the start or end fields are not provided then both fields will be ignored. If a custom time range is not declared then it will return the last 200 datas..

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 one minute, three minutes, five minutes, fifteen minutes, thirty minutes, one hour, two hours, six hours, twelve hours, one day, and 1 week respectively.

The chart data may be incomplete and should not be polled.

The maximum number of data points for a single request is 200 candles. If your selection of start/end time and granularity will result in more than 200 data points, your request will be rejected. If you wish to retrieve fine granularity data over a larger time range, you will need to make multiple requests with new start/end ranges.

Return Sample

[
    [
        "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"
    ]
]

Error Code

Error Code Sample
Business Error Messages Business Error Codes http Status Code Scenarios
margin account for this pair is not enabled yet 33001 400 the service must be enabled before trading
margin account for this pair is suspended 33002 400 margin account suspended
no loan balance 33003 400 insufficient balance for loan
loan amount cannot be smaller than the minimum limit 33004 400 minimum loan amount limit not reached
repayment amount must exceed 0 33005 400 invalid repayment amount
loan order not found 33006 400 loan order not found
status not found 33007 400 status unchanged
loan amount cannot exceed the maximum limit 33008 400 invalid loan amount
user ID is blank 33009 400 user ID not provided
you cannot cancel an order during session 2 of call auction 33010 400 order cancellation not allowed during call auction
no new market data 33011 400 no market data
order cancellation failed 33012 400 order cancellation failed
order placement failed 33013 400 order placement failed
order does not exist 33014 400 order canceled already. Invalid order number
exceeded maximum limit 33015 400 exceeded maximum limit during multiple-order placement
margin trading is not open for this token 33016 400 insufficient balance for order placement
insufficient balance 33017 400 margin trading not supported for this pair
this parameter must be smaller than 1 33018 400 invalid parameter for getting market data
request not supported 33020 400 margin trading not supported for some exchanges
token and the pair do not match 33021 400 incorrect token for the token pair during repayment
pair and the order do not match 33022 400 incorrect token for the order during repayment
you can only place market orders during call auction 33023 400 you can only place market orders during call auction
trading amount too small 33024 400 invalid trading amount
base token amount is blank 33025 400 settings not completed during order placement
transaction completed 33026 400 cancel limited when the transaction completed
cancelled order or order cancelling 33027 400 cancel limited when the order is cancelling or cancelled
the decimal places of the trading price exceeded the limit 33028 400 order endpoint: The decimal places of the trading price exceeded the limit
the decimal places of the trading size exceeded the limit 33029 400 order endpoint::The decimal places of the trading size exceeded the limit

Margin Trading API

The market data, account info, order operations, bill details and more of token margin trading.

Description: in order to integrate with the old version, some of the API return parameters may be redundant.

Please refer to the parameter description in the documentation. For example, the parameters of frozen, old, and hoids of token account information API return are the same. Take hold as the criterion. The API return parameters to capture borrowed token records repay_amount and returned_amount, as well as repay_interest and paid_interest are the same, to name a few.

Margin account

List all assets under token margin trading account, including information such as balance, amount on hold and more.

Rate limit: 20/ 2s
HTTP Requests

GET /api/margin/v3/accounts

End Certificate Request Sample

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

Return Parameters
Parameters Parameters Types Description
instrument_id string trading pair
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)
Explanation

The funds for order placement will be put on hold. They will not be able to transfer or used for other purposes until the order is filled or cancelled.

Return Sample
[
{
    "currency:BTC": {
        "available": "2",
        "balance": "3",
        "borrowed": "3",
        "can_withdraw": "1.78823759",
        "frozen": "1",
        "hold": "1",
        "holds": "1",
        "lending_fee": "0.7"
    },
    "currency:ETH": {
        "available": "200",
        "balance": "300",
        "borrowed": "300",
        "can_withdraw": "1.78823759",
        "frozen": "100",
        "hold": "100",
        "holds": "100",
        "lending_fee": "75"
    },
    "instrument_id": "ETH-BTC",
    "liquidation_price": "122",
    "product_id": "ETH-BTC",
    "risk_rate": "0.3"
}, {
    "currency:BTC": {
        "available": "2",
        "balance": "3",
        "borrowed": "3",
        "can_withdraw": "1.78823759",
        "frozen": "1",
        "hold": "1",
        "holds": "1",
        "lending_fee": "0.7"
    },
    "currency:ETH": {
        "available": "200",
        "balance": "300",
        "borrowed": "300",
        "can_withdraw": "1.78823759",
        "frozen": "100",
        "hold": "100",
        "holds": "100",
        "lending_fee": "75"
    },
    "instrument_id": "IOST-BTC",
    "liquidation_price": "20",
    "product_id": "IOST-BTC",
    "risk_rate": "0.6"
}]

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/btc-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)
Return Sample
{
    "currency:BTC": {
        "available": "2",
        "balance": "3",
        "borrowed": "3",
        "can_withdraw": "1.78823759",
        "frozen": "1",
        "hold": "1",
        "holds": "1",
        "lending_fee": "0.7"
    },
    "currency:ETH": {
        "available": "200",
        "balance": "300",
        "borrowed": "300",
        "can_withdraw": "1.78823759",
        "frozen": "100",
        "hold": "100",
        "holds": "100",
        "lending_fee": "75"
    },

    "liquidation_price": "122",
    "risk_rate": "0.3"
}

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.

Rate limit: 20/ 2s
HTTP Requests

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

End Certificate Request Sample

2018-09-13T02:26:29.443ZGET/api/margin/v3/accounts/btc-usdt/ledger?limit=2&type=1&from=2&to=4

Request Parameters
Parameters Parameters Types Description
type string [optional]1: transfer in 2: transfer out 3: borrow 4: repay 5: interest 6: liquidation loss 7: buy 8: sell. All types will be returned if this filed is left blank
from string [optional]request page before(newer) this id
to string [optional]request page after(older) this id
limit string [optional]number of results per request. Maximum 100(default 100)
instrument_id string [required] trading pair
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
fee fee as a result of a trade
rebate fee rebate as per our fee schedule
Return Sample
[
{
 "amount":"0.999",
 "balance”:"6.539194",
 "currency”:"LTC”,
 "timestamp":"2018-06-20T02:31:00.000Z",
 "details":
 {"order_id”:7542,"instrument_id":"LTC-BTC"},
 "ledger_id": "912025447”,
 "type”:”trade"
},
{
 "amount":"1",
 "balance”:"31.797831",
 "currency”:"LTC”
 "timestamp":"2018-06-20T02:31:00.000Z",
 "details":
 {"order_id”:7542,"instrument_id":"LTC-BTC"},
 "ledger_id”:"912025427”,
 "type”:”trade"},
…
]

Margin Account Settings

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

Rate limit:20/2s
HTTP Requests

GET /api/margin/v3/accounts/availability

End Certificate Request Sample

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

Return Parameters
Parameters Parameters Types Description
instrument_id string trading pair
currency string token
available string maximum loan amount
rate string interest rate
leverage string maximum leverage
Return Sample
[{
 "instrument_id”:”BTC-USDT”,

 "currency:BTC”: {

 "available”:”3”,

 "rate”:”0.001”,

 "leverage”:”3”

 },

 "currency:USDT”: {

 "balance”:”300”,

 "rate”:”0.001”,

 "leverage”:”3”
    }
 },
{

 "instrument_id”:”XRP-USDT”,

 "currency:XRP”: {

 "available”:”300”,

 "rate”:”0.0002”,

 "leverage”:”3”

 },

 "currency:USDT”: {

 "available”:”300”,

 "rate”:”0.001”,

 "leverage”:”3”

 }
 },
…
]

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

2018-09-13T02: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:ETH":{
            "available":"0",
            "leverage":"3",
            "leverage_ratio":"3",
            "rate":"1.3248E-4"
        },
        "currency:USDT":{
            "available":"0",
            "leverage":"3",
            "leverage_ratio":"3",
            "rate":"1.4496E-4"
        },
        "instrument_id":"ETH-USDT",
        "product_id":"ETH-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 Description
status string [optional] status(0: outstanding 1: repaid)
from string [optional]request page from(newer) this id.
to string [optional]request page to(older) this id.
limit string [optional]number of results per request. Maximum 100.(default 100)
Return Parameters
Parameters Parameters Types Description
borrow_id long 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.1",
    "borrow_id": 185762,
    "created_at": "2018-10-11T09:04:18Z",
    "currency": "USDT",
    "instrument_id": "LTC-USDT",
    "interest": "0",
    "last_interest_time": "2018-10-11T09:04:18Z",
    "paid_interest": "0",
    "product_id": "LTC-USDT",
    "repay_amount": "0.1",
    "repay_interest": "0",
    "returned_amount": "0.1",
    "timestamp": "2018-10-11T09:04:18.000Z",
    "force_repay_time":"2018-12-03T08:44:19Z",
    "rate":"0.00000045"
}, {
    "amount": "0.1",
    "borrow_id": 185761,
    "created_at": "2018-10-11T06:28:24Z",
    "currency": "USDT",
    "instrument_id": "LTC-USDT",
    "interest": "0",
    "last_interest_time": "2018-10-11T06:28:24Z",
    "paid_interest": "0",
    "product_id": "LTC-USDT",
    "repay_amount": "0.1",
    "repay_interest": "0",
    "returned_amount": "0.1",
    "timestamp": "2018-10-11T06:28:24.000Z",
    "force_repay_time":"2018-12-03T08:44:19Z",
    "rate":"0.00000045"
}]

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&status=1&from=2&to=4

Request Parameters
Parameters Parameters Types Description
status string [optional]status(0: outstanding 1: repaid)
from string [optional]request page from(newer) this id.
to string [optional]request page to(older) this id.
limit string [optional]number of results per request. Maximum 100.(default 100)
instrument_id string [required] trading pair
Return Parameters
Parameters Parameters Types Description
borrow_id long 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.1",
    "borrow_id": 185761,
    "created_at": "2018-10-11T06:28:24Z",
    "currency": "USDT",
    "instrument_id": "LTC-USDT",
    "interest": "0",
    "last_interest_time": "2018-10-11T06:28:24Z",
    "paid_interest": "0",
    "product_id": "LTC-USDT",
    "repay_amount": "0.1",
    "repay_interest": "0",
    "returned_amount": "0.1",
    "timestamp": "2018-10-11T06:28:24.000Z",
    "force_repay_time":"2018-12-03T08:44:19Z",
    "rate":"0.00000045"
}]

Loan

Borrowing tokens in a margin trading account.

Rate limit:100/2s
HTTP Requests

POST /api/margin/v3/accounts/borrow

End Certificate Request Sample

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

Request 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 long borrow ID
result boolean result
Return Sample
{
    "borrow_id":185760,
    "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 long borrow ID
result boolean result
Return Sample
{
    "repayment_id":185760,
    "result":true
}

Place an Order

OKEx API only supports limit and market orders (more orders 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.

Rate limit: 100/ 2s
HTTP Requests

POST /api/margin/v3/orders

End Certificate Request Sample

Market Order: 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"}

Limit Order: 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","price":"100","margin_trading ":"2"}

Request Parameters
Parameters Parameters Types Required Description
client_oid string No the order ID customized 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
type string No Limit/market(default:limit)
side string Yes buy/sell
instrument_id string Yes Trading pair
margin_trading string Yes Order type (The request value is 2)
order_type string No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Limit Order Parameters
Parameters Parameters Types Required Description
price string Yes price
size string Yes quantity bought or sold
Market Order Parameters
Parameters Parameters Types Compulsory Description
size string No quantity sold.(for orders sold at market price only)
notional string No amount bought.(for orders bought at market price only)
Return Parameters
Parameters Parameters Types Description
order_id string order ID
client_oid string the order ID customized by yourself
result boolean result of the order.Error message will be returned if the order failed.
Explanation

instrument_id

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

client_oid

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 and canceled

When placing an order, you can specify the order type. The order type you specify will influence which other order parameters are required 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 orders are both the default and basic order type. A limit order requires specifying a price and size. The size is the number of tokens to buy or sell, and the price is the price per bitcoin. The limit order will be filled at the price specified or better. A sell order can be filled at the specified price per token or a higher price per token and a buy order can be filled at the specified price or a lower price depending on market conditions. If market conditions cannot fill the limit order immediately, then the limit order will become part of the open order book until filled by another incoming order or cancelled by the user.

market orders differ from limit orders in that they provide no pricing guarantees. They however do provide a way to buy or sell specific amounts of tokens without having to specify the price. Market orders execute immediately and no part of the market order will go on the open order book. Market orders are always considered takers and incur taker fees. When placing a market order you can specify funds and/or size. Funds will limit how much of your quote currency account balance is used and size will limit the token amount transacted.

price

The price must be specified in quote_increment product units. The quote increment is the smallest unit of price. This value can be acquired via the /instrument endpoint.

size

Size is the quantity of buying or selling and must be larger than the base_min_size. Base_increment is the minimum increment size. The above parameters can be acquired via the /instrument endpoint.

Example: If the base_min_size of OKB/USDT is 10 and the base_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 optionally used for market orders. When specified it indicates how much of the product quote currency to buy or sell. For example, a market buy for BTC-USDT with funds specified as 5000 will spend 5000 USDT to buy BTC.

hold

The amount on hold of a limit order = specific price x buying size. Cancelling an open order releases the amount on hold.

Order Lifecycle

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 done 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.

Return Sample
{
    "order_id": "667893",
    "client_oid": "E102",
    "result": true
}

Place Multiple Orders

Place multiple orders for specific trading pairs (up to 4 trading pairs, Maximum 10 orders can be placed at a time for each trading pair).

Rate limit: 50 / 2s
HTTP Requests

POST /api/margin/v3/batch_orders

End Certificate Request Sample

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 ":"1"},{"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"limit"," size ":"0.001","notional":"10002","margin_trading ":"1"}

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 ":"1"},{"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"limit","size":"0.001","price":"10002","margin_trading ":"1"}

Request Parameters
Parameters Parameters Types Required Description
client_oid string No The order ID customized by yourself ,The type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, Both uppercase and lowercase letters are supported
type string No Limit/market(default:limit)
side string Yes buy/sell
instrument_id string Yes Trading pair
margin_trading string Yes Order type (The request value is 2)
order_type string No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Limit Order Parameters
Parameters Parameters Types Required Description
price string Yes price
size string Yes quantity bought or sold
Market Order Parameters
Parameters Parameters Types Required Description
size string No quantity sold.(for orders sold at market price only)
notional string No amount bought.(for orders bought at market price only)
Return Parameters
Parameters Parameters Types Description
order_id long Order ID
client_oid string This client_oid is the order ID sent by the user.
result boolean If the order cannot be cancelled (already settled or cancelled),the error description it returns to will display the corresponding reason.
Explanation

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 and 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":[
        {
            "client_oid":"F20180918",
            "order_id":995703349,
            "result":true
        },
        {
            "client_oid":"T20180917",
            "order_id":995703350,
            "result":true
        },
{
            "client_oid":"S20180917",
            "order_id":-1,
            "false":true
        }

    ]
}

Cancel an Order

Cancelling an unfilled order.

Rate limit: 100 / 2s
HTTP Requests

DELETE /api/margin/v3/cancel_orders/<order_id>

or

DELETE /api/margin/v3/cancel_orders/<client_oid>

End Certificate Request Sample

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

or

2018-10-12T07:34:30.223ZPOST/api/margin/v3/cancel_orders/2e3850{"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 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 yes order ID
Return Parameters
Parameters Parameters Types Description
order_id long order ID
client_oid string this client_oid is the order ID sent by the user.
result boolean if the order cannot be cancelled (already settled or cancelled),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
{
"client_oid":"E2018100901",
"order_id":1745,
"result":true
}

Cancel all Orders

With best effort, cancel all open orders.Maximum 10 orders can be cancelled at a time for each trading pair

Rate limit: 50/ 2s
HTTP Requests

DELETE /api/margin/v3/cancel_batch_orders

End Certificate Request Sample

2018-10-12T07:33:28.988ZPOST/api/margin/v3/cancel_batch_orders[{"instrument_id":"btc-usdt","order_ids":[23464,23465]},{"instrument_id":"ltc-usdt","order_ids":[233464,22465]}]

OR

2018-10-12T07:30:49.664ZPOST/api/spot/v3/cancel_batch_orders[{"instrument_id":"btc-usdt","client_oid":"16ee593327162368"},{"instrument_id":"ltc-usdt","client_oid":"243464oo234465"}]

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_id list<long> Yes order ID
client_oid string Yes 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 list<string> order ID
client_oid string this client_oid is the order ID sent by the user.
instrument_id string trading pair
result boolean if the order cannot be cancelled (already settled or cancelled),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":"",
"order_id":["1747","1748"]
},
"ltc-eth”:{
"result":true,
"client_oid":"",
"order_id”:["1758”,”1779","1880"]
}
}

Get Order List

List your orders. Cursor pagination is used. All 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/orders

End Certificate Request Sample

2018-09-12T07:49:43.306ZGET/api/spot/v3/orders?instrument_id=BTC-USDT&status=filled%7Copen&limit=2&from=2&to=4

Request Parameters
Parameters Parameters Types Description
status string [required] list the status of all orders (all, open, part_filled, canceling, filled, cancelled,ordering,failure )
instrument_id string [required] list the orders of specific trading pairs
from string [optional]request page from(newer)this id.
to string [optional]request page to(older)this id.
limit string [optional]number of results per request.Maximum 100.(default 100)

(Multiple status separated by '|',and '|' need encode to ' %7C')

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 quantity
notional string the total buying amount.This value will be returned for market orders
instrument_id string trading pair
side string order side
type string order type
timestamp string order creation date
filled_size string quantity filled
filled_notional string amount filled
status string order status
order_type string 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Explanation

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, the record may be removed. This indicates that this order cannot be downloaded with this endpoint.

Unfilled orders status may change depending on the market between the time of request creation and server response.

Return Sample
[{
    "order_id": "3000",
    "client_oid": "w125678",
    "notional": "30",
    "price": "0.10000000",
    "size": "0.01000000",
    "instrument_id": "BTC-USDT",
    "side": "buy",
    "type": "limit",
    "order_type”:”1”,
    "timestamp": "2016-12-08T20:02:28.538Z",
    "filled_size": "0.00000000",
    "filled_notional": "0.0000000000000000",
    "status": "open"
},{
    "order_id": “2998",
     "notional": "30",
     "client_oid": "w125678",
    "size": "1.00000000",
    "instrument_id": "BTC-USDT",
    "side": "sell",
    "type": "market",
    "order_type”:”1”,
    "timestamp": "2016-12-08T20:09:05.508Z",
    "filled_size": "1.00000000",
    "filled_notional": "9.9750556620000000",
    "status": "filled"
}]

Get Order Details

Get order details by order ID

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
status string order status(all, open, part_filled, canceling, filled, cancelled,ordering,failure )
order_type string 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Explanation

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.

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

Return Sample
{
    "order_id": "233456",
    "client_oid": "w125678",
    "notional": "10000.0000",
    "price”:"8014.23”,
    "size”:"4”,
    "instrument_id": "BTC-USDT",
    "side": "buy",
    "type": "market",
    "order_type”:”1”,
    "timestamp": "2016-12-08T20:09:05.508Z",
    "filled_size": "0.1291771",
    "filled_notional": "10000.0000",
    "status": "filled"
}

Get All Open Orders

List all your current orders. Cursor pagination is used. All 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/orders_pending

End Certificate Request Sample

2018-09-12T07:51:51.138ZGET/api/margin/v3/orders_pending?limit=2&instrument_id=btc-usdt&from=2&to=4

Request Parameters
Parameters Parameters Types Description
from string [optional] request page after this id (latest information) (eg. 1, 2, 3, 4, 5. There is only a 5 "from 4", while there are 1, 2, 3 "to 4")
to string [optional]request page after (older) this id.
limit string [optional]number of results per request. Maximum 100. (default 100)
instrument_id string [optional]trading pair ,information of all trading pair will be returned if the field is left blank
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 quantity
notional string the total buying amount. This value will be returned for market orders
instrument_id string trading pair
side string buy or sell
type string limit,market(defaulted as limit)
timestamp string order creation date
filled_size string quantity filled
filled_notional string amount filled
status string order status(all, open, part_filled, canceling, filled, cancelled,ordering,failure)
Explanation

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 .

This endpoint can provide the filled orders and the cancelled orders.

Unfilled orders’ status may change depending on the market between the time of request creation and server response.

Return Sample
[{
    "order_id": "125678",
    "client_oid": "w125678",
    "notional": "12.4",
    "price": "0.10000000",
    "size": "0.01000000",
    "instrument_id": "BTC-USDT",
    "side": "buy",
    "type": "limit",
    "timestamp": "2016-12-08T20:02:28.538Z",
    "filled_size": "0.00000000",
    "filled_notional": "0.0000000000000000",
    "status": "open"
},{
    "order_id": "125600",
    "client_oid": "w1256708",
    "notional": "12.4",
    "price": "0.10000000",
    "size": "1.00000000",
    "instrument_id": "BTC-USDT",
    "side": "sell",
    "type": "market",
    "timestamp": "2016-12-08T20:09:05.508Z",
    "filled_size": "0.80000000",
    "filled_notional": "9.9750556620000000",
    "status": "part_filled”
}
]

Get Transaction Details

Get details of the recent filled orders. Cursor pagination is used. All 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/fills

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types Description
order_id string [required]list all transaction details of this order_id.
instrument_id string [required]list all transaction details of this instrument_id.
from string [optional]request page from(newer)this id.
to string [optional]request page to(older)this id.
limit string [optional]number of results per request.Maximum 100(default 100)
Return Parameters
Parameters Parameters Types Description
ledger_id string bill ID
instrument_id string trading pair
price string price
size string order size
order_id string order ID
timestamp string order creation time
exec_type string taker or Maker(T or M)
fee string fees
side string side of order (buy or sell)
Explanation

Fees The fee levied in the transactions

Liquidity The order is created by maker or taker. (M=Maker, T=Taker)

Pagination Ledger_id are listed in a descending order, from biggest to smallest. The first ledger_id can be found under OK-FROM, so it would be easier to acquire a larger ledger_id (new bills) by using OK-FROM in the future.

Return Sample
[{

"ledger_id": "74",

"instrument_id": "BTC-USDT",

"price": "10.00",

"size": "0.01",

"order_id": "d50ec984-77a8-460a-b958-66f114b0de9b",

"timestamp": "2014-11-07T22:19:28.578Z",

"exec_type": "T",

"fee": "0.00025",

"side": "buy"

}]

Margin Trading Market Data

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

To acquire updated market data, please read the WebSocket document, which can help you to get and create more comprehensive data.

Spot trading and margin trading shares the same market data, please visit token trading for endpoints details.

Error Code

Error Code Sample
Business Error Messages Business Error Codes http Status Code Scenarios
margin account for this pair is not enabled yet 33001 400 the service must be enabled before trading
margin account for this pair is suspended 33002 400 margin account suspended
no loan balance 33003 400 insufficient balance for loan
loan amount cannot be smaller than the minimum limit 33004 400 minimum loan amount limit not reached
repayment amount must exceed 0 33005 400 invalid repayment amount
loan order not found 33006 400 loan order not found
status not found 33007 400 status unchanged
loan amount cannot exceed the maximum limit 33008 400 invalid loan amount
user ID is blank 33009 400 user ID not provided
you cannot cancel an order during session 2 of call auction 33010 400 order cancellation not allowed during call auction
no new market data 33011 400 no market data
order cancellation failed 33012 400 order cancellation failed
order placement failed 33013 400 order placement failed
order does not exist 33014 400 order canceled already. Invalid order number
exceeded maximum limit 33015 400 exceeded maximum limit during multiple-order placement
margin trading is not open for this token 33016 400 insufficient balance for order placement
insufficient balance 33017 400 margin trading not supported for this pair
this parameter must be smaller than 1 33018 400 invalid parameter for getting market data
request not supported 33020 400 margin trading not supported for some exchanges
token and the pair do not match 33021 400 incorrect token for the token pair during repayment
pair and the order do not match 33022 400 incorrect token for the order during repayment
you can only place market orders during call auction 33023 400 you can only place market orders during call auction
trading amount too small 33024 400 invalid trading amount
base token amount is blank 33025 400 settings not completed during order placement
transaction completed 33026 400 cancel limited when the transaction completed
cancelled order or order cancelling 33027 400 cancel limited when the order is cancelling or cancelled
the decimal places of the trading price exceeded the limit 33028 400 order endpoint: The decimal places of the trading price exceeded the limit
the decimal places of the trading size exceeded the limit 33029 400 order endpoint::The decimal places of the trading size exceeded the limit

Futures Trading API

Market data, account info, order operations, order enquiry, bills enquiry of futures trading.

Futures Positions

Get the information of all holding positions in futures trading.Due to high energy consumption, you are advised to capture data with the "Futures Account of a Currency" API instead.

HTTP Requests

GET /api/futures/v3/position

Limit: 5 times / 2s
Request Sample

GET/api/futures/v3/position

Return Parameters
Crossed_margin
Crossed_marginParameters Parameters Types Description
margin_mode String Account Type: crossed
force_liqu_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
realised_pnl String realised profits
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-USD-180213”
leverage String Leverage
created_at String Creation date
updated_at String Last margin adjusting time
Fixed_margin
Fixed_margin 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
realised_pnl String realised profits
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-USD-180213”
created_at(long) String Creation date
updated_at String Last margin adjusting time
Return Sample
Cross_margin
{
    "result":true,
    "holding":[
        [
            {
                "long_qty":"1",
                "long_avail_qty":"1",
                "long_margin":"0.464",
                "long_liqui_price":"1.977",
                "long_pnl_ratio":"0.014",
                "long_avg_cost":"2.154",
                "long_settlement_price":"2.154",
                "realised_pnl":"-0.001",
                "short_qty":"0",
                "short_avail_qty":"0",
                "short_margin":"0",
                "short_liqui_price":"0",
                "short_pnl_ratio":"-0",
                "short_avg_cost":"0",
                "short_settlement_price":"0",
                "instrument_id":"EOS-USD-190329",
                "long_leverage":"10",
                "short_leverage":"0",
                "created_at":"2018-12-17T14:52:45.0Z",
                "updated_at":"2018-12-28T06:30:52.0Z",
                "margin_mode":"fixed"
            }
        ],
        [
            {
                "long_qty":"0",
                "long_avail_qty":"0",
                "long_avg_cost":"0",
                "long_settlement_price":"0",
                "realised_pnl":"-0.0001133",
                "short_qty":"1",
                "short_avail_qty":"1",
                "short_avg_cost":"26.479",
                "short_settlement_price":"26.479",
                "liquidation_price":"0.000",
                "instrument_id":"LTC-USD-190329",
                "leverage":"10",
                "created_at":"2018-12-28T06:30:40.0Z",
                "updated_at":"2018-12-28T06:30:40.0Z",
                "margin_mode":"crossed"
            }
        ]
    ]
}

Futures Positions of a Contract

Get the information of holding positions of a contract.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID, e.g.“BTC-USD-180213”
Return Parameters
Cross_margin
Cross_marginParameters Parameters Types 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
realised_pnl String realised profits
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-USD-180213”
created_at String Creation date
updated_at String Last margin adjusting time
Fixed_margin
Fixed_margin 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
realised_pnl String realised 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
realised_pnl String realised profits of long positions
short_leverage String Leverage for short positions
instrument_id String Contract ID, e.g. “BTC-USD-180213”
created_at(long) String Creation date
updated_at String Last margin adjusting time
Return Sample
Crossed_margin
{
    "result":true,
    "holding":[
        {
            "long_qty":"1",
            "long_avail_qty":"1",
            "long_avg_cost":"27.94",
            "long_settlement_price":"27.94",
            "realised_pnl":"-0.00010737",
            "short_qty":"0",
            "short_avail_qty":"0",
            "short_avg_cost":"0",
            "short_settlement_price":"0",
            "liquidation_price":"11.831",
            "instrument_id":"LTC-USD-181228",
            "leverage":"10",
            "created_at":"2018-12-28T06:34:10.0Z",
            "updated_at":"2018-12-28T06:34:10.0Z",
            "margin_mode":"crossed"
        }
    ],
    "margin_mode":"crossed"
}
Fixed_margin
{
    "result":true,
    "holding":[
        {
            "long_qty":"1",
            "long_avail_qty":"1",
            "long_margin":"0.218",
            "long_liqui_price":"2.202",
            "long_pnl_ratio":"-0.079",
            "long_avg_cost":"2.29",
            "long_settlement_price":"2.29",
            "realised_pnl":"-0.102",
            "short_qty":"0",
            "short_avail_qty":"0",
            "short_margin":"0",
            "short_liqui_price":"0",
            "short_pnl_ratio":"1.153",
            "short_avg_cost":"2.544",
            "short_settlement_price":"2.544",
            "instrument_id":"EOS-USD-181228",
            "long_leverage":"20",
            "short_leverage":"10",
            "created_at":"2018-10-04T01:31:49.0Z",
            "updated_at":"2018-12-28T06:15:52.0Z",
            "margin_mode":"fixed"
        }
    ],
    "margin_mode":"fixed"
}

Futures Account of all Currency

Get the futures account info of all token.Due to high energy consumption, you are advised to capture data with the "Futures Account of a Currency" API instead.

HTTP Requests

GET /api/futures/v3/accounts

Limit: 1 times / 10s
Request Sample

GET/api/futures/v3/accounts

Return Parameters
Cross_margin
Cross_marginParameters 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
margin String Margin (on hold for open orders + positions holding)
margin_frozen String Position margin
margin_for_unfilled String Margin on hold for open orders
realized_pnl String realised profit and loss
unrealized_pnl String Unrealised profit and loss
margin_ratio String Margin ratio
Fixed_margin
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
balance String Account balance (contract)
margin_frozen String Position margin
margin_for_unfilled String Margin on hold for open orders
realized_pnl String realised profit and loss
unrealized_pnl String Unrealised profit and loss
equity String Equity of the account
total_avail_balance String Balance of the account
auto_margin String 1. auto_margin has been opened 0, auto_margin has not been opened
Explanation

Futures and perpetual swap position/account data interface: All position/all account data, return to null if no position held; return to defaulted value for return from no single position/account data when no position/asset held.

Fixed-margin mode:

  1. Equity = user account balance + fixed-margin account balance + RPL of all contracts + UPL of all contracts

  2. Available assets = user account balance + fixed-margin account balance + RPL of all contracts - fixed margin - assets on hold

Cross-margin mode:

  1. Equity = user account balance + RPL of all contracts + UPL of all contracts

  2. Available assets = user account balance + UPL of all contracts - position margin - assets on hold

Return Sample
{
    "info":{
        "eos":{
            "contracts":[
                {
                    "available_qty":"4.44054037",
                    "fixed_balance":"0",
                    "instrument_id":"EOS-USD-181228",
                    "margin_for_unfilled":"0",
                    "margin_frozen":"0",
                    "realized_pnl":"0",
                    "unrealized_pnl":"0"
                },
                {
                    "available_qty":"4.44054037",
                    "fixed_balance":"0.46564531",
                    "instrument_id":"EOS-USD-190329",
                    "margin_for_unfilled":"0",
                    "margin_frozen":"0.46425255",
                    "realized_pnl":"-0.00139276",
                    "unrealized_pnl":"0"
                }
            ],
            "equity":"4.90479292",
            "margin_mode":"fixed",
            "total_avail_balance":"4.44054037"
        },
        "ltc":{
            "equity":"0.49598676",
            "margin":"0.035792262",
            "margin_for_unfilled":"0",
            "margin_frozen":"0.46425255",
            "margin_mode":"crossed",
            "margin_ratio":"13.8574",
            "realized_pnl":"-0.00004859",
            "total_avail_balance":"0.49604816",
            "unrealized_pnl":"-0.00001281"
        }
    }
}

Futures Account of a Currency

Get the futures account info of a token.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

GET/api/futures/v3/accounts/btc

Request Parameters
Parameters Parameters Types Required Description
currency String Yes Token, eg.“BTC”
Return Parameters
Cross_margin
Cross_marginParameters 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
margin String Margin (on hold for open orders + positions holding)
margin_frozen String Position margin
margin_for_unfilled String Margin on hold for open orders
realized_pnl String realised profit and loss
unrealized_pnl String Unrealised profit and loss
margin_ratio String Margin ratio
Fixed_margin
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 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
total_avail_balance String Balance of the account
auto_margin String 1. auto_margin has been opened 0, auto_margin has not been opened
Explanation

Futures and perpetual swap position/account data interface: All position/all account data, return to null if no position held; return to defaulted value for return from no single position/account data when no position/asset held.

Fixed-margin mode:

  1. Equity = user account balance + fixed-margin account balance + RPL of all contracts + UPL of all contracts

  2. Available assets = user account balance + fixed-margin account balance + RPL of all contracts - fixed margin - assets on hold

Cross-margin mode:

  1. Equity = user account balance + RPL of all contracts + UPL of all contracts

  2. Available assets = user account balance + UPL of all contracts - position margin - assets on hold

Return Sample
Cross_margin
{
    "margin":"0.035807641",
    "margin_mode":"crossed",
    "total_avail_balance":"0.49604816",
    "realized_pnl":"-0.00004859",
    "unrealized_pnl":"-0.0001666",
    "margin_ratio":"13.8471",
    "equity":"0.49583297"
}
Fixed_margin
{
    "margin_mode":"fixed",
    "total_avail_balance":"4.44054037",
    "contracts":[
        {
            "available_qty":"4.44054037",
            "fixed_balance":"0",
            "instrument_id":"EOS-USD-181228",
            "margin_for_unfilled":"0",
            "margin_frozen":"0",
            "realized_pnl":"0",
            "unrealized_pnl":"0"
        },
        {
            "available_qty":"4.44054037",
            "fixed_balance":"0.46564531",
            "instrument_id":"EOS-USD-190329",
            "margin_for_unfilled":"0",
            "margin_frozen":"0.46425255",
            "realized_pnl":"-0.00139276",
            "unrealized_pnl":"-0.013"
        }
    ],
    "equity":"4.89182497"
}

Get Futures Leverage

Get the leverage of the futures account

HTTP Requests

GET /api/futures/v3/accounts/<currency>/leverage

Limit: 5 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
currency String Yes Token, eg.“BTC”
Return Parameters
Cross_margin
Cross_margin Parameters Parameters Types Description
margin_mode String Account Type: crossed
currency String Token, e.g. btc
leverage String Leverage
Fixed_margin
Fixed_margin Parameters Parameters Types Description
margin_mode String Account Type: fixed
instrument_id String Contract ID, e.g.“BTC-USD-180213”
long_leverage Number Leverage for long positions
short_leverage Number Leverage for short positions
Explanation

Cross-margin mode only allows one leverage for a future. In fixed margin mode, you can pick leverage per coin per side.

Example:

Cross-magin mode: if you are holding a 10x BTC quarterly contract, then you must also use 10x leverage for opening any new BTC contracts. But you can choose 20x leverage when 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.

Return Sample
Cross_margin
{
    "leverage":10,
    "margin_mode":"crossed",
    "currency":"LTC"
}
Fixed_margin
{
    "margin_mode":"fixed",
    "EOS-USD-190329":{
        "long_leverage":10,
        "short_leverage":10
    },
    "EOS-USD-190104":{
        "long_leverage":10,
        "short_leverage":10
    },
    "EOS-USD-181228":{
        "long_leverage":10,
        "short_leverage":10
    }
}

Set Futures Leverage

Adjusting the leverage for futures account。

HTTP Requests

POST /api/futures/v3/accounts/<currency>/leverage

Limit: 5 times / 2s
Request Sample

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)

Request Parameters
Crossed_margin
Crossed_margin Parameters Parameters Types Required Description
leverage Number Yes 10x or 20x leverage
currency String Token, e.g. “btc”
Fixed_margin
Fixed_margin 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 opening side (long or short)
leverage Number Yes 10x or 20x leverage
Return Parameters
Cross_margin
Cross_margin Parameters Parameters Types Description
margin_mode String Account Type: crossed
currency String Token, e.g. “btc”
leverage Number 10x or 20x leverage
result String Return set result, Success or Error Code
Fixed_margin
Fixed_margin Parameters Parameters Types 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 Number 10x or 20x leverage
result String Return set result, Success or Error Code
Explanation

Margin mode: cross-margin, fixed-margin

Cross-margin: provide currency and leverage

Fixed-margin: provide instrument_id, side, and leverage

Cross-margin mode only allows one leverage for a future. In fixed margin mode, you can pick leverage per coin per side.

Example:

Cross-magin mode: if you are holding a 10x BTC quarterly contract, then you must also use 10x leverage for opening any new BTC contracts. But you can choose 20x leverage when 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.

Return Sample
Cross_margin
{
    "result":"true",
    "leverage":10,
    "margin_mode":"crossed",
    "currency":"LTC"
}
Fixed_margin
{
    "result":"true",
    "margin_mode":"fixed",
    "EOS-USD-181228":{
        "short":10,
        "long":10
    }
}

Bills Details

Shows the account’s historical coin in flow and out flow. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

HTTP Requests

GET /api/futures/v3/accounts/<currency>/ledger

Limit: 5 times / 2s
Request Sample

GET/api/futures/v3/accounts/btc/ledger?from=1&limit=87

Request Parameters
Parameters Parameters Types Required Description
currency String Yes Token, e.g "btc"
from Number No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to Number No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit Number No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
ledger_id String Bill ID
currency String Token, “btc”
amount String Amount
type String Type of bills
timestamp String Bill Creation Date
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”
Type Value Parameters Types Description
transfer String Funds Transfer
match String open long/open short/close long/close short
fee String fee
settlement String settlement/clawback/settle long/settle short
liquidation String force close long/force close short/deliver close long/deliver close short
Return Sample
[
    {
        "ledger_id":"2047518493474817",
        "timestamp":"2018-12-28T06:30:52.0Z",
        "amount":"-0.00139276",
        "balance":"0",
        "currency":"EOS",
        "type":"fee",
        "details":{
            "order_id":2047518485521408,
            "instrument_id":"EOS-USD-190329"
        }
    },
    {
        "ledger_id":"2047518493474816",
        "timestamp":"2018-12-28T06:30:52.0Z",
        "amount":"0",
        "balance":"1",
        "currency":"EOS",
        "type":"match",
        "details":{
            "order_id":2047518485521408,
            "instrument_id":"EOS-USD-190329"
        }
    }
]

Place an Order

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

HTTP Requests

POST /api/futures/v3/order

Limit: 40 times / 2s
Request Sample

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","leverage":"10"}

Request Parameters
Parameters Parameters Types Required Description
client_oid string No the order ID customized 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
instrument_id String Yes Contract ID,e.g. “TC-USD-180213”
type String Yes 1:open long 2:open short 3:close long 4:close short
price price Yes Price of each contract
size Number Yes The buying or selling quantity
match_price String No Order 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
leverage Number Yes 10x or 20x leverage
order_type string No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Return Parameters
Parameters Parameters Types Description
order_id String Order ID. If order placement fails, this value will be -1.
client_oid String The order ID customized by yourself
error_code Number 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.
result String Return set result, Success or Error Code
Explanation

instrument_id

Instrument_id must match a valid contract ID, Such as “BTC-USD-180213” The contract list is available through the /instrument interface.

client_oid

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 and canceled (This feature will be available on Feb 28, 2019)

type

You can specify the order type when placing order. If you are not holding any positions, you can only open long or short. You can only close the positions holding. price

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

Price is the price of buying or selling a contract. The price must be a multiple of the increment (tick_size). Increment (tick_size) is the smallest unit of price, and is available via the instrument endpoint.

order_qty

Order_qty is the number of contracts buying or selling. The value must be an integer.

match_price

Best counter party price is the best price available to fill the order at the moment. It is either the best bid / ask price on the order book.

Order Lifecycle

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 done 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.

Return Sample
{
    "client_oid":"51dfa81b01084dfdb07bd642b5bfce63",
    "error_code":0,
    "error_messsage":"",
    "order_id":"2047622606459904",
    "result":true
}

Place Multiple Orders

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

HTTP Requests

POST /api/futures/v3/orders

Limit: 20 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID, e.g.“BTC-USD-180213”
order_data List Yes the JSON word string for placing multiple orders, include:{order_type client_oid type price size match_price}
leverage Number Yes 10x or 20x leverage
client_oid string No the order ID customized by yourself ,The type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, Both uppercase and lowercase letters are supported
order_type string No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Return Parameters
Parameters Parameters Types Description
order_info String Order Details
order_id String Order ID. When failing to place an order, the value is -1
client_oid String To identify your order with the order ID set by you
error_code Int Error code; 0 for successful order; corresponding error code shows for failed order
error_message String Error code; blank for successful order; error code shows for failed order
result String Call interface returns results
Explanation

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 and canceled .(This feature will be available on Feb 28, 2019)

As long as any of the orders are successful, result returns true. The returned result data is in the same order as the order_data submission order data. If the order fails, order_id is -1, error_code is error code, and error_message is error message.

Return Sample
{
    "result":true,
    "order_info":[
        {
            "error_message":"",
            "error_code":0,
            "client_oid":"be598d8c4e9b46e0a73aa1a5285c7f90",
            "order_id":"2047624459797504"
        },
        {
            "error_message":"",
            "error_code":0,
            "client_oid":"84ce2246fd704840bb996bb52763b47d",
            "order_id":"2047624461370368"
        },
        {
            "error_message":"",
            "error_code":0,
            "client_oid":"349846b77d3744588ca41980957cba55",
            "order_id":"2047624462746624"
        }
    ]
}

Cancel an Order

Cancelling an unfilled order.

HTTP Requests

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

or

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

Limit: 40 times / 2s
Request Sample

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

or

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

Request Parameters
Parameters Parameters Types Required Description
order_id String Yes Order ID
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
client_oid string Yes 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
Return Parameters
Parameters Parameters Types Description
order_id String Order ID
result Long Order cancellation status
client_oid string the order ID created by yourself
instrument_id String instrument id

The return value is the list of canceling orders IDs. Please note that these orders are not necessarily canceled successfully. Matched orders cannot be canceled, only unmatched orders can be canceled.

Explanation

Only fill in either parameter client_oid (This feature will be available on Feb 28, 2019)or order_id

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.

The order_id is the ID generated by the server, not the self-customised client_oid.

If the order cannot be cancelled (filled or cancelled already), then the reason will be explained in the error message.

Return Sample
{
    "result":true,
    "client_oid":"2047593676229632",
    "order_id":"2047593676229632",
    "instrument_id":"LTC-USD-181228"
}

Cancel multiple Orders

With best effort, cancel all open orders.Maximum 10 orders can be cancelled at a time for each trading pair

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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]}

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes The contract of the orders to be cancelled
order_id String Yes ID's of the orders canceled
client_oids string Yes 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
instrument_id String The contract of the orders to be cancelled
order_id String Order ID
result String Call interface returns results
client_oids string the order ID created by yourself
Explanation

For bulk order cancellation, the parameters should be either all order_id or all client_oid(This feature will be available on Feb 28, 2019), otherwise it will trigger an error code.

Cancellations of orders are not guaranteed. Users are recommended to get the order list to confirm if the orders are cancelled after using this endpoint.

Return Sample
{
    "result":true,
    "client_oids":[
            "2047645297220608",
            "2047646381807616"
        ],
    "order_ids":[
        "2047645297220608",
        "2047646381807616"
    ],
    "instrument_id":"LTC-USD-181228"
}

Get Order List

List your orders. Cursor pagination is used. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

GET/api/futures/v3/orders/BTC-USD-180309?status=2&from=4&limit=87((returning the first 87 messages of page 4 of all filled orders in BTC-USD-180309))

Request Parameters
Parameters Parameters Types Required Description
status Number Yes Order Status (-1 canceled; 0: pending, 1: partially filled, 2: fully filled, 6: open (pending partially + fully filled), 7: completed (canceled + fully filled))
instrument_id String Yes Contract ID, e.g. “BTC-USD-180213”
from Number No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to Number No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit Number No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
instrument_id String Contract ID, e.g. “BTC-USD-180213”
client_oid string the order ID customised by yourself
size String Quantity
timestamp String Order creation date
filled_qty String Filled quantity
fee String Fees
order_id String Order ID
price String Order Price
price_avg String Average Price
status String Order Status (-1 canceled; 0: pending, 1: partially filled, 2: fully filled)
type String Type (1: open long 2: open short 3: close long 4: close short)
contract_val String Contract Value
leverage String Leverage value:10\20 default:10
order_type string 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
pnl string profit
Explanation

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 .

This endpoint can only provide the filled orders of the recent two days and the cancelled orders.

If the order is not filled in the order lifecycle, the record may be removed. This indicates that this order cannot be downloaded with this endpoint.

Unfilled orders’ status may change depending on the market between the time of request creation and server response.

Return Sample
{
    "result":true,
    "order_info":[
        {
            "instrument_id":"LTC-USD-181228",
            "size":"1",
            "timestamp":"2018-12-28T06:57:21.000Z",
            "filled_qty":"0",
            "fee":"0",
            "order_id":"2047622606459904",
            "price":"990000",
            "price_avg":"0",
            "status":"0",
            "order_type”:”1”,
            "type":"2",
            "contract_val":"10",
            "leverage":"10"
        }
    ]
}

Get Order Details

Get order details

HTTP Requests

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

or

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

Limit: 40 times / 2s
Request Sample

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

or

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

Request Parameters
Parameters Parameters Types Required Description
order_id String Yes Order ID
instrument_id String Yes Contract ID,e.g.“BTC-USD-180213”
client_oid string Yes 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
instrument_id String Contract ID, e,g. “BTC-USD-180213”
size String Quantity
timestamp String Order creation date
filled_qty String Filled quantity
fee String Fees
order_id String Order ID
price String Order Price
price_avg String Average Price
status String Order Status (-1 canceled; 0: pending, 1: partially filled, 2: fully filled)
type String Type (1: open long 2: open short 3: close long 4: close short)
contract_val String Contract Value
leverage String Leverage value:10\20 default:10
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
pnl string profit
Explanation

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 .(This feature will be available on Feb 28, 2019)

Only fill in either parameter client_oid or order_id

This endpoint can only provide the filled orders of the recent two days and the cancelled orders.

If the order is not filled in the order lifecycle, the record may be removed. This indicates that this order cannot be downloaded with this endpoint.

Unfilled orders’ status may change depending on the market between the time of request creation and server response.

Return Sample
{
    "leverage":"10",
    "size":"1",
    "filled_qty":"0",
    "price":"990000",
    "fee":"0",
    "contract_val":"10",
    "price_avg":"0",
    "type":"2",
    "order_type”:”1”,
    "instrument_id":"LTC-USD-181228",
    "order_id":"2047622606459904",
    "timestamp":"2018-12-28T06:57:21.000Z",
    "status":"0"
}

Get Transaction Details

Get details of the recent filled orders. Cursor pagination is used. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

HTTP Requests

GET /api/futures/v3/fills

Limit: 20 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
order_id String Yes List all transaction details of this order_id. All values will be returned by default
instrument_id String Yes List all transaction details of this instrument_id. All values will be returned by default
from Int No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to Int No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit Int No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
trade_id String Bill ID
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 Order creation time
exec_type String Taker or Maker (T or M)
fee String Fees
side String Side of order(buy or sell)
Explanation

Fees

The fee levied in the transactions

Liquidity

The order is created by maker or taker. (M=Maker, T=Taker)

Pagination

Ledger_id are listed in a descending order, from biggest to smallest. The first ledger_id can be found under OK-FROM, so it would be easier to acquire a larger ledger_id (new bills) by using OK-FROM in the future.

Return Sample
[
    {
        "trade_id":"2047624468856838",
        "instrument_id":"LTC-USD-181228",
        "price":"27.942",
        "order_qty":"1",
        "order_id":"2047624459797504",
        "created_at":"2018-12-28T06:57:49.0Z",
        "exec_type":"T",
        "fee":"-0.00010737",
        "side":"sell"
    }
]

Get Contract Information

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

HTTP Requests

GET /api/futures/v3/instruments

Limit: 20 times / 2s
Request Sample

GET /api/futures/v3/instruments

Return Parameters
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 Int Contract value (USD)
listing String Listing date
delivery String Delivery date
tick_size Double Order price accuracy
trade_increment Int Order quantity accuracy
alias String this_week next_week quarter
Explanation

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.

The trade increment is the smallest unit of quantity. If the trade increment is 1, entering a quantity of 1.21 will be adjusted back to 1 instead. The trade increment value of a contract is 1.

Return Sample
[
    {
        "contract_val":100,
        "delivery":"2018-10-26",
        "instrument_id":"BTC-USD-181026",
        "listing":"2018-10-12",
        "quote_currency":"USD",
        "tick_size":0.01,
        "trade_increment":1,
        "underlying_index":"BTC"
    },
    {
        "contract_val":100,
        "delivery":"2018-11-02",
        "instrument_id":"BTC-USD-181102",
        "listing":"2018-10-19",
        "quote_currency":"USD",
        "tick_size":0.01,
        "trade_increment":1,
        "underlying_index":"BTC"
    },
]

Get Order Book

List all contracts. This request does not support pagination. The full list will be returned for a request.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
size Int No The size of the price range (max: 200)
Return Parameters

[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 orderbook.

Explanation

Aggregation is the merging of prices into different price ranges on the order book.

Return Sample
{
    "asks":[
        [
            5.33,
            416,
            0,
            1
        ],
        [
            5.332,
            946,
            0,
            13
        ]
    ],
    "bids":[
        [
            5.329,
            708,
            0,
            12
        ],
        [
            5.328,
            277,
            0,
            13
        ]
    ],
    "timestamp":"2018-10-19T10:56:03.758Z"
}

Get All Tokens Information

Get the last traded price, best bid/ask price, 24 hour trading volume and more info of all contracts.

HTTP Requests

GET /api/futures/v3/instruments/ticker

Limit: 20 times / 2s
Request Sample

GET /api/futures/v3/instruments/ticker

Return Parameters
Parameters Parameters Types Description
instrument_id String Contract ID,e.g. “BTC-USD-180213”
last Double Last traded price
best_ask Double Best ask price
best_bid Double Best bid price
high_24h Double 24 hour high
low_24h Double 24 hour low
volume_24h Int 24 hour trading volume (contracts)
timestamp String Timestamp
Explanation

The high, low and trading volume are all computed based on the data in the last 24 hours.

Return Sample
{
    "best_ask":5.333,
    "best_bid":5.332,
    "high_24h":5.376,
    "instrument_id":"EOS-USD-181026",
    "last":5.333,
    "low_24h":5.245,
    "timestamp":"2018-10-19T10:44:41.570Z",
    "volume_24h":3894872
}

Get Information of a Token

Get the last traded price, best bid/ask price, 24 hour trading volume and more info of a contract.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
Return Parameters
Parameters Parameters Description
instrument_id String Contract ID,e.g. “BTC-USD-180213”
last Price Last traded price
best_ask Price Best ask price
best_bid Price Best bid price
high_24h Price 24 hour high
low_24h Price 24 hour low
volume_24h Number 24 hour trading volume (contracts)
timestamp String Timestamp
Explanation

The high, low and trading volume are all computed based on the data in the last 24 hours.

Return Sample
{
    "best_ask":5.367,
    "best_bid":5.366,
    "high_24h":5.46,
    "instrument_id":"EOS-USD-181026",
    "last":5.366,
    "low_24h":5.352,
    "timestamp":"2018-10-23T10:59:59.884Z",
    "volume_24h":9009474
}

Get Filled Orders Data

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

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
from Int No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to Int No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit Int No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
timestamp String Filled time
trade_id String Transaction time ID
price Double Filled price
qty Int Filled size
side String Filled side
Explanation

The filled side is the order side of the Taker. Taker is the one who actively take the order on the book. Buying indicates the taker is taking liquidity from the book, so the price is rising. While selling indicates the price is falling.

trade_id is the increasing ID of the filled orders (could be incomplete).

Return Sample
[
    {
        "price":5.328,
        "qty":62,
        "side":"sell",
        "timestamp":"2018-10-19T10:53:27.561Z",
        "trade_id":"1652189269622792"
    },
    {
        "price":5.328,
        "qty":4,
        "side":"buy",
        "timestamp":"2018-10-19T10:53:35.932Z",
        "trade_id":"1652189818159105"
    },
    {
        "price":5.329,
        "qty":4,
        "side":"buy",
        "timestamp":"2018-10-19T10:53:37.769Z",
        "trade_id":"1652189938679821"
    }
]

Get Market Data

Get the charts of the trading pairs. Charts are returned in grouped buckets based on requested granularity.

HTTP Requests

GET /api/futures/v3/instruments/<instrument-id>/candles

Limit: 20 times / 2s
Request Sample

GET/api/futures/v3/instruments/BTC-USD-180309/candles?start=2018-06-20T02:31:00Z&end=2018-06-20T02:55:00Z&granularity=60

Request 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(For example:2018-06-20T02:31:00Z)
end String No End time in ISO 8601(For example:2018-06-20T02:31:00Z)
granularity Number No Desired time slice in seconds[60/180/300 900/1800/3600/7200/14400/21600/43200/86400/604800]
Return Parameters
Parameters Parameters Types Description
time Date timestamp
open Price Open price
high Price Highest price
low Price Lowest price
close Price Close price
volume Number Trading volume
currency_volume Number The trading volume in a specific token
Explanation

If either one of the start or end fields are not provided then both fields will be ignored. If a custom time range is not declared then one ending now is selected.

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 one minute, three minutes, five minutes, fifteen minutes, thirty minutes, one hour, two hours, six hours, twelve hours, one day, and 1 week respectively.

The chart data may be incomplete and should not be polled. Please use WebSocket if you need real-time data.

The maximum number of data points for a single request is 300 candles. If your selection of start/end time and granularity will result in more than 300 data points, your request will be rejected. If you wish to retrieve fine granularity data over a larger time range, you will need to make multiple requests with new start/end ranges.

Return Sample
[["2018-12-09T08:40:00.000Z","5.425","5.426","5.423","5.424","3364.0","6201.95008788"],["2018-12-09T08:40:00.000Z","5.424","5.424","5.421","5.422","3152.0","5812.78855111"]]

Get Hold Amount

Get the number 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.00000102",
    "instrument_id":"LTC-USD-181228",
    "timestamp":"2018-12-28T07:40:02.874Z"
}

Get Indices

Get Indices of tokens. This is a public endpoint, no identity verification is needed.

HTTP Requests

GET/api/futures/v3/instruments//index

Limit: 20 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Index, e.g. “BTC-USD”
Return Parameters
Parameters Parameters Types Description
instrument_id String Index, e.g.“BTC-USD”
index String Index price
timestamp String Timestamp
Explanation

The token displayed is the quote currency of the index.

Return Sample
{
    "index":5.331,
    "instrument_id":"EOS-USD-181026",
    "timestamp":"2018-10-23T09:18:11.192Z"
}

Get Exchange Rates

Get the fiat exchange rates. This is a public endpoint, no identity verification is needed.

HTTP Requests

GET /api/futures/v3/rate

Limit: 20 times / 2s
Request Sample

GET /api/futures/v3/rate

Return Parameters
Parameters Parameters Types Description
instrument_id String Contract ID, e.g. “BTC-USD-180213”
rate String Exchange rates
timestamp String Timestamp
Return Sample
{
    "instrument_id":"USD_CNY",
    "rate":"6.899",
    "timestamp":"2018-12-10T07:17:49.556Z"
}

Get 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 Number Estimated delivery price
timestamp String Timestamp
Return Sample
{
    "instrument_id":"EOS-USD-181026",
    "settlement_price":0,
    "timestamp":"2018-10-23T10:07:44.095Z"
}

Get Open Interests

Get the open interest of a contract. This is a public endpoint, no identity verification is needed.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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

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 Number Total open interest
timestamp String Timestamp
Return Sample
{
    "amount":1461063,
    "instrument_id":"EOS-USD-181026",
    "timestamp":"2018-10-23T11:01:37.301Z"
}

Get Current Price Limit

The maximum buying price and the minimum selling price of the contract. This is a public endpoint, no identity verification is needed.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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

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”
highest Double Maximum buying price
lowest Double Minimum selling price
timestamp String Timestamp
Return Sample
{
     "highest":5.487,
     "instrument_id":"EOS-USD-181026",
     "lowest":5.168,
     "timestamp":"2018-10-19T10:55:28.569Z"
 }

Get Current Mark Price

The maximum buying price and the minimum selling price of the contract. This is a public endpoint, no identity verification is needed.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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

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”
highest Double Maximum buying price
lowest Double Minimum selling price
timestamp String Timestamp
Return Sample
{
     "highest":5.487,
     "instrument_id":"EOS-USD-181026",
     "lowest":5.168,
     "timestamp":"2018-10-19T10:55:28.569Z"
 }

Get Force-Liquidated Orders

Get force liquidated orders. This is a public endpoint, no identity verification is needed.

HTTP Requests

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

Limit: 20 times / 2s
Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes Contract ID,e.g. “BTC-USD-180213”
status String No Status (0:unfilled orders in the recent 7 days 1:filled orders in the recent 7 days)
from Number No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to Number No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit Number No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
instrument_id String Contract ID,e.g. “BTC-USD-180213”
size Number Quantity
created_at Date Order creation time
loss Number User loss
price Price Order price
type Number Order type(3:close long 4:close short)
Return Sample
[
    {
        "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
    }
]

Get 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 Double 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":3917.39,
    "instrument_id":"BTC-USD-190329",
    "timestamp":"2019-01-09T09:07:47.681Z"
}

Error Code

Error Code Sample
Business Error Messages Business Error Codes http Status Code Scenarios
futures account suspended 32001 400 when the futures account is suspended
futures account does not exist 32002 400 when futures trading is not enabled for the account
canceling, please wait 32003 400 when the user execute other operations during order cancellation
you have no unfilled orders 32004 400 when the user check the unfilled orders
max order quantity 32005 400 when the user placed an order exceeding the quantity limit
the order price or trigger price exceeds USD 1 million 32006 400 when the user placed and order with price or trigger price over USD 1 million
leverage level must be the same for orders on the same side of the contract 32007 400 when the user has open positions with 10x leverage and trying to open a 20x leverage order
Max. positions to open (cross margin) 32008 400 when the order quantity is larger than the availability (cross margin)
Max. positions to open (fixed margin) 32009 400 when the order quantity is larger than the availability fixed margin)
leverage cannot be changed with open positions 32010 400 if an user holds a short position with 10x leverage, he/she will not be able to change the leverage to 20x
futures status error 32011 400 contract expired
futures order update error 32012 400 updating the status of a canceled order
token type is blank 32013 400 token type is blank
your number of contracts closing is larger than the number of contracts available 32014 400 your number of contracts closing is larger than the number of contracts available
margin ratio is lower than 100% before opening positions 32015 400 margin ratio is lower than 100% before opening positions
margin ratio is lower than 100% after opening position 32016 400 margin ratio is lower than 100% after opening position
no BBO 32017 400 no BBO
the order quantity is less than 1, please try again 32018 400 the order quantity is less than 1, please try again
the order price deviates from the price of the previous minute by more than 3% 32019 400 the order price deviates from the price of the previous minute by more than 3%
the price is not in the range of the price limit 32020 400 the price is not in the range of the price limit
leverage error 32021 400 leverage is not set as 10x or 20x
this function is not supported in your country or region according to the regulations 32022 400 futures trading not supported in certain regions
this account has outstanding loan 32023 400 this account has outstanding loan
order cannot be placed during delivery 32024 400 order placement failure during delivery
order cannot be placed during settlement 32025 400 order placement failure during settlement
your account is restricted from opening positions 32026 400 restricted from opening position
order info does not exist 32029 400 order has been canceled already
account is suspended and liquidated 32028 400 account is suspended and liquidated
cancelled over 20 orders 32027 400 order cancellation limit reached
Number of commission over 1 million 32045 400 Number of commission over 1 million
Each user can hold up to 10 trade plans at the same time 32046 400 Each user can hold up to 10 trade plans at the same time
system error 32047 400 system error
Order strategy track range error 32048 400 Order strategy track range error
Each user can hold up to 10 track plans at the same time 32049 400 Each user can hold up to 10 track plans at the same time
Order strategy rang error 32050 400 Order strategy rang error
Order strategy ice depth error 32051 400 Order strategy ice depth error
Number of commission over 100 thousand 32052 400 Number of commission over 100 thousand
Each user can hold up to 6 ice plans at the same time 32053 400 Each user can hold up to 6 ice plans at the same time
The order price is zero. Market-close-all function cannot be executed 32057 400 The order price is zero. Market-close-all function cannot be executed
Trade not allow 32054 400 Trade not allow
cancel order error 32055 400 cancel order error
iceberg per order average should between {0}-{1} contracts 32056 400 iceberg per order average should between {0}-{1} contracts
Each user can hold up to 6 initiative plans at the same time 32058 400 Each user can hold up to 6 initiative plans at the same time
Total amount should exceed per order amount 32059 400 Total amount should exceed per order amount
Order strategy type error 32060 400 Order strategy type error
Order strategy initiative limit error 32061 400 Order strategy initiative limit error
Order strategy initiative range error 32062 400 Order strategy initiative range error
Order strategy initiative rate error 32063 400 Order strategy initiative rate error
Time interval of orders should set between 5-120s 32064 400 Time interval of orders should set between 5-120s

Perpetual Swap API

Market data, account info, order operations, order enquiry, bills enquiry of perpetual swap.

Perpetual Swap Positions

Get the information of all holding positions in swap trading.Due to high energy consumption, you are advised to capture data with the "Swap Account of a Currency" API instead.

Rate limit:1/10s
HTTP Requests

GET /api/swap/v3/position

Request Sample

GET/api/swap/v3/position

Return Parameters

Cross_margin
Cross_marginParameters 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 PnL
side String Side
timestamp String Creation time
Fixed_margin
Fixed_marginParameters 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 PnL
side String Side
timestamp String Creation time
Return Sample
[
    {
        "margin_mode":"fixed",
        "holding":[
            {
                "avail_position":"20",
                "avg_cost":"3549.4",
                "instrument_id":"BTC-USD-SWAP",
                "leverage":"50",
                "liquidation_price":"3711.5",
                "margin":"0.0210",
                "position":"20",
                "realized_pnl":"0.0000",
                "settlement_price":"3589.3",
                "side":"short",
                "timestamp":"2019-01-16T00:23:24.841Z"
            }
        ]
    },
    {
        "margin_mode":"crossed",
        "holding":[

        ]
    }
]

Perpetual Swap Positions of a Contract

Get the information of holding positions of a contract.

Rate limit:20/2s

HTTP Requests

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

Request Sample

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

Request Parameters

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

Return Parameters

Cross_margin
Cross_marginParameters 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 PnL
side String Side
timestamp String Last margin adjusting time
Fixed_margin
Fixed_marginParameters 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 PnL
side String Side
timestamp String Last margin adjusting time
Return Sample
Cross_margin
{

"margin_mode": "crossed",

"holding": [

{

"liquidation_price": "0.07",

"position": "1",

"avail_position": "1",

"avg_cost": "210.24",

"settlement_price": "210.34",

"instrument_id": "BTC-USD-SWAP",

"leverage": "10",

"realized_pnl": "0.00307096",

"side": "short",

"timestamp": "2018-10-17T20:11:00.443Z"

},
]
}
Fixed_margin
{

"margin_mode": "fixed",

 "holding": [

{

"liquidation_price": "0.05",

"position": "5",

"avail_position": "5",

"margin": "1.27832803",

"avg_cost": "210.32123263",

"settlement_price": "215.34252134",

"instrument_id": "BTC-USD-SWAP",

"leverage": "10",

"realized_pnl": "0.00307096",

"side": "long",

"timestamp": "2018-10-17T20:11:00.443Z"

},

{

"liquidation_price": "0.05",

"position": "5",

"avail_position": "5",

"margin": "1.27832803",

"avg_cost": "210.32123263",

"settlement_price": "215.34252134",

"instrument_id": "BTC-USD-SWAP",

"leverage": "10",

"realized_pnl": "0.00307096",

"side": "short",

"timestamp": "2018-10-17T20:11:00.443Z"

}
]
}

Perpetual Swap Account of all Currency

Get the perpetual swap account info of all tokens. Margin ratio set as 10,000 when users have no open position.

Rate limit:1/10s

HTTP Requests

GET /api/swap/v3/accounts

Request Sample

GET /api/swap/v3/accounts

Return Parameters

Parameters Type Description
equity String Equity of the account
total_avail_balance String Balance of the 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

Explanation

Futures and perpetual swap position/account data interface: All position/all account data, return to null if no position held; return to defaulted value for return from no single position/account data when no position/asset held.

Fixed-margin mode:

Equity = user account balance + fixed-margin account balance + RPL of all contracts + UPL of all contracts

Cross-margin mode:

Equity = user account balance + RPL of all contracts + UPL of all contracts

Return Sample

{

 "info": [

{

"equity": "1",

"fixed_balance": "50",

"total_avail_balance": "88.23567432",

"margin": "0",

"realized_pnl": "0.00307096",

"unrealized_pnl": "0.46",

"margin_ratio": "0.23435632",

"instrument_id": "BTC-USD-SWAP",

"margin_frozen": "0",

"timestamp": "2018-10-17T20:11:443Z",

"margin_mode": "fixed"

},
]
}

Perpetual Swap Account of a Currency

Get the perpetual swap account info of a token. Margin ratio set as 10,000 when users have no open position.

Rate limit:20/2s

HTTP Requests

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

Request Sample

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

Request Parameters

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

Return Parameters

Parameters Type Description
equity String Equity of the account
total_avail_balance String Balance of the 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

Explanation

Futures and perpetual swap position/account data interface: All position/all account data, return to null if no position held; return to defaulted value for return from no single position/account data when no position/asset held.

Fixed-margin mode:

Equity = user account balance + fixed-margin account balance + RPL of all contracts + UPL of all contracts

Cross-margin mode:

Equity = user account balance + RPL of all contracts + UPL of all contracts

Return Sample

{

 "info": 

{

"equity": "1",

"fixed_balance": "50",

"total_avail_balance": "88.23567432",

"margin": "0",

"realized_pnl": "0.00307096",

"unrealized_pnl": "0.46",

"margin_ratio": "0.23435632",

"instrument_id": "BTC-USD-SWAP",

"margin_frozen": "0",

"timestamp": "2018-10-17T20:11:00.443Z",

"margin_mode": "fixed"

}
}

Get Account Settings of a Contract

Get leverage level and margin mode of a contract.

Rate limit:5/2s

HTTP Requests

GET /api/swap/v3/accounts/<instrument_id>/settings

Request Sample

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

Request Parameters

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

Return Parameters

Parameters Type Description
long_leverage Number Leverage level for long positions
margin_mode String Margin mode
short_leverage Number Leverage level for short positions
instrument_id String Contract ID

Explanation

Cross-margin mode only allows one leverage for a future. In fixed margin mode, you can pick leverage per coin per side.

Return Sample

{

"long_leverage": 10,

"margin_mode": "crossed",

"short_leverage": 10,

"instrument_id": "BTC-USD-SWAP"

}

Set Leverage Level of a Contract

Setting the leverage level of a contract

Rate limit:5/2s

HTTP Requests

POST /api/swap/v3/accounts/<instrument_id>/leverage

Request Sample

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

Request 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 Side: 1.FIXED-LONG 2.FIXED-SHORT 3.CROSSED

Return Parameters

Parameters Type Description
long_leverage Number Leverage level for long positions
margin_mode String Margin mode
short_leverage Number Leverage level for short positions
instrument_id String Contract ID

Return Sample

{

"long_leverage": 10,

"margin_mode": "fixed",

"short_leverage": 20,

"instrument_id": "BTC-USD-SWAP"

}

Bills Details

Shows the account’s historical coin in flow and out flow. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

Rate limit:5/2s

HTTP Requests

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

Request Sample

GET /api/swap/v3/accounts/BTC-USD-SWAP/ledger?from=2&limit=30

Note: from=2&limit=30 indicates the request of 30 strings of data on page 2. The result will be the 30 recent strings of data on page 2

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
from String No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to String No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit String No Number of results per request. Maximum 100. (default 100)

Return Parameters

Parameters Type Description
ledger_id String Bill id
amount String Amount change
type String Type
fee String Fee
timestamp String Bill creation time
instrument_id String Contract ID

| Type | 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 |

Return Sample

[

{

"ledger_id": "234",

"amount": "-0.0011",

"type": "14",

"fee": "0.00432458",

"timestamp": "2018-10-17T20:11:443Z",

"instrument_id": "BTC-USD-SWAP"

},
]

Place an Order

OKEx perpetual swap trading only supports limit orders,USD as quote currency for orders. You can place an order only if you have enough funds. Once your order is placed, the amount will be put on hold in the order lifecycle. The assets and amount on hold depends on the order's specific type and parameters.

USD as quote currency for orders

Rate limit:40/2s

HTTP Requests

POST /api/swap/v3/order

Request Sample

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"}

Request Parameters

Parameters Type Required Description
client_oid String No [optional]the order ID customized by yourself. 1-32 with digits and letter,The type of client_oid should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters,Both uppercase and lowercase letters 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 Order at best counter party price? (0:no 1:yes)
price String Yes Price of each contract
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
order_type string No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel

Request Parameters verification: Instrument_id must match a valid contract ID; Price must meet the order filled price requirements (no premium and not reaching liquidation price); Types other than 1:open long 2:open short 3:close long 4:close short will trigger an error code; Size cannot be lower than 0 and cannot be larger than available contract size.

Return Parameters

Parameters Type Description
order_id String String Order ID. If order placement fails, this value will be -1
client_oid String The order ID customized by yourself
error_code String Number 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.
result String Return set result, Success or Error Code

Explanation

instrument_id

Instrument_id must match a valid contract ID, Such as “BTC-USD-180213” The contract list is available through the /instrument interface.

client_oid

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 and canceled

The client_oid is different than the server-assigned order id. If you are consuming the public feed and see a received message with your client_oid, you should record the server-assigned order_id as it will be used for future order status updates. The client_oid will NOT be used after the received message is sent.

type

You can specify the order type when placing order. If you are not holding any positions, you can only open long or short. You can only close the positions holding. price

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

Price is the price of buying or selling a contract. The price must be a multiple of the increment (tick_size). Increment (tick_size) is the smallest unit of price, and is available via the instrument endpoint.

order_qty

Order_qty is the number of contracts buying or selling. The value must be an integer.

match_price

Best counter party price is the best price available to fill the order at the moment. It is either the best bid / ask price on the order book.

Order Lifecycle

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 done 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.

Return Sample

{

"order_id": "64-2b-17122f911-0",

"client_oid": "12233456",

"error_code": "0",

"error_message": "",

"result": "true"

}

Place Multiple Orders

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

Rate limit:20/2s

HTTP Requests

POST /api/swap/v3/orders

Request Sample

POST /api/swap/v3/orders{"instrument_id": "BTC-USD-SWAP","order_data":[{"client_oid": "s213","price": "5","size": "2","type": "1","order_type”:”1”,"match_price": "0"},{"client_oid": "E243","price": "2","size": "3","type":"2","order_type”:”1”,"match_price": "1"}]}

Request Parameters

Parameters Type Required Description
order_data List Yes the JSON word string for placing multiple orders e.g.:[{"order_type":"0","client_oid": "E213","price": "5","size": "2","type": "1","match_price": "0"},{"client_oid": "243","price": "2","size": "3","type": "2","match_price": "1"}] Maximum size is 20
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
order_type string No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel

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

Return Parameters

Parameters Type Description
order_id String Order ID. When failing to place an order, the value is -1
client_oid String To identify your order with the order ID set by you
error_code String Error code; 0 for successful order; corresponding error code shows for failed order
error_message String Error code; blank for successful order; error code shows for failed order
result String Call interface returns results

Explanation

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 and canceled .

The returned value is the order ID list of orders to be canceled, instead of orders canceled. Orders filled cannot be canceled, orders unfilled can be canceled. The returned result data is in the same order as the order_data submission order data. If the order fails, order_id is -1, error_code is error code, and error_message is error message.

Return Sample

{

 "order_info": [

{

"order_id": "64-2b-17122f911-3",

"client_oid": "12233456",

"error_code": "0",

"error_message": ""

},

{

"order_id": "64-2c-17132f711-0",

"client_oid": "12453456",

"error_code": "0",

"error_message": ""

}

],

"result": "true"

}

Cancel an Order

Cancelling an unfilled order.

Rate limit:40/2s

HTTP Requests

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

or

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

Request Sample

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

or

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

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
client_oid string yes 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 yes order ID

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

Return Parameters

Parameters Type Description
order_id String Order id
result String Call interface returns results

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.

The order_id is the ID generated by the server, not the self-customised client_oid.

If the order cannot be cancelled (filled or cancelled already), then the reason will be explained in the error message.

Return Sample

{

"order_id": "64-2b-17122f911-0",

"result": "true"

}

Cancel multiple open orders

Cancel multiple open orders with order_id,Maximum 10 orders can be cancelled at a time for each trading pair

Rate limit:20/2s

HTTP Requests

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

Request Sample

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"]}

Request Parameters

Parameters Type Required Description
ids String Yes Order ID list
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
client_oids string Yes The client_oid type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported

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

Return Parameters

Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
ids String Order ID list
result String Call interface returns results

Return Parameters

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.

The returned value is the order ID list of orders to be canceled, instead of orders canceled. Orders filled cannot be canceled, orders unfilled can be canceled.

Explanation

Cancellations of orders are not guaranteed. Users are recommended to get the order list to confirm if the orders are cancelled after using this endpoint.

Return Sample

{

"instrument_id": "BTC-USD-SWAP",
"client_oids": ["abcde"],

 "ids": [

"64-2a-17122d911-0",

"64-2b-17124f911-0",

"64-2c-17126f911-0"

],

"result": "true"

}

Get Order List

List your orders.

Rate limit:20/2s

HTTP Requests

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

Request Sample

GET /api/swap/v3/orders/BTC-USD-SWAP?status=2&from=4&limit=30

Request Parameters

Parameters Type Required Description
status String Yes List the status of all orders(-2: failed -1: canceled 0: open 1: partially filled 2: fully filled 6: open (pending partially + fully filled), 7: completed (canceled + fully filled))
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
from String No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to String No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit String No Number of results per request. Maximum 100. (default 100)

Return 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 ID
price String Order price
price_avg String Average price
status String order status (-2: failed -1: canceled 0: open 1: partially filled 2: fully filled)
type String 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
Explanation

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 .

Return Sample

{

 "order_info": [

{

"instrument_id": "BTC-USD-SWAP",

"size": "5",

"timestamp": "2018-10-23T20:11:00.443Z",

"filled_qty": "2",

"fee": "0.00432458",

"order_type”:”1”,

"order_id": "64-2b-16122f931-3",

"price": "25",

"price_avg": "21",

"status": "1",

"type": "1",

"contract_val": "100"

},

{

"instrument_id": "BTC-USD-SWAP",

"size": "10",

"timestamp": "2018-10-23T20:11:00.443Z",

"filled_position": "3",

"fee": "0.00434457"

"order_id": "64-2a-26132f931-3",

"price": "20",

"price_avg": "17",

"status": "1",

"type": "1",

"contract_val": "100"

}
]
}

Get Order Details

Get order details by order ID.

Rate limit:40/2s

HTTP Requests

GET /api/swap/v3/orders/<instrument_id>/<order_id>

OR

GET /api/swap/v3/orders/<instrument_id>/<client_oid>

Request Sample

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

OR

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

Request 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 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 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 ID
price String Order price
price_avg String Average price
status String order status (-2: failed -1: canceled 0: open 1: partially filled 2: fully filled)
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
Explanation

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 .

Return Sample

{

"instrument_id": "BTC-USD-SWAP",

"size": "10",

"timestamp": "2018-10-23T20:11:00.443Z",

"filled_qty": "3",

"fee": "0.00434457"

"order_id": "64-2a-26132f931-3",

"order_type”:”1”,

"price": "20",

"price_avg": "17",

"status": "1",

"type": "1",

"contract_val": "100"

}

Get Transaction Details

Get details of the recent filled orders

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/fills

Request Sample

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

Request Parameters

Parameters Type Required Description
order_id String Yes Order ID
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
from String No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to String No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit String No Number of results per request. Maximum 100. (default 100)

Return Parameters

Parameters Type Description
trade_id String Filled Order ID
instrument_id String Contract ID, e.g. BTC-USD-SWAP
order_id String Order ID
price String Filled price
order_qty String Filled quantity
fee String Fees
timestamp String Creation time
exec_type String Type, T:taker M:maker
side String Order side

Return Sample

[

{

"trade_id": "434365",

"instrument_id": "BTC-USD-SWAP",

"order_id": "64-2b-16122f931-3",

"price": "25",

"order_qty": "20",

"fee": "0.00432458",

"timestamp": "2018-10-24T20:11:00.443Z",

"exec_type": "T",

"side": "long"

},

{

"trade_id": "372795",

"instrument_id": "BTC-USD-SWAP",

"order_id": "64-2b-16122f931-3",

"price": "20",

"order_position": "2",

"fee": "0.00132458",

"timestamp": "2018-10-23T20:11:00.443Z",

"exec_type": "T",

"side": "long"

}
]

Get 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": "BTC-USD-SWAP",

"underlying_index": "BTC",

"quote_currency": "USD",

"coin": "BTC",

"contract_val": "100",

"listing": "2018-10-23T20:11:00.443Z",

"delivery": "2018-10-24T20:11:00.443Z",

"size_increment": "4",

"tick_size": "4"

},

{

"instrument_id": "LTC-USD-SWAP",

"underlying_index": "LTC",

"quote_currency": "USD",

"coin": "LTC",

"contract_val": "10",

"listing": "2018-10-23T20:11:00.443Z",

"delivery": "2018-10-24T20:11:00.443Z",

"size_increment": "4",

"tick_size": "4"

}
]

Get Order Book

Get the charts of the trading pairs.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/depth

Request Sample

GET /api/swap/v3/instruments/<instrument_id>/depth?size=50

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
size String No Quantity returned, Max: 200, so the depth of both the buying and selling side is 40 strings.

Contract name will be verified. If the name differs from database, error code will be triggered.

When size is left blank, 1 string will be returned. If size is 0, 9 string will be returned. If size is larger than 200, only 200 strings will be returned.

Return Parameters

Parameters Type Description
asks String Selling side
bids String Buying side
timestamp String System time stamp

Explanation

[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 orderbook.

Return Sample

{

"asks": [

["411.3","16",5,4],

["411.5","9",4,3],

["411.6","22",6,2],

[411.75,11,9,4],

[411.8,10,8,4],

],

"bids": [

[410.65,10,8,4],

[410.64,11,9,4],

[410.5,22,6,2],

[410.3,9,4,3],

[410.18,16,5,4],

],

"timestamp": "2018-10-24T20:11:11.443Z"

}

Get All Tokens Information

Get the last traded price, best bid/ask price, 24 hour trading volume and more info of all contracts.

Rate limit: 20/2s

HTTP Requests

GET /api/swap/v3/instruments/ticker

Request Sample

GET /api/swap/v3/instruments/ticker

Return Parameters

Parameters Type Description
instrument_id String Contract ID, e.g. BTC-USD-SWAP
best_ask String best ask
best_bid String best bid
last String Last traded price
high_24h String 24 hour high
low_24h String 24 hour low
volume_24h String 24 hour trading volume
timestamp String Timestamp

Explanation

The high, low and trading volume are all computed based on the data in the last 24 hours.

Return Sample

[
{

"instrument_id": "BTC-USD-SWAP",

"last": 6212.2,

"high_24h": 6239.3,

"low_24h": 6100.6,

"best_bid": "333.98",

"best_ask": "333.99",

"volume_24h": 34654,

"timestamp": "2018-10-24T20:11:20.443Z"

},

{

"instrument_id": "LTC-USD-SWAP",

"best_bid": "333.98",

"best_ask": "333.99",

"last": 402.2,

"high_24h": 439.3,

"low_24h": 400.6,

"volume_24h": 34654,

"timestamp": "2018-10-24T20:11:30.443Z"

}
]

Get Information of a Token

Get the last traded price, best bid/ask price, 24 hour trading volume and more info of a contract.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/ticker

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/ticker

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
last String Last traded price
best_bid string best bid price
best_ask string best ask price
high_24h String 24 hour high
low_24h String 24 hour low
volume_24h String 24 hour trading volume
timestamp String Time stamp

Explanation

The high, low and trading volume are all computed based on the data in the last 24 hours.

Return Sample

{

"last": 6212.2,
"best_bid": "333.98",

"best_ask": "333.99",

"high_24h": 6239.3,

"low_24h": 6100.6,

"volume_24h": 457864,

"timestamp": "2018-10-24T20:11:443Z"

}

Get Filled Orders Data

Get all filled orders record.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/trades

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/trades?from=1&limit=50

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
from Number No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to Number No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
limit Number 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. If both to and from is received by the system, from prevails.

Return Parameters

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

Explanation

The filled side is the order side of the Taker. Taker is the one who actively take the order on the book. Buying indicates the taker is taking liquidity from the book, so the price is rising. While selling indicates the price is falling.

Get the recent 300 transactions of all contracts.

Return Sample

[

{

"trade_id": "199",

"price": 25,

"size": 12,

"side": "buy",

"timestamp": "2018-10-24T20:11:443Z"

},

{

"trade_id": "200",

"price": 25,

"size": 3,

"side": "sell",

"timestamp": "2018-10-24T20:11:443Z"

}
]

Get Market Data

Get the charts of the trading pairs.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/candles

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/candles?start=2018-10-26T02:31:00.000Z&end=2018-10-26T02:55:00.000Z&granularity=60(Get the 1 minute chart of BTC-USD-SWAP from 02:31 Oct 26, 2018 to 02:55 Oct 26, 2018)

Request 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]

Contract name will be verified. If the name differs from database, error code will be triggered.

Start and end must be in ISO 8601, otherwise error code will be triggered.

Granularity must be the desired time slice in secondes (as mentioned above) , otherwise error code will be triggered.

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 in a specific token

Explanation

If either one of the start or end fields are not provided then both fields will be ignored. If a custom time range is not declared then one ending now is selected.

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 one minute, three minutes, five minutes, fifteen minutes, thirty minutes, one hour, two hours, six hours, twelve hours, one day, and 1 week respectively.

The chart data may be incomplete and should not be polled. Please use WebSocket if you need real-time data.

The maximum number of data points for a single request is 200 candles. If your selection of start/end time and granularity will result in more than 200 data points, your request will be rejected. If you wish to retrieve fine granularity data over a larger time range, you will need to make multiple requests with new start/end ranges.

The data returned will be arranged as below:

[timestamp,open,high,low,close,volume,currency_volume]

Return Sample

[

["2018-10-26T02:31:00.000","0.276","0.475","0.382","0.453","500","18.2754"],

["2018-10-26T02:31:00.000","1.568","1.324","1.375","1.456","600","20.2644"],

["2018-10-26T02:31:00.000","2.567","2.143","2.224",'2.338","700","21.3674"]
//[timestamp,open,high,low,close,volume,currency_volume]

]

Get Indices

Get Indices of tokens.

Rate limit:20/2s

HTTP Requests

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

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/index

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
index String Index price
timestamp String Timestamp

Explanation

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

Return Sample

{

"instrument_id": "BTC-USD-SWAP",

"index": 6214.8,

"timestamp": "2018-10-24T20:11:443Z"

}

Get Exchange Rates

Get the fiat exchange rates.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/rate

Request Sample

GET /api/swap/v3/rate

Return Parameters

Parameters Type Description
instrument_id String USD_CNY
rate String Exchange rates
timestamp String Timestamp

Return Sample

 {

"instrument_id": "USD_CNY",

"rate": 6.83,

"timestamp": "2018-10-24T20:11:443Z"

}

Get Open Interest

Get the open interest of a contract.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/open_interest

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/open_interest

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 Total open interest
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": 35666,

"timestamp": "2018-10-24T20:11:443Z"

}

Get Current Price Limits

The maximum buying price and the minimum selling price of the contract.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/price_limit

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/price_limit

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
highest String Maximum buying price
lowest String Minimum buying price
timestamp String Timestamp

Return Sample

{

"instrument_id": "BTC-USD-SWAP",

"highest": 8903.2,

"lowest": 7980.6,

"timestamp": "2018-10-24T20:11:443Z"

}

Get Force Liquidated Orders

Get force liquidated orders.

Rate limit:20/2s

HTTP Requests

GET /api/swap/v3/instruments/<instrument_id>/liquidation

Request Sample

GET /api/swap/v3/instruments/BTC-USD-SWAP/liquidation?status=0&from=1&limit=50

Request Parameters

Parameters Type Required Description
instrument_id String Yes Contract ID, e.g. BTC-USD-SWAP
status String Yes No Status (0:unfilled orders in the recent 7 days 1:filled orders in the recent 7 days)
from String No Request paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to String No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
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.

If status isn’t 0 or 1, 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
size String Quantity
created_at String Order creation time
loss String User loss
price String Order price
type String 3:Close long 4:Close short

Return Sample

[

{

"instrument_id": "BTC-USD-SWAP",

"size": 25,

"created_at": "2018-10-24T20:11:443Z",

"loss": 0,

"price": 256,

"type": 3

},

{

"instrument_id": "BTC-USD-SWAP",

"size": 20,

"created_at": "2018-10-24T20:11:443Z",

"loss": 0,

"price": 250,

"type": 4

}
]

Get On Hold Amount for Open Orders

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": 0.00045,

"timestamp": "2018-10-24T20:11:443Z"

}

Get 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 next settlement

Return Sample

{

"instrument_id": "BTC-USD-SWAP",

"funding_time": "2018-10-24T20:11:443Z"

}

Get 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 paging content for this page number.(Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
to String No Request page after (older) this pagination id. (Example: 1,2,3,4,5. From 4 we only have 4, to 4 we only have 3)
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": "7100.35",

"timstamp": "2018-10-24T20:11:443Z"

}

Get Funding Rate History

Get Funding Rate History.

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?from=1&limit=50

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 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.0025,

"realized_rate": 0.0022,

"interest_rate": 0,

"funding_time": "2018-10-24T20:11:443Z"

},

{

"instrument_id": "BTC-USD-SWAP",

"funding_fee": 0.0025,

"realized_rate": 0.0022,

"interest_rate": 0,

"funding_time": "2018-10-24T04:11:443Z"

}
]

Error Codes

Error Codes

Example

error_code Description Scenario
35001 Contract does not exist Contract subscribing does not exist
35002 Contract settling Contract is being settled
35003 Contract paused Contract is being paused
35004 Contract pending settlement Pending contract settlement
35005 User does not exist Perpetual swap trading is not enabled
35008 Risk ratio too high Margin ratio too low when placing order
35010 Position closing too large Closing position size larger than available size
35012 Incorrect order size Placing an order with less than 1 contract
35014 Order price is not within limit Order size is not in acceptable range
35015 Invalid leverage level Leverage level unavailable
35017 Open orders exist Changing leverage level
35019 Order size too large Order size exceeds limit
35020 Order price too high Order price exceeds limit
35021 Order size exceeded current tier limit Order size exceeds limit of the current tier
35022 Contract status error Contract is paused or closed
35024 Contract not initialized
35025 No account balance
35026 Contract settings not initialized
35029 Order does not exist
35030 Order size too large Place multiple orders
35031 Cancel order size too large Cancel multiple orders
35032 Invalid user status
35039 Open order quantity exceeds limit
35044 Invalid order status
35046 Negative account balance
35047 Insufficient account balance
35048 User contract is frozen and liquidating
35049 Invalid order type
35050 Position settings are blank
35052 Insufficient cross margin
35053 Account risk too high
35055 Insufficient account balance
35057 No last traded price
35058 No limit
30023 Required parameters cannot be blank Required parameters not filled
30024 Invalid parameters Parameters are invalid
30062 Invalid match price
30063 Invalid order size
30064 Invalid client_oid

INDEX API

Rest API public index

Get Index Content

get constituents of index

Rate limit: 20 /2s
HTTP Requests

GET/api/index/v3//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
参数名 参数类型 描述
instrument_id String trading pair of index ,such as:BTC-USD
index Price price of index
timestamp String timestamp
Return Sample
{
    "index":5.331,
    "instrument_id":"EOS-USD-181026",
    "timestamp":"2018-10-23T09:18:11.192Z"
}

ETT API

Constituents enquiry, account information, order operations, order enquiry, bills details of ETT trading.

Get ETT

List the assets in ETT account. Get information such as balance, amount on hold/ available.

HTTP Requests

GET /api/ett/v3/accounts

Return Parameters
Parameters Description
currency Token or ETT name
balance Balance
holds On hold
available Amount available for trading or transfer
Explanation

After you placed an order, the amount of the order will be put on hold. This amount will not be available for transfer or using in other orders until the order is completed or cancelled.

Return Sample
[
    {
        "currency": "USDT", // Token
        "balance": 0.27124022, // Balance
        "available": 231.23432 // Available
        "holds": 0, // On hold
    }
]

Get Account Information of a Currency

Getting the balance, amount available/on hold of a token in ETT account.

HTTP Requests

GET /api/ett/v3/accounts/<currency>

Return Parameters
Parameters Description
balance Balance
holds amount on hold(not available)
available available amount for trading or transfer
Return Sample
{
    "balance": 0.27124022, // Balance
    "available": 231.23432 // Available
    "holds": 0, // On hold
}

Bills Details

Bills details. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

HTTP Requests

GET /api/ett/v3/accounts/<currency>/ledger

Return Parameters
Parameters Description
ledger_id Bill ID
currency Token or ETT name
balance Balance
amount Amount
type Type of bills
created_at Bill creation date
details If the type is trading related, order details will be included under this
Type Description
transfer Funds transfer
match Funds moved as a result of a trade
fee Fee as a result of a trade
rebate Fee reate as per our fee schedule
Return Sample
[
    {
        "ledger_id": 1,
        "currency": "USDT",
        "balance": 99988.587,
        "amount": -5.151,
        "type": "transfer", // transfer match fee
        "created_at": "2018-03-23T07:41:35.019Z",
        "details": 20
    },
    {  
        "ledger_id": 1,
        "currency": "USDT",
        "balance": 99988.587,
        "amount": -5.151,
        "type": "match",
        "created_at": "2018-03-23T07:41:35.019Z",
        "details": 20
    }

Place an Order

You can place subscription or redemption orders under ETT trading. You can place an order only if you have enough funds. Once your order is placed, the amount will be put on hold in the order lifecycle. The assets and amount on hold depends on the order's specific type and parameters.

HTTP Requests

POST /api/ett/v3/orders

Request Parameters
Parameters Description
client_oid [optional]the order ID customized by yourself
type Type of order (0:ETT subscription 1:subscribe with USDT 2:Redeem in USDT 3:Redeem in underlying)
quote_currency Subscription/redemption currency
amount Subscription amount. Required for usdt subscription
size Redemption size. Required for ETT subscription and redemption
ett ETT name
Return Parameters
Parameters Description
order_id Order ID
client_oid The order ID customized by yourself
result Result of the order. Error message will be returned if the order failed.
Explanation

currency

currency must be a valid ETT name. ETT list can be acquired via the constituents endpoint.

client_oid

The optional client_oid field must be a UUID generated by your trading application.

This field value will be broadcast in the public feed for received messages. You can use this field to identify your orders in the public feed.

type

Subscription order is the order type for subscribing ETT. Amount is required for subscribing ETT. Size cannot be specified.

Redemption order is the order type of redeeming ETT. Size is required for redeeming ETT. Amount cannot be specified. User may choose to redeem in a specific token or in underlying.

order lifecycle

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 done 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.

Return Sample
{
    "order_id": "888845120785408",
    "client_oid": "2235679",
    "result": true
}

Cancel an Order

Cancel an unfilled order.

HTTP Requests

DELETE /api/ett/v3/orders/<order_id>

Request Parameters
Parameters Description
order_id Order ID
Explanation

This order_id is the order ID assigned by the server, instead of the client_oid sent by the user.

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

Get Order List

List your orders. Cursor pagination is used. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

HTTP Requests

GET /api/ett/v3/orders

Request Parameters
Parameters Description
status List the orders of the status (0:All 1:Unfilled 2:Filled 3:Canceled)
ett [required] list specific ETT order
type [required](1: subscription 2: redemption)
from Request page before (newer) this pagination id.(Example: 1,2,3,4,5. From 4 we only have 5, to 4 we have 1,2,3)
to Request page after (older) this pagination id.
limit Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Description
order_id Order ID
price Price
size ETT size
amount Amount of subscription / redemption
ett ETT name
type Order type
created_at Order creation time
status Order Status(open = new, process = processing, done = completed, cancel = cancelled)
Explanation

This endpoint can be used for enquiring the filled and cancelled orders of the recent 2 days

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.

Return Sample
[{
    "order_id": "888845120785408",
    "price": "0.10000000",
    "size": “0.01000000",
    "amount": “0.0000000000000000",
    "quote_currency": "USDT",
    "ett": "OK06",
    "type": 1,
    "created_at": "2016-12-08T20:02:28.53864Z",
    "status": "open"
},{
    "order_id": "885845120785408",
    "price": "0.10000000",
    "size": “0.01000000",
    "amount": “0.0000000000000000",
    "quote_currency": "USDT",
    "ett": "OK06",
    "type": 1,
    "created_at": "2016-12-08T20:02:28.53864Z",
    "status": "open"
},{
    "order_id": "888845120785308",
    "price": "0.10000000",
    "size": “0.01000000",
    "amount": “0.0000000000000000",
    "quote_currency": "USDT",
    "ett": "OK06",
    "type": 1,
    "created_at": "2016-12-08T20:02:28.53864Z",
    "status": "done"
}]

Get Order Details

Get order details by order ID.

HTTP Requests

GET /api/ett/v3/orders/

Request Parameters
Parameters Description
order_id Order ID
Return Parameters
Parameters Description
order_id Order ID
price Price
size ETT size
amount Amount of subscription / redemption
ett ETT name
type Order type
created_at Order creation time
status Order status
Explanation

This endpoint can be used for enquiring the filled and cancelled orders of the recent 2 days

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.

Return Sample
{
    "order_id": "888845020785408",
    "price": "0.10000000",
    "size": “0.01000000",
    "amount": “0.0000000000000000",
    "quote_currency": "USDT",
    "ett": "OK06",
    "type": 1,
    "created_at": "2016-12-08T20:02:28.53864Z",
    "status": "done"
}

Get ETT Constituents

Get ETT Constituents.This is a public endpoint, no identity verification is needed.

HTTP Requests

GET /api/ett/v3/constituents/< ett >

Request Parameters
Parameters Description
ett [required] ETT name such as OK06
Return Parameters
Parameters Description
net_value NAV
ett ETT name
amount The constituents of the ETT (tokens & proportion)
currency The constituents of the ETT (tokens)
Return Sample
{

"net_value": 100,

"ett": “OK06",

"constituents": [


    {

        "amount": 0.14353453,
        "currency": "btc"
    },

    {
        "amount": 0.14353453,
        "currency": "ltc"

    },

    {

        "amount": 0.14353453,
        "currency": "eth"
    }
 ]
}

Get ETT Settlement Price History

Get ETT settlement price history. This is a public endpoint, no identity verification is needed.

HTTP Requests

GET /api/ett/v3/define-price/<ett>

Request Parameters
Parameters Description
ett ETT name (only OK06ETT is available at the moment)
Return Parameters
Parameters Description
date Delivery date
price Delivery price
Return Sample
[

{
    "date": 1523874826000,

    "price": 0.883423

},
{

    "date": 1523874826000,

    "price": 0.883423

},

{
    "date": 1523874826000,

    "price": 0.883423
}
]

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
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
Description Error Codes http Status Code Scenarios
body cannot be blank 30020 400 body cannot be blank
json data format error 30021 400 json data format error
{0} parameter cannot be blank; required parameter cannot be blank 30023 400 parameters returned respectively
{0} parameter value error 30024 400 parameters returned respectively
{0} parameter category error 30025 400 parameter category error
requested too frequent; endpoint limit exceeded 30026 429 requested too frequent; endpoint limit exceeded
login failure 30027 401 operating orders of other users
unauthorized execution 30028 400 unauthorized execution
account suspended 30029 400 account suspended
endpoint request failed. Please try again 30030 400 endpoint request failed. Please try again
token does not exist 30031 400 token requested does not exist
pair does not exist 30032 400 pair requested does not exist
exchange domain does not exist 30033 400 the error returned when the exchange for the apikey validation is not filled
exchange ID does not exist 30034 400 the error returned when the exchange ID for the apikey validation is not filled
trading is not supported in this website 30035 400 the error returned when the exchange is closed
no relevant data 30036 400 no relevant data when enquiring the endpoint
user does not exist 30038 400 user does not exist
endpoint is offline or unavailable 30037 400 endpoint is offline or unavailable
successful 0 200 when the order placement / cancellation / operation is successful

Contract Delivery Error Codes

Error Messages Error Codes http Status Code Scenarios
futures account suspended 32001 400 when the futures account is suspended
futures account does not exist 32002 400 when futures trading is not enabled for the account
canceling, please wait 32003 400 when the user execute other operations during order cancellation
you have no unfilled orders 32004 400 when the user check the unfilled orders
max order quantity 32005 400 when the user placed an order exceeding the quantity limit
the order price or trigger price exceeds USD 1 million 32006 400 when the user placed and order with price or trigger price over USD 1 million
leverage level must be the same for orders on the same side of the contract 32007 400 when the user has open positions with 10x leverage and trying to open a 20x leverage order
Max. positions to open (cross margin) 32008 400 when the order quantity is larger than the availability (cross margin)
Max. positions to open (fixed margin) 32009 400 when the order quantity is larger than the availability fixed margin)
leverage cannot be changed with open positions 32010 400 if an user holds a short position with 10x leverage, he/she will not be able to change the leverage to 20x
futures status error 32011 400 contract expired
futures order update error 32012 400 updating the status of a canceled order
token type is blank 32013 400 token type is blank
your number of contracts closing is larger than the number of contracts available 32014 400 your number of contracts closing is larger than the number of contracts available
margin ratio is lower than 100% before opening positions 32015 400 margin ratio is lower than 100% before opening positions
margin ratio is lower than 100% after opening position 32016 400 margin ratio is lower than 100% after opening position
no BBO 32017 400 no BBO
the order quantity is less than 1, please try again 32018 400 the order quantity is less than 1, please try again
the order price deviates from the price of the previous minute by more than 3% 32019 400 the order price deviates from the price of the previous minute by more than 3%
the price is not in the range of the price limit 32020 400 the price is not in the range of the price limit
leverage error 32021 400 leverage is not set as 10x or 20x
this function is not supported in your country or region according to the regulations 32022 400 futures trading not supported in certain regions
this account has outstanding loan 32023 400 this account has outstanding loan
order cannot be placed during delivery 32024 400 order placement failure during delivery
order cannot be placed during settlement 32025 400 order placement failure during settlement
your account is restricted from opening positions 32026 400 restricted from opening position
order info does not exist 32029 400 order has been canceled already
account is suspended and liquidated 32028 400 account is suspended and liquidated
cancelled over 20 orders 32027 400 order cancellation limit reached
The margin ratio after submitting this order is lower than the minimum requirement ({0}) for your tier. 32044 400

Token and margin error codes

Error Messages Error Codes http Status Code Scenarios
margin account for this pair is not enabled yet 33001 400 the service must be enabled before trading
margin account for this pair is suspended 33002 400 margin account suspended
no loan balance 33003 400 insufficient balance for loan
loan amount cannot be smaller than the minimum limit 33004 400 minimum loan amount limit not reached
repayment amount must exceed 0 33005 400 invalid repayment amount
loan order not found 33006 400 loan order not found
status not found 33007 400 status unchanged
loan amount cannot exceed the maximum limit 33008 400 invalid loan amount
user ID is blank 33009 400 user ID not provided
you cannot cancel an order during session 2 of call auction 33010 400 order cancellation not allowed during call auction
no new market data 33011 400 no market data
order cancellation failed 33012 400 order cancellation failed
order placement failed 33013 400 order placement failed
order does not exist 33014 400 order canceled already. Invalid order number
exceeded maximum limit 33015 400 exceeded maximum limit during multiple-order placement
margin trading is not open for this token 33016 400 insufficient balance for order placement
insufficient balance 33017 400 margin trading not supported for this pair
this parameter must be smaller than 1 33018 400 invalid parameter for getting market data
request not supported 33020 400 margin trading not supported for some exchanges
token and the pair do not match 33021 400 incorrect token for the token pair during repayment
pair and the order do not match 33022 400 incorrect token for the order during repayment
you can only place market orders during call auction 33023 400 you can only place market orders during call auction
trading amount too small 33024 400 invalid trading amount
base token amount is blank 33025 400 settings not completed during order placement
transaction completed 33026 400 cancel limited when the transaction completed
cancelled order or order cancelling 33027 400 cancel limited when the order is cancelling or cancelled
the decimal places of the trading price exceeded the limit 33028 400 order endpoint: The decimal places of the trading price exceeded the limit
the decimal places of the trading size exceeded the limit 33029 400 order endpoint::The decimal places of the trading size exceeded the limit
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

Wallet error codes

Error Messages 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

Swap Error Codes

Error Codes

Example

error_code Description Scenario
1 System error Invalid parameter in url normally
35001 Contract does not exist Contract subscribing does not exist
35002 Contract settling Contract is being settled
35003 Contract paused Contract is being paused
35004 Contract pending settlement Pending contract settlement
35005 User does not exist Perpetual swap trading is not enabled
35008 Risk ratio too high Margin ratio too low when placing order
35010 Position closing too large Closing position size larger than available size
35012 Incorrect order size Placing an order with less than 1 contract
35014 Order price is not within limit Order size is not in acceptable range
35015 Invalid leverage level Leverage level unavailable
35017 Open orders exist Changing leverage level
35019 Order size too large Order size exceeds limit
35020 Order price too high Order price exceeds limit
35021 Order size exceeded current tier limit Order size exceeds limit of the current tier
35022 Contract status error Contract is paused or closed
35024 Contract not initialized
35025 No account balance
35026 Contract settings not initialized
35029 Order does not exist
35030 Order size too large Place multiple orders
35031 Cancel order size too large Cancel multiple orders
35032 Invalid user status
35039 Open order quantity exceeds limit
35044 Invalid order status
35046 Negative account balance
35047 Insufficient account balance
35048 User contract is frozen and liquidating
35049 Invalid order type
35050 Position settings are blank
35052 Insufficient cross margin
35053 Account risk too high
35055 Insufficient account balance
35057 No last traded price
35058 No limit
30023 Required parameters cannot be blank Required parameters not filled
30024 Invalid parameters Parameters are invalid
35061 Invalid instrument_id Invalid instrument_id
35059 client_oid or order_id is required
35060 Only fill in either parameter client_oid or order_id
35062 Invalid match_price
35063 Invalid order_size
35064 Invalid client_oid

WebsocketAPI

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:10442/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>","error_code":"<error_code>"}

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/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

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

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
response examples
{
        ”table”: "swap/ticker”,
        ”data”: [{
                ”high_24h”: "24711”,
                "best_bid": "5",
                "best_ask": "8.8",
                ”instrument_id”: "BTC-USD-SWAP”,
                ”last”: "22621”,
                ”low_24h”: "22478.92”,
                ”timestamp”: "2018-11-22T09:27:31.351Z”,
                ”volume_24h”: "85”
        }]
}

Kline

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": ["2018-12-09T08:40:00.000Z", "3345", "3345", "3332.1", "3344.9", "7531", "225.9413"]
    }]
}

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": "3250",
        "side": "sell",
        "size": "1",
        "timestamp": "2018-12-17T09:48:41.903Z",
        "trade_id": "126518511769403393"
    }]
}

Funding Fee

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 Settlement time
funding_rate String Funding rate
response examples

{
        ”table”: "swap/funding_rate”,
        ”data”: [{
                ”funding_rate”: "0.0025”,
                ”funding_time”: "2018-11-22T10:12:59.253Z”,
                ”instrument_id”: "BTC-USD-SWAP”,
                ”interest_rate”: "0.0001”
        }]

}

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”: "22391.96”,
                ”instrument_id”: "BTC-USD-SWAP”,
                ”lowest”: "20583.40”,
                ”timestamp”: "2018-11-22T08:46:45.016Z”
        }]
}

Depth5

First 5 entries of data in depth trial channel

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": [
             ["3986", "7", 0, 1],
             ["3986.9", "198", 0, 2],
             ["3987", "9499", 0, 2],
             ["3987.5", "6455", 0, 5],
             ["3987.8", "501", 0, 1]
         ],
         "bids": [
             ["3983", "12790", 0, 4],
             ["3981.9", "2907", 0, 3],
             ["3981.6", "7963", 0, 1],
             ["3981.5", "9800", 0, 2],
             ["3981", "700", 0, 3]
         ],
         "instrument_id": "BTC-USD-SWAP",
         "timestamp": "2018-12-04T09:51:56.500Z"
     }]
 }

Depth

First time return 200 entries, followed by increment data

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] [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
 First 200 entries 


{
    "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
    }]
}

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
response examples
{
        ”table”: "swap/mark_price”,
        ”data”: [{
               ”instrument_id”: "BTC-USD-SWAP”,
                ”mark_price”: "22616.58”,
                ”timestamp”: "2018-11-22T10:09:31.541Z”
        }]
}

User Position

Get the information of holding positions of a contract. require login

send examples
{"op": "subscribe", "args": ["swap/position:BTC-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)
response examples

{
"table”:”swap/position”,
"data”:[
{
"holding”:[
{
"avail_position”:”1.000”,
"avg_cost”:”48.0000”,
"leverage”:”11”,
"liquidation_price”:”52.5359”,
"margin”:”0.018”,
"position”:”1.000”,
"realized_pnl”:”-0.001”,
"settlement_price”:”48.0000”,
"side”:”short”,
"timestamp”:”2018-11-29T02:37:01.963Z”
}
],
"instrument_id”:”BTC-USD-SWAP”,
"margin_mode”:”fixed”
}
]
}

User Account

Get the user's account information , require login.

send examples
{"op": "subscribe", "args": ["swap/account:BTC-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
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 fixed margin account
margin_mode String Margin Mode: crossed/fixed
response examples
{
"table”:”swap/account”,
"data”:[
{
"equity”:”333378.858”,
"fixed_balance”:”555.649”,
"instrument_id”:”LTC-USD-SWAP”,
"margin”:”554.017”,
"margin_frozen”:”7.325”,
"margin_mode”:”fixed”,
"margin_ratio”:”0.000”,
"realized_pnl”:”-1.633”,
"timestamp”:”2018-11-26T07:43:52.303Z”,
"total_avail_balance”:”332774.283”,
"unrealized_pnl”:”50.556”
}]
}

User Orders

Get user's order information , require login

send examples
{"op": "subscribe", "args": ["swap/order:BTC-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 ID
price_avg String Average price
status String Order Status (-2:failure ; -1 cancelled; 0: pending, 1: partially filled, 2: fully filled
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
response examples
{
"table”:”swap/order”,
"data”:[
{
"size”:”1”,
"filled_qty”:”0”,
“client_oid”:”B333”,
"price”:”46.1930”,
"fee”:”0.000000”,
"contract_val”:”10”,
"price_avg”:”0.0000”,
"type”:”1”,
"instrument_id”:”BTC-USD-SWAP”,
"order_id”:”65-6e-2e904c43d-0”,
"status”:”0”,
"order_type”:”1”,
"timestamp”:”2018-11-26T08:02:18.618Z”
}
]
}

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:10442/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>","error_code":"<error_code>"}

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/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

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

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-170310"]}

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
response examples
     {
         "table": "futures/ticker",
         "data": [{
             "last": 3922.4959,
             "best_bid": 3921.8319,
             "high_24h": 4059.74,
             "low_24h": 3922.4959,
             "volume_24h": 2396.1,
             "best_ask": 4036.165,
             "instrument_id": "BTC-USD-170310",
             "timestamp": "2018-12-17T06:30:07.142Z"
         }]
     }

Kline

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/candle60s:BTC-USD-170310"]}

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/candle60s",
    "data": [{
        "instrument_id": "BTC-USD-SWAP",
        "candle": ["2018-12-09T08:40:00.000Z", "3345", "3345", "3332.1", "3344.9", "7531", "225.9413"]
    }]
}

Trade

Get the filled orders data

send examples
{"op": "subscribe", "args": ["futures/trade:BTC-USD-170310"]}

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”: "swap/trade”,
        ”data”: [
                [{
                        ”instrument_id”: "BTC-USD-SWAP”,
                        ”price”: "22888”,
                        ”side”: "buy”,
                        ”qty”: "7”,
                        ”timestamp”: "2018-11-22T03:58:57.709Z”,
                        ”trade_id”: "108223090144493569”
               }]
        ]
}

Price Range

The maximum buying price and the minimum selling price of the contract.

send examples
{"op": "subscribe", "args": ["futures/price_range:BTC-USD-170310"]}

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": 4159.5279,
        "lowest": 2773.0186,
        "instrument_id": "BTC-USD-170310",
        "timestamp": "2018-12-18T10:49:40.021Z"
    }]
}

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 Double Estimated delivery price
timestamp String Timestamp
response examples
{
        ”table”: "futures/mark_price”,
        ”data”: [{
                ”instrument_id”: "BTC-USD-SWAP”,
                ”mark_price”: "22616.58”,
                ”timestamp”: "2018-11-22T10:09:31.541Z”
        }]
}

Depth5

Back to the previous five entries of depth data

send examples
{"op": "subscribe", "args": ["futures/depth5:BTC-USD-170310"]}

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][double ,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": [
            [3921.8772, 1, 1, 1],
            [3981.6852, 40, 1, 1],
            [4036.165, 12, 1, 1],
            [4059.7606, 95, 1, 1],
            [4100.0, 6, 0, 4]
        ],
        "bids": [
            [3921.608, 12, 0, 1],
            [3920.972, 12, 0, 1],
            [3920.692, 12, 0, 1],
            [3920.672, 12, 0, 1],
            [3920.3759, 12, 0, 1]
        ],
        "instrument_id": "BTC-USD-170310",
        "timestamp": "2018-12-17T09:48:09.978Z"
    }]
}

Depth

First time return 200 entries, followed by increment data

send examples
{"op": "subscribe", "args": ["futures/depth:BTC-USD-170310"]}

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] [double ,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-170310",
        "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-170310",
        "asks": [],
        "bids": [
            [3983, 89, 0, 3]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1200119424
    }]
}

Mark Price

Get the mark price

send examples
{"op": "subscribe", "args": ["futures/mark_price:BTC-USD-170310"]}

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
response examples
{
    "table": "futures/mark_price",
    "data": [{
        "mark_price": "3921.81",
        "instrument_id": "BTC-USD-170310",
        "timestamp": "2018-12-17T10:01:56.963Z"
    }]
}

User Position

Get the information of holding positions of a contract. require login

send examples
{"op": "subscribe", "args": ["futures/position:BTC-USD-170317"]}

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
response examples
{
    "table":"futures/position",
    "data":[
        {
            "long_qty":"62",
            "long_avail_qty":"62",
            "long_margin":"0.229",
            "long_liqui_price":"2469.319",
            "long_pnl_ratio":"3.877",
            "long_avg_cost":"2689.763",
            "long_settlement_price":"2689.763",
            "realised_pnl":"-0.635",
            "short_qty":"17",
            "short_avail_qty":"17",
            "short_margin":"0.039",
            "short_liqui_price":"4803.766",
            "short_pnl_ratio":"-0.049",
            "short_avg_cost":"4371.398",
            "short_settlement_price":"4371.398",
            "instrument_id":"BTC-USD-170317",
            "long_leverage":"10",
            "short_leverage":"10",
            "created_at":"2018-12-07T10:49:59.000Z",
            "updated_at":"2018-12-19T09:43:26.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
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"
        }
    ]
}

User Account

Get the user's account information , require login.

send examples
{"op": "subscribe", "args": ["futures/account:BTC"]}

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
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
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
total_avail_balance String Balance of the account
Fixed margin
{
    "table":"futures/account",
    "data":[
        {
            "BTC":{
                "contracts":[
                    {
                        "available_qty":"990.05445298",
                        "fixed_balance":"0",
                        "instrument_id":"BTC-USD-170310",
                        "margin_for_unfilled":"5.63890118",
                        "margin_frozen":"0",
                        "realized_pnl":"-0.02197068",
                        "unrealized_pnl":"0"
                    },
                    {
                        "available_qty":"990.05445298",
                        "fixed_balance":"0.90761235",
                        "instrument_id":"BTC-USD-170317",
                        "margin_for_unfilled":"0.1135112",
                        "margin_frozen":"0.27228744",
                        "realized_pnl":"-0.63532491",
                        "unrealized_pnl":"0.8916"
                    },
                    {
                        "available_qty":"990.05445298",
                        "fixed_balance":"0.356976",
                        "instrument_id":"BTC-USD-170331",
                        "margin_for_unfilled":"0.0025641",
                        "margin_frozen":"0.35680727",
                        "realized_pnl":"-0.00016873",
                        "unrealized_pnl":"0.0785"
                    }
                ],
                "equity":"997.40890131",
                "margin_mode":"fixed",
                "total_avail_balance":"995.83140014"
            }
        }
    ]
}

User Orders

Get user's order information , require login .

send examples
{"op": "subscribe", "args": ["futures/order:BTC-USD-170317"]}

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 Creation time
filled_qty String Filled quantity
fee String Fees
order_id String Order price
price String Order ID
price_avg String Average price
status String Order Status (-1 cancelled; 0: pending, 1: partially filled, 2: fully filled
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
response examples
{
    "table":"futures/order",
    "data":[
        {
            "leverage":"10",
            "client_oid":"20181009e",
            "size":"1",
            "filled_qty":"1",
            "price":"4393.0",
            "fee":"-0.00000683",
            "contract_val":"100",
            "price_avg":"4393.0",
            "type":"2",
            "order_type”:”1”,
            "instrument_id":"BTC-USD-170317",
            "order_id":"1997723572808704",
            "timestamp":"2018-12-19T11:27:22.000Z",
            "status":"2"
        }
    ]
}

Spot&Margin

This is the V3 Websocket API for spot and margin ,Except for the separate channel of "account", data of other channels is open to both token and margin trading users.

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:10442/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 spot/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>","error_code":"<error_code>"}

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 channel name is composed of business/channel

spot push business is spot, 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:

"spot/ticker:ETH-USDT"or "spot/margin_account:ETH-USDT"

Filter is filterable data. 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

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-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:.... (see the following example)

"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 push data depth channel users receive is:

First 200 amount


{
    "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

spot/ticker // ticker channel

spot/candle60s // 1mins kline channel

spot/candle180s // 3mins kline channel

spot/candle300s // 5mins kline channel

spot/candle900s // 15mins kline channel

spot/candle1800s // 30mins kline channel

spot/candle3600s // 1hour kline channel

spot/candle7200s // 2hour kline channel

spot/candle14400s // 4hour kline channel

spot/candle21600 // 6hour kline channel

spot/candle43200s // 12hour kline channel

spot/candle86400s // 1day kline channel

spot/candle604800s // 1week kline channel

spot/trade // trade information

spot/depth //depth information,200 entries of depth data for the first time, then increment data

spot/depth5 //depth information, the previous five entries of depth data

Channels that require login

spot/account //User's account information

spot/margin_account //User's margin account information

spot/order //User's order information

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": ["spot/ticker:ETH-USDT"]}

spot/ticker is channel name ,ETH-USDT is instrument_id

response parameters
Parameters Parameters type Description
instrument_id String trading pair
last String last traded 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 high
base_volume_24h String 24 trading volume of the base currency
quote_volume_24h String 24 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"
    }]
}

Kline

Kline information for spot business

channel lists:

spot/candle60s // 1mins kline channel

spot/candle180s // 3mins kline channel

spot/candle300s // 5mins kline channel

spot/candle900s // 15mins kline channel

spot/candle1800s // 30mins kline channel

spot/candle3600s // 1hour kline channel

spot/candle7200s // 2hour kline channel

spot/candle14400s // 4hour kline channel

spot/candle21600 // 6hour kline channel

spot/candle43200s // 12hour kline channel

spot/candle86400s // 1day kline channel

spot/candle604800s // 1week kline channel

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": ["2018-12-18T02:55:00.000Z", "8.8", "8.8", "8.8", "8.8", "0"],
        "instrument_id": "ETH-USDT"
    }]

}

Trade

Get the filled orders data

send examples
{"op": "subscribe", "args": ["spot/trade:ETH-USDT"]}

spot/trade is channel name ,ETH-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
response examples

{
        ”table”: "spot/trade”,
        ”data”: [
                [{
                        ”instrument_id”: "ETH-USDT”,
                        ”price”: "22888”,
                        ”side”: "buy”,
                        ”size”: "7”,
                        ”timestamp”: "2018-11-22T03:58:57.709Z”,
                        ”trade_id”: "108223090144493569”
               }]
        ]
}

Depth5

Back to the previous five entries of depth data

send examples
{"op": "subscribe", "args": ["spot/depth5:ETH-USDT"]}

spot/depth5 is channel name ,ETH-USDT is instrument_id

response parameters
Parameters Parameters Types Description
price String price
size String Size
timestamp String timestamp
num_orders integer total orders in the book
instrument_id String trading pair

["411.8","10",8][price ,size ,num_orders ]

response examples

{
    "table": "spot/depth5",
    "data": [{
        "asks": [
            ["8.8", "96.99999966", 1],
            ["9", "39", 3],
            ["9.5", "100", 1],
            ["12", "12", 1],
            ["95", "0.42973686", 3]
        ],
        "bids": [
            ["5", "7", 4],
            ["3", "5", 3],
            ["2.5", "100", 2],
            ["1.5", "100", 1],
            ["1.1", "100", 1]
        ],
        "instrument_id": "ETH-USDT",
        "timestamp": "2018-12-18T07:27:13.655Z"

Depth

First time return 200 entries, followed by increment data

send examples
{"op": "subscribe", "args": ["spot/depth:ETH-USDT"]}

spot/depth is channel name ,ETH-USDT is trading pair

response parameters
Parameters Parameters Types Description
price String price
size String Size
timestamp String timestamp
num_orders integer total orders in the book
instrument_id String trading pair
checksum String checksum

["411.8","10",8][price ,size ,num_orders ]

response examples
 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
    }]
}

User Spot Account

Get the user's spot account information , require login.

send examples
{"op": "subscribe", "args": ["spot/account:BTC"]}

spot/account is channel name ,BTC is token

response parameters
Parameters Parameters type Description
currency string token
balance string balance
hold string amount on hold(not available)
available string available amount for trading or transfer
id long account id
response examples
{
    "table": "spot/account",
    "data": [{
        "balance": "881.5011237890123457",
        "available": "868.4011237890123457",
        "currency": "USDT",
        "id": "6916752",
        "hold": "13.1"
    }]
}

User Margin Account

Get the user's margin account information , require login.

send example
{"op": "subscribe", "args": ["spot/margin_account:ETH-USDT"]}

spot/margin_account is channel name ,ETH-USDT is instrument_id

response parameters
Parameters Parameters type Description
instrument_id string trading pair
balance string 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”:[
{
"equity”:”333378.858”,
"fixed_balance”:”555.649”,
"instrument_id”:”LTC-USDT”,
"margin”:”554.017”,
"margin_frozen”:”7.325”,
"margin_mode”:”fixed”,
"margin_ratio”:”0.000”,
"realized_pnl”:”-1.633”,
"timestamp”:”2018-11-26T07:43:52.303Z”,
"total_avail_balance”:”332774.283”,
"unrealized_pnl”:”50.556”
}]
}

User Orders

Get user's order information , users need to log in first

send examples
{"op": "subscribe", "args": ["spot/order:LTC-USDT"]}

spot/order is channel name ,LTC-USDT is instrument_id

response parameters
Parameters Parameters type Description
order_id long order ID
client_oid string the order ID customised by yourself
price string price
size string size of order
notional string size of order
instrument_id string trading pair
side string buy or sell
type string limit,market(defaulted as limit)
timestamp string order creation date
filled_size string size filled
filled_notional string amount filled
status string order status(all, open, part_filled, filled, cancelled ,failure)
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
response examples
{
    "table": "spot/order",
    "data": [{
        "filled_notional": "0",
        "filled_size": "0",
        "instrument_id": "LTC-USDT",
        "margin_trading": "2",
        "notional": "",
        "order_id": "1997224323070976",
        "client_oid":"20181009e",
        "price": "1",
        "side": "buy",
        "order_type”:”1”,
        "size": "1",
        "status": "open",
        "timestamp": "2018-12-19T09:20:24.608Z",
        "type": "limit"
    }]
}

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/ticker 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”:” ",”error_code”:”"}

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

Pre-launch Notice

[2019-2-22]

1, Functional optimization of client_oid:

the type of client_oid will be changed into alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported

e.g.:client_oid:AB123456/client_oid:ABCDEF/client_oid:aaaa

For spot,futures,swap RestAPI :

1),Place an order endpoint :the type of client_oid will be changed into alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported

2),Place multiple orders endpoint :the type of client_oid will changed into alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported

3),Cancel an order endpoint:will add client_oid to request and response parameters

4),Cancel multiple orders endpoint:will add client_oid to request and response parameters

5),Get order details endpoint:will add client_oid to request and response parameters

6),Get order list endpoint:will add client_oid to request and response parameters

For spot,futures,swap Websocket API:

will add client_oid parameter in order channel

(Futures and perpetual swap will be included by Friday).

2, Perpetual swap statement inquiry interface GET /api/swap/v3/accounts//ledger :

Return parameter “Statement Type” is upgraded to “Statement Source Type” (including transfer in/out, liquidation/societal loss, etc. Please refer to API document for details).

HTTP Requests

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

Return Parameters

Parameters Type Description
ledger_id String Bill id
amount String Amount change
type String Type 1-21 numbers
fee String Fee
timestamp String Bill creation time
instrument_id String Contract ID

Changes:

Return Parameters
Parameters Type Description
ledger_id String Bill id
amount String Amount change
type String Type
fee String Fee
timestamp String Bill creation time
instrument_id String Contract ID
Type 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
  • 5、6 transfer
  • 1、2、3、4 match
  • 7、8 settlement
  • 10、11、19、20 liquidation
  • 14 funding
  • 15、16、17、18、21 margin

3, Futures and perpetual swap position/account data interface: All position/all account data, return to null if no position held; return to defaulted value for return from no single position/account data when no position/asset held.

HTTP Requests

GET /api/futures/v3/position

Return Sample
{
    "result":true,
    "holding":[

    ]
}
HTTP Requests

GET /api/swap/v3/position

Return Sample
[
    {
        "margin_mode":"fixed",
        "holding":[

        ]
    }

]

GET /api/futures/v3/accounts

Return Sample
{
    "info":{

    }
}

GET /api/futures/v3/accounts

Return Sample
{

 "info": [

]
}

Hello everyone,

Here is the preview of the V3 API upgrade next week (scheduled to launch on Monday):

  1. Added interface or channel for client oid: Spot, futures, perpetual swap rest: posting interface, bulk posting interface, cancelation interface, bulk cancelation interface, order list capture interface, order data capture interface

Ws: added client oid for user trading channel;

Note: the format of client_oid will be changed to alphabets only (upper and lower cases) or alphabets (upper and lower cases) + digits. Length 1 – 32 characters. (Please change your client_oid accordingly to avoid posting problems)

  1. Added advanced limit order options: Maker (Post-only) / Fill or Kill / Immediate or Cancel. Interface or channel: spot, futures, perpetual swap rest posting interface, bulk posting interface, order list capture interface, order data capture interface, ws: user trading channel. (Futures and perpetual swap will be included by Friday. Please refer to our announcement.)

  2. Increase to 10 orders / per trading pair for bulk posting / cancelation of spot, futures, perpetual swap orders

  3. Interface to capture single / all futures account data GET /api/futures/v3/accounts//GET /api/futures/v3/accounts/{currency} : The original return parameter “Margin” is divided into: “Margin frozen for open order” and “Margin used for holding position” (same as fixed margin).

  4. Interface to capture futures data GET /api/futures/v3/instruments, added parameter alias include weekly, bi-weekly, and quarterly.

```

Change Log

Update Records

API Description

【2018-11-06】

Modification: user ID will be used for rate limiting for RestAPI with valid API Key. Otherwise, public IP will be used instead.

Wallet

【2018-11-27】

New feature: Funds Transfer endpoints ,added 8:PiggyBank for request parameter of from and to

【2018-10-24】

New feature: the parameter of the funds transfer endpoint instrument_id is changed to supported trading pairs

Token trading

【2019-01-21】

Modification: modified the return value format for kline endpoints

【2018-12-17】

New feature: added "failure" on order status

【2018-11-16】

New feature: Get order details endpoint: added loyalty points fee and new example for "side"

【2018-11-14】

New feature: Speed limits for token trading APIs

【2018-11-08】

New feature: Timestamp added for market date

New feature: Multiple status supported for getting order list:status=filled|open

【2018-11-06】

Modification: Multiple order, order endpoint example: market order type=market

【2018-10-19】

New feature: Supports enquiring unfilled orders by instrument_id when getting all unfilled order endpoints

Margin trading

【2018-12-17】

New feature: added "failure" on order status

【2018-11-16】

New feature:repayment endpoint : borrow_id is optional for request parameter,all borrowed token under this trading pair will be repay if the field is left blank

【2018-11-30】

Modification:Margin account endpoint : The trading pairs returned will be linked by a hyphen (-) instead of an underscore (_), but both formats are supported in spot trading

Modification:Margin Account Settings for a Currency endpoint:modified the response example

【2018-11-27】

New feature: Get Loan History &Get Loan History of a Currency :added response parameters of force_repay_time and rate

【2018-11-16】

New feature: Place multiple orders endpoint: added order placement status of every order for data return

【2018-11-14】

New feature: Speed limits for margin trading APIs

【2018-11-08】

New feature: Multiple status supported for getting order list:status=filled|open

【2018-11-06】

Modification: Multiple order, order endpoint example: market order type=market

【2018-10-22】

New feature: Margin trading endpoints - borrowed & lending_fee (interest)

【2018-10-19】

New feature: Supports enquiring unfilled orders by instrument_id when getting all unfilled order endpoints

Futures delivery

【2019-01-21】

Modification: modified the return value format for kline endpoints

【2018-11-14】

New feature: Speed limits for futures trading APIs

【2018-10-24】

New feature:added status - 1 cancellation success

【2018-10-19】

New feature: Supports order cancellation by order_id

New feature: Timestamp added for market data enquiry

【2018-12-19】 1、Futures Positions GET /api/futures/v3/position changed from 10 times/2s to 5 times/2s

2、Futures Positions of a Contract GET /api/futures/v3//position changed from 10 times/2s to 20 times/2s

3、Futures Account of a Currency GET /api/futures/v3/accounts/{currency} changed from 10 times/2s to 20 times/2s

4、Place an Order POST /api/futures/v3/order changed from 20 times/2s to 40 times/2s

5、Place Multiple Orders POST /api/futures/v3/orders changed from 5 times/2s to 20 times/2s

6、Get Order List GET /api/futures/v3/orders/ changed from 10 times/2s to 20 times/2s

7、Get Order Details GET /api/futures/v3/orders// changed from 10 times/2s to 40 times/2s

8、Cancel an Order POST /api/futures/v3/cancel_order// changed from 10 times/2s to 40 times/2s

9、Cancel Multiple Orders POST /api/futures/v3/cancel_batch_orders/ changed from 5 times/2s to 20 times/2s

10、Get Transaction Details GET /api/futures/v3/fills changed from 5 times/2s to 20 times/2s

SWAP

【2019-1-16】

New feature: add “GET /api/swap/v3/position” API

New feature:add status:6: open (pending partially + fully filled), 7: completed (canceled + fully filled) for order endpoint

ETT

【2018-10-24】

New feature:Order placement endpoints - Type: "Add 0":"Subscribe in constituents";Amount:usdt (required for subscription);Size:required for subscription and redemption

Error code

【2018-11-30】

New feature: added error codes to account API: 34021,34022

Modification: dropped error code 30036, no error code return when there's no relevant data

【2018-11-01】

New feature: scenarios for public error codes

【2018-10-31】

Modification: Futures & wallet

【2018-10-29】

Modification: Token & margin trading

Websocket Change Log

Update Records

Swap

【2018-12-6】

New feature:added API documents

Futures

【2018-12-20】

New feature:added API documents

Spot&Margin

【2018-12-20】

New feature:added API documents

Error Code

【2018-12-6】

New feature:added API documents

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 ""