INTRODUCTION


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

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

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

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

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

  • historical price of trading pairs

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

Getting Access

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

Endpoints Configurations

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

REST API

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

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

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

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

Please join the OKCoin API community on Telegram (https://t.me/okcoin_en), where we will help answer your questions and you can share your experiences with other users.

API Summary

Market overview and general information.

Matching Engine

This section explains the matching engine based on the following:

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

Fill Price

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

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

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

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

Order Life Cycle

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

Token Trading Price Limit Rules

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

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

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

Fees

This sections explains the fee details for the following:

  • Trading Fees
  • Deposit/Withdrawal Fees

Trading Fees

To encourage more order placement and liquidity, OKCoin adopts a maker-taker fee schedule, where the maker fee is lower than the taker fee. The fee schedule is volume-based. To qualify for a tier, you need to meet the minimum trading volume required, calculated on the average trading volume in the past 30 days. The higher the tier you are in, the lower the fees. In addition to the tiered fee schedule, OkCoin rewards traders who intend to provide consistent liquidity and competitive bid-ask spread.

Please see here for details

Deposit/Withdrawal Fees

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

Server Location

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

Requests

This section explains the requests details based on the following:

  • Introduction
  • Errors
  • Success

Introduction

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

REST API URL https://www.okcoin.com/api

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

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

Errors

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

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

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

Success

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

Standards

This section explains the standard specifications for the following:

  • Timestamps
  • Numbers
  • IDs

Timestamps

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

Example

2014-11-06T10:34:47.123Z

Numbers

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

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

IDs

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

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

Endpoints

This section explains the endpoint details:

  • Public Endpoints
  • Private Endpoints

Public Endpoints

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

Private Endpoints

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

Rate Limits

This section explains the rate limit details for the following:

  • REST API
  • WebSocket

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

REST API

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

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

WebSocket

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

Authentication

This section explains the authentication details:

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

Generating an API Key

Before being able to sign any requests, you must create an API key on OKCoin. 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 OKCoin; the Passphrase will be provided by you to further secure your API access. OKCoin stores the salted hash of your passphrase for authentication, but cannot recover the passphrase if you lose it.

Making Requests

All private REST requests must contain the following headers:

OK-ACCESS-KEY The API key as a String.

OK-ACCESS-SIGN The base64-encoded signature (see Signing Messages subsection for details).

OK-ACCESS-TIMESTAMP The timestamp of your request.

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

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

Signing Messages

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

  • create a prehash string of timestamp + method + requestPath + body (where + represents String concatenation)
  • prepare the Secret
  • sign the prehash string with the Secret using the HMAC SHA256
  • encode the signature in the base64 format

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

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

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

The requestPath is the path of requesting an endpoint.

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

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

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

The Secret is generated when you create an API Key.

Example: 22582BD0CFF14C41EDBF1AB98506286D

public enum ContentTypeEnum {

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


    private String contentType;

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

    public String contentType() {
        return contentType;
    }
}


public enum HttpHeadersEnum {

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

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

    private String header;

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

    public String header() {
        return header;
    }
}

import com.okcoin.commons.okcoin.open.api.config.APIConfiguration;
import com.okcoin.commons.okcoin.open.api.constant.APIConstants;
import com.okcoin.commons.okcoin.open.api.enums.ContentTypeEnum;
import com.okcoin.commons.okcoin.open.api.enums.HttpHeadersEnum;
import com.okcoin.commons.okcoin.open.api.exception.APIException;
import com.okcoin.commons.okcoin.open.api.utils.DateUtils;
import com.okcoin.commons.okcoin.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 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);
        }
    }

}
package okcoin

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.okcoin.com/
    Endpoint string
    // The user's api key provided by OKCOIN.
    ApiKey string
    // The user's secret key provided by OKCOIN. 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 NewTestClient() *Client {
    // Set OKCOIN API's config
    var config Config
    config.Endpoint = "https://www.okcoin.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"
)
string OKCOINAPI::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 OKCOINAPI::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() {
    OKCOINAPI okcoinapi;
    /************************** set config **********************/
    struct Config config;
    config.Endpoint = "https://www.okcoin.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 okcoinapi.Request(method, request_path);
}

string AddSpotOrderExample() {
    OKCOINAPI okcoinapi;
    /************************** set config **********************/
    struct Config config;
    config.Endpoint = "https://www.okcoin.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 okcoinapi.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.okcoin.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.okcoin.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.okcoin.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 timezone of Unix timestamp decimal seconds format or the ISO8601 standard time format. It needs to be accurate to milliseconds.

The request will be rejected if the latency between the timestamp and the time reported on the server is more than 30 seconds. We recommend using the time endpoint to query the API server time if you believe there may be discrepancy between your server and the API servers.

Getting Server Time

This endpoint is used to get the API server time. This is a public method so it can be used without authentication.

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

}

Funding Account API

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

Get Currencies

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

Limit: 20 requests per 2 seconds

HTTP Request

GET /api/account/v3/currencies

Request Sample

GET /api/account/v3/currencies

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

Get Balances

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

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/wallet

Example Request

GET /api/account/v3/wallet

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

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

Get Currency

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

Limit: 20 requests per 2 seconds
HTTP Request

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

Request Sample

GET /api/account/v3/wallet/XMR

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

Funds Transfer

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

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

POST /api/account/v3/transfer

Example Request

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

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

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

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

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

When from or to is 5, instrument_id is required.

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

Withdrawal

This endpoint supports the withdrawal of tokens

Limit: 20 requests per 2 seconds
HTTP Request

POST /api/account/v3/withdrawal

Example Request

POST /api/account/v3/withdrawal

{"amount":1,"fee":0.0005,"trade_pwd":"123456","destination":4,"currency":"btc","to_address":"17DKe3kkkkiiiiTvAKKi2vMPbm1Bz3CMKw"}

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

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

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

Withdrawal Fees

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

HTTP Requests

GET /api/account/v3/withdrawal/fee

Example Request

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

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

Withdrawal History

This retrieves up to 100 recent withdrawal records.

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/withdrawal/history

Example Request

GET /api/account/v3/withdrawal/history

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

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

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

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

Example Response

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

Withdrawal History of a Currency

This retrieves the withdrawal records of a specific currency.

Limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

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

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

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

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

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

Bills Details

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

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/ledger

Example Request

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

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

Deposit Address

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

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/deposit/address

Example Request

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

Parameters
Parameters Parameters Types Required Description
currency String Yes Token symbol
Response
Parameters Parameters Types Description
address String Deposit address
tag String Deposit tag (This will not be returned if the token does not require a tag for deposit)
payment_id String Deposit payment ID (This will not be returned if the token does not require a payment_id for deposit)
currency String Token symbol
Notes

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

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

Example Response

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

Deposit History

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

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/deposit/history

Example Request

GET /api/account/v3/deposit/history

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

Deposit History of a Currency

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

Limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

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

Error Codes

Error Response
Message Error Code HTTP Status Description
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

Spot Trading API

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

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

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

Account Information

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/accounts

Example Request

GET /api/spot/v3/accounts

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

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

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

Get Currency

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

Limit: 20 requests per 2 seconds
HTTP Request

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

Request Sample

GET /api/account/v3/wallet/XMR

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

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

Bills Details

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

Limit: 20 requests per 2 seconds
HTTP Requests

GET /api/spot/v3/accounts/currency/ledger

Example Request

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

Parameters
Parameters Parameters Types Required Description
currency String No The token symbol, e.g. 'BTC'. Complete account statement for will be returned if the field is left blank
type String No Type of bill 1:deposit 2:withdrawal 13:cancel withdrawal 20:into sub account 21:out of sub account 28: claim 33: into margin account 34: out of margin account 37: into spot account 38: out of spot account
after String No Pagination of data to return records earlier than the requested ledger_id
before String No Pagination of data to return records newer than the requested ledger_id
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
ledger_id String Bill ID
balance String Remaining balance
currency String Token symbol
amount String Amount changed
type String Type of bills
timestamp String Creation time
Details String Order details when type is trade or fee
order_id String Order ID
instrument_id String Trading pair
Notes

The following is the enumeration value type

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

Place Order

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

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

Rate limit: 100 requests per 2 seconds
HTTP Request

POST /api/spot/v3/orders

Example Authenticated Request

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

Parameters

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

client_oid

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

instrument_id

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

type

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

price

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

size

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

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

notional

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

hold

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

Order life cycle

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

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

Response

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

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

Batch Orders

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

Rate limit: 50 requests per 2 seconds
HTTP Request

POST /api/spot/v3/batch_orders

Example Request

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

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

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

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

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

Cancel Order

This is used to cancel an unfilled order.

Rate limit: 100 requests per 2 seconds
HTTP Request

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

Example Request with Authentication

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

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

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

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

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

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

Batch Cancel Orders

This is used to cancel all open orders for specific trading pairs. For each request, orders for Up to 4 trading pairs and a maximum of 10 orders per trading pair can be canceled.

Rate limit: 20 requests per 2 seconds
HTTP Requests

POST /api/spot/v3/cancel_batch_orders

Example Request with Authentication

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

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

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

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

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

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

Order List

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/orders

Example Authenticated Request

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

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

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

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

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

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

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

Open Orders

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/orders\_pending

Example Authenticated Request

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

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

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

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

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

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

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

Order Details

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

or

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

Example Authenticated Request

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

or

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

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

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

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

Unfilled order status may change according to the market conditions.

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

Transaction Details

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

Rate limit: 20 requests per 2 seconds

HTTP Request

GET /api/spot/v3/fills

Example Authenticated Request

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

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

Transaction Fees

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

Liquidity

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

Pagination

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

Example Response
[
    [
        {
            "created_at":"2019-03-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"
    }
]

Public - Trading Pairs

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

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

Rate limit: 20 Requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments

Example Request

GET/api/spot/v3/instruments

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

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

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

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

Public - Order Book

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

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

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

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

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

Public - Trading Pairs

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments/ticker

Example Request

GET /api/spot/v3/instruments/ticker

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

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

The open_24 is the opening price exactly 24 hours ago.

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

Public - Trading Pair Information

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

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

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

The open_24 is the opening price exactly 24 hours ago.

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

Public - Filled Orders

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

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

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

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

Public - Market Data

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

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

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

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

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

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

Example Response

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

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

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/margin/v3/accounts

Example Request

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

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

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

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

Margin Account of a Currency

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

Rate limit: 20 / 2s
HTTP Requests

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

End Certificate Request Sample

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

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

Bills Details

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

Rate limit: 20/ 2s
HTTP Requests

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

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types Description
type String [optional]3. Borrow 4. Repayment 5. Interest 7. Buy 8. Sell 9. From Wallet 10. From C2C 11. From Futures 12. From Spot 13. From ETT 14. To Wallet 15. To C2C 16. To Spot 17. To Futures 18. To ETT 19. Mandatory Repayment 20. From Piggybank 21. To Piggybank 22. From Perpetual 23. To Perpetual 24. Liquidation Fee 54. Clawback 59. Airdrop Return. 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
rebate fee rebate as per our fee schedule
Return Sample
[
    [
        {
            "created_at":"2019-03-20T05:45:10.000Z",
            "ledger_id":"78965766",
            "timestamp":"2019-03-20T05:45:10.000Z",
            "currency":"EOS",
            "amount":"0",
            "balance":"0.59957711",
            "type":"transfer",
            "details":{
                "instrument_id":"EOS-USDT",
                "order_id":"787057",
                "product_id":"EOS-USDT"
            }
        },
        {
            "created_at":"2019-03-20T04:45:07.000Z",
            "ledger_id":"78942699",
            "timestamp":"2019-03-20T04:45:07.000Z",
            "currency":"EOS",
            "amount":"0",
            "balance":"0.59957711",
            "type":"transfer",
            "details":{
                "instrument_id":"EOS-USDT",
                "order_id":"787057",
                "product_id":"EOS-USDT"
            }
        },
        {
            "created_at":"2019-03-20T03:45:05.000Z",
            "ledger_id":"78918186",
            "timestamp":"2019-03-20T03:45:05.000Z",
            "currency":"EOS",
            "amount":"0",
            "balance":"0.59957711",
            "type":"transfer",
            "details":{
                "instrument_id":"EOS-USDT",
                "order_id":"787057",
                "product_id":"EOS-USDT"
            }
        }
    ],
    {
        "before":"78965766",
        "after":"78918186"
    }
]

Margin Account Settings

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

Rate limit:20 requests per 2 seconds
HTTP Request

GET /api/margin/v3/accounts/availability

Example Request

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

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

Margin Account Settings for a Currency

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

Rate limit:20/2s
HTTP Requests

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

End Certificate Request Sample

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

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

Get Loan History

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

Rate limit:20/2s
HTTP Requests

GET /api/margin/v3/accounts/borrowed

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types 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 String borrow ID
instrument_id String trading pair
currency String token
created_at String borrow time
amount String borrow amount
interest String interest
returned_amount String amount repaid
paid_interest String interest repaid
last_interest_time String last interest accrual time
force_repay_time String force repay time
rate String rate
Return Sample
[
    [
        {
            "amount":"0.5",
            "borrow_id":"787057",
            "created_at":"2019-03-18T09:41:44.000Z",
            "currency":"EOS",
            "force_repay_time":"2019-03-25T09:42:19.000Z",
            "instrument_id":"EOS-USDT",
            "interest":"0.0000386883807232",
            "last_interest_time":"2019-03-20T05:45:11.000Z",
            "paid_interest":"0.00000208",
            "product_id":"EOS-USDT",
            "rate":"0.00000416",
            "repay_amount":"0.29999792",
            "repay_interest":"0.00000208",
            "returned_amount":"0.29999792",
            "timestamp":"2019-03-18T09:41:44.000Z"
        }
    ],
    {
        "before":"787057",
        "after":"787057"
    }
]

Get Loan History of a Currency

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

Rate limit:20/2s
HTTP Requests

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

End Certificate Request Sample

2018-09-13T02:29:06.610ZGET/api/margin/v3/accounts/BTC-USDT/borrowed?limit=2&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 String borrow ID
currency String token
created_at String borrow time
amount String borrow amount
interest String interest
returned_amount String amount repaid
paid_interest String interest repaid
last_interest_time String Last interest accrual time
force_repay_time String force repay time
rate String rate
Return Sample
[
    [
        {
            "amount":"0.5",
            "borrow_id":"787057",
            "created_at":"2019-03-18T09:41:44.000Z",
            "currency":"EOS",
            "force_repay_time":"2019-03-25T09:42:19.000Z",
            "instrument_id":"EOS-USDT",
            "interest":"0.0000386883807232",
            "last_interest_time":"2019-03-20T05:45:11.000Z",
            "paid_interest":"0.00000208",
            "product_id":"EOS-USDT",
            "rate":"0.00000416",
            "repay_amount":"0.29999792",
            "repay_interest":"0.00000208",
            "returned_amount":"0.29999792",
            "timestamp":"2019-03-18T09:41:44.000Z"
        }
    ],
    {
        "before":"787057",
        "after":"787057"
    }
]

Loan

Borrowing tokens in a margin trading account.

Rate limit:100 requests per 2 seconds
HTTP Request

POST /api/margin/v3/accounts/borrow

Example Request

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

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

Repayment

Repaying tokens in a margin trading account.

Rate limit:100/2s
HTTP Requests

POST /api/margin/v3/accounts/repayment

End Certificate Request Sample

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

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

Place Order

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

Rate limit: 100 requests per 2 seconds
HTTP Request

POST /api/margin/v3/orders

Example Authenticated Request

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

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

client_oid

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

instrument_id

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

type

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

price

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

size

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

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

notional

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

hold

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

Order life cycle

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

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

Response

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

Example Response
{
    "client_oid":"oktlever50",
    "error_code":"",
    "error_message":"",
    "order_id":"2512084870235136",
    "result":true
}

Place Multiple Orders

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

Rate limit: 50 requests per 2 seconds
HTTP Request

POST /api/margin/v3/batch_orders

Example Request

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

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

Parameters

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

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

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

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

Cancel an Order

Cancelling an unfilled order.

Rate limit: 100 / 2s
HTTP Requests

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

End Certificate Request Sample

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

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

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

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

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

Cancel 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

POST /api/margin/v3/cancel_batch_orders

End Certificate Request Sample

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

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

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

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

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

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

Get Order List

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/margin/v3/orders

Example Authenticated Request

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

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

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

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

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

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

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

Get Order Details

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

Rate limit:20/2s
HTTP Requests

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

or

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

End Certificate Request Sample

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

or

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

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

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

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":"",
    "created_at":"2019-03-18T03:45:55.000Z",
    "filled_notional":"1.504",
    "filled_size":"0.4",
    "funds":"",
    "instrument_id":"EOS-USDT",
    "notional":"",
    "order_id":"2499854635054080",
    "order_type":"0",
    "price":"3.76",
    "product_id":"EOS-USDT",
    "side":"buy",
    "size":"0.4",
    "status":"filled",
    "state": "-2",       
    "timestamp":"2019-03-18T03:45:55.000Z",
    "type":"limit"
}

Get All Open Orders

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/margin/v3/orders\_pending

Example Authenticated Request

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

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

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

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

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

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

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

Get Transaction Details

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

Rate limit: 20 requests per 2 seconds

HTTP Request

GET /api/margin/v3/fills

Example Authenticated Request

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

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

Transaction Fees

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

Liquidity

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

Pagination

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

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

Margin Trading Market Data

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

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

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

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
Api is offline or unavailable 30019 400
Json data format error 30021 400
Api has been frozen 30022 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

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

Websocket API

This is the V3 Websocket API for spot and margin users. Except for the separate Account Channel, data of all channels are applicable to both spot and margin users.

General

Websocket is a new HTML5 Protocol. It achieves full-duplex data transmission between the client and the server, allowing data to be transferred effectively in both directions. With just only one handshake, the connection between the client and the server is established. The server will then be able to push data to the client according to preset rules. Its advantages include:

  • The Websocket request header for data transmission between client and server is only approximately 2 bytes
  • Either the client or server can initiate a data transmission
  • As there is no need to create and delete TCP connection repeatedly, it saves resources for both bandwidth and server

We strongly recommend developers to use Websocket API to retrieve market data and order book depth.

url:wss://real.okcoin.com:10442/ws/v3

Notes:

All the messages returning from Websocket API will be optimized by Deflate compression. All users will be required to decompress the messages by themselves with the methods they find most appropriate. Please refer to our demo.

The connection will break automatically if subscription is not established or data has not been pushed for more than 30s.

Command Format

Request format:

{"op": "<value>", "args": ["<value1>","<value2>"]}

the value of op 1-- subscribe 2--unsubscribe 3--login

args: the value is the channel name, which can be one or more channels

Successful response format:

  {"event": "<value>","channel":"<value>"}
  {"table":"channel","data":"[{"<value1>","<value2>"}]"}

In the spot/depth channel, the return formats for distinguishing between the first full amount and the subsequent incremental data are:


{"table":"channel", "action":"<value>","data":"[{"<value1>","<value2>"}]"}

Failure response format:

{"event":"error","message":"<error_message>","errorCode":"<errorCode>"}

Subscription

Users may subscribe to one or more channels,The total length of multiple channels should not exceed 4,096 bytes.

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

Note: the value of <op> is subscribe

The array content of <args> is channel names:<channelname>:<filter>

The <channelname> is composed of business/channel

The value of business is 'spot', and channel is the specific data name of the aforementioned business. If a <channelname> consists of more than one words, they will be connected with an underscore " _ ".

Example:

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

<Filter>> is data filterable. For details, please refer to the description of each channel

Example :

send:

{"op": "subscribe", "args": ["spot/ticker:ETH-USDT","spot/candle60s:ETH-USDT"]}

response:

 {"event":"subscribe","channel":"spot/ticker:ETH-USDT"}

 {"event":"subscribe","channel":"spot/candle60s:ETH-USDT"}

 {"table":"spot/ticker","data":[{"instrument_id":"ETH-USDT","last":"8.8","best_bid":"3","best_ask":"8.1","open_24h":"5.1","high_24h":"8.8","low_24h":"3","base_volume_24h":"13.77340909",
 "quote_volume_24h":"78.49886361","timestamp":"2018-12-20T03:13:41.664Z"}]}

 {"table":"spot/candle60s","data":[{"candle":["2018-12-20T06:18:00.000Z","8.8","8.8","8.8","8.8","0"],"instrument_id":"ETH-USDT"}]}

Cancel Subscription

Users can cancel one or more channels.

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

send:

{"op": "unsubscribe", "args": ["spot/ticker:BTC-USDT", "spot/candle60s:BTC-USDT"]}

response:

{"event":"unsubscribe","channel":"spot/ticker:BTC-USDT"}
{"event":"unsubscribe","channel":"spot/candle60s:BTC-USDT"}

Login

Please refer to the Authentication section to understand how a valid authenticated sign is made with requests.

Login subscription format:

{"op":"login","args":["<api_key>","<passphrase>","<timestamp>","<sign>"]

Response:

{"event":"login","success":"true"}

Example:

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

api_key:'api_key' is apply 'apiKey' for users

passphrase:The passphrase entered when creating the API key

timestamp: Must be number of seconds since unix-epoch in UTC Decimal values are allowed. The timestamp will expire for every 30 seconds. It is recommended to use the time endpoint to retrieve the server time if you find a large discrepancy between your server time and the API server.

sign:It is the authentication string. the description of generating a valid sign can be referred to in the Authentication section.

Example of timestamp:const timestamp = '' + Date.now() / 1000

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

methodis preset as'GET'。

requestPath is preset as '/users/self/verify'

If the login fails, the connection will be automatically cut.

Connect limit

Connection limit:once per second

Subscription limit:240 times per hour

If there is no data returned after connection to Websocket is established, the connection will break in 30 seconds. Users are advised to do the followings:

  • Set a timer each time that a response message is received.
  • If the timer is triggered, which means that no new message is received within N seconds, send the string 'ping'.
  • Expect a ‘pong’ as response message. If the response message is not received within 5 seconds, please signal an error alert or reconnect.

The connection will be cut if there happens a network problem.

Checksum

This function helps users verify the accuracy of depth data.

Every time when depth data is pushed, a timestamp and a checksum value are returned together. A total of 200 entries of depth data will be returned after the subscription is successfully established. And the depth data afterwards is incremental. Each time the incremental data is pushed, the crc 32 value comprised of the first 25 string of latest 200 depth data should be calculated by the users. And the result should be compared with the Checksum value provided together with the latest incremental data. If the Checksum are the same, the connection is correctly established, otherwise please re-subscribe the channel.

The notes of depth aggregation: A total of 200 entries of depth data will be returned after the subscription is successfully established, the depth data received afterwards is incremental. Then the 200 entries of the price of ask & bid array shall be traversed with the incremental data. If the prices match, look at the quantity. If the quantity is 0, then delete the depth data; if the quantity has changed, replace the original data; if the price cannot be matched, sort the entry by the price.

Calculation Description: The value of checksum is a signed integer (32 bit)

1,The following data is aligned with bid and ask, the checksum String will be bid:ask:bid:ask:....


"data": [{
        "instrument_id": "BTC-USDT",
        "asks": [["3366.8", "9", 10],[ "3368","8",3]],
        "bids": [
            ["3366.1", "7", 0],[ "3366","6",3 ]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1881014294
    }]

The checksum string of this example will be 3366.1:7:3366.8:9:3366:6:3368:8

2,If bid and ask data does not align , the checksum String will be bid:ask:ask:ask:....

"data": [{
        "instrument_id": "BTC-USDT",
        "asks": [["3366.8", "9", 10],[ "3368","8",3],[ "3372","8",3 ]],
        "bids": [
            ["3366.1", "7", 0]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": 831078360
    }]

The checksum String of this example will be 3366.1:7:3366.8:9:3368:8:3372:8

The pushed data of depth channel that user receives are:

First 200 entries


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

Increment:

{
    "table": "spot/depth",
    "action": "update",
    "data": [{
        "instrument_id": "BTC-USDT",
        "asks": [],
        "bids": [
            ["3983", "789", 0, 3]
        ],
        "timestamp": "2018-12-04T09:38:36.300Z",
        "checksum": -1200119424
    }]
}

Channel List

Channels that don't require login authentication includes: channels of market data, candlestick line, transaction data, fee rate, limit price spectrum, order book depth and mark price.

Channels that require login authentication includes: channels of account information, transaction information and positions.

Channels that don't require login

spot/ticker // ticker channel

spot/candle60s // 1mins candlestick

spot/trade // trade information

spot/depth //depth information,200 bids & asks for the first time, followed by incremental data

spot/depth5 //depth information, the best 5 bids & asks each time the request is returned

Channels that require login

spot/account //User's account information

spot/margin_account //User's margin account information

spot/order //User's order information

Public - Ticker

Retrieve the latest price, best bid & offer and 24-hours trading volume of a single contract.

Example Sends:
{"op": "subscribe", "args": ["spot/ticker:ETH-USDT"]}

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

Response
Parameter Type Description
instrument_id String Contract ID, e.g., BTC-USD-170310
last String Lst price
best_bid String Best bid price
best_ask String Best ask price
open_24h String 24-hour open
high_24h String 24-hour high
low_24h String 24-hour low
base_volume_24h String 24-hour trading volume of the base currency
quote_volume_24h String 24-hour trading volume of the quote currency
timestamp String Timestamp
response examples
{
    "table": "spot/ticker",
    "data": [{
        "instrument_id": "ETH-USDT",
        "last": "8.8",
        "best_bid": "5",
        "best_ask": "8.8",
        "open_24h": "6.6",
        "high_24h": "8.8",
        "low_24h": "4",
        "base_volume_24h": "85.68492053",
        "quote_volume_24h": "570.14238013",
        "timestamp": "2018-12-17T12:28:29.250Z"
    }]
}

Public - Candlestick

Retrieve the candlestick data

channel lists:

spot/candle60s // 1mins candlestick

spot/candle180s // 3mins candlestick

spot/candle300s // 5mins candlestick

spot/candle900s // 15mins candlestick

spot/candle1800s // 30mins candlestick

spot/candle3600s // 1hour candlestick

spot/candle7200s // 2hour candlestick

spot/candle14400s // 4hour candlestick

spot/candle21600 // 6hour candlestick

spot/candle43200s // 12hour candlestick

spot/candle86400s // 1day candlestick

spot/candle604800s // 1week candlestick

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

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

response parameters
Parameters Parameters Types Description
timestamp String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
currency_volume String The trading volume in a specific token
instrument_id String Trading pair
response examples
{
    "table": "spot/candle60s",
    "data": [{
        "candle": ["2018-12-18T02:55:00.000Z", "8.8", "8.8", "8.8", "8.8", "0"],
        "instrument_id": "ETH-USDT"
    }]

}

Public - Trade

Get the filled orders data

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

spot/trade is the channel nameETH-USDT is instrument_id

response parameters
Parameters Parameters Types Description
trade_id String Transaction id
price String Filled price
size String Filled size
side String Filled side (buy/sell)
timestamp String Filled time
instrument_id String Trading pair
Example Response

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

Public - Depth5

Back to the previous five entries of depth data,This data is snapshot data per 100 milliseconds.For every 100 milliseconds, we will snapshot and push 5 entries of market depth data of the current order book.

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

spot/depth5 is channel nameETH-USDT is instrument_id

response parameters
Parameter Type Description
price String price
size String Size
timestamp String timestamp
num_orders String total orders in the book
instrument_id String trading pair

bids and asks value example: In [“411.8”,”10”,8”], 411.8 is price depth, 10 is price amount, 8 is the orders depth.

response examples

{
    "table": "spot/depth5",
    "data": [{
        "asks": [
            ["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"

Public - Depth

After subscription, 200 entries of market depth data of the order book will first be pushed. Subsequently every 100 milliseconds we will snapshot and push entries that have changed during this time.

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

spot/depth is channel nameETH-USDT is trading pair

Response
Parameter Types Description
price String price
size String Size
timestamp String Timestamp
num_orders String Total orders in the book
instrument_id String Trading pair
checksum String Checksum

bids and asks value example: In [“411.8”,”10”,8”], 411.8 is price depth, 10 is price amount, 8 is the orders depth.

Example Response
 First 200 entries 


{
    "table": "spot/depth",
    "action": "partial",
    "data": [{
        "instrument_id": "ETH-USDT",
        "asks": [
            ["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

Retrieve the user's spot account information (login authentication required).

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

spot/account is the channel name,BTC is the currency

Response
Parameters type Description
currency String Token symbol
balance String Remaining balance
hold String Amount on hold(not available)
available String Available amount for trading or transfer
id String Account id
response examples
{
    "table": "spot/account",
    "data": [{
        "balance": "881.5011237890123457",
        "available": "868.4011237890123457",
        "currency": "USDT",
        "id": "6916752",
        "hold": "13.1"
    }]
}

User Margin Account

Retrieve the user's margin account information (login authentication required).

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

spot/margin_account is channel nameETH-USDT is instrument_id

response parameters
Parameters Parameters type Description
instrument_id String Trading pair
balance String Remaining balance
hold String Amount on hold(not available)
available String Available amount for trading or transfer
borrowed String Borrowed tokens (unpaid))
lending_fee String Interest (unpaid)
response example
{
"table”:”spot/margin_account”,
"data”:[
{
"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

Retrieve the user's transaction information (login authentication required).

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

spot/order is channel nameLTC-USDT is instrument_id

Response
Parameters Type Description
order_id String Order ID
client_oid String Client supplied order ID
price String Price
size String Size of the order in the unit of the quote currency
notional String The amount allocated for buying. Returned for market orders
instrument_id String Trading pair
side String Buy or sell
type String limit,market(defaulted as limit)
timestamp String Time of order creation
filled_size String Quantity of order filled
filled_notional String Amount of order filled
margin_trading String 1 spot order. 2 margin order
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
last_fill_px String Latest Filled Price. '0' will be returned if the data is empty
last_fill_qty String Latest Filled Volume. '0' will be returned if the data is empty.
last_fill_time String Latest Filled Time. The '1970-01-01T00:00:00.000Z' will be returned if the data is empty.
state String Order Status(-2:Failed,-1:Canceled,0:Open ,1:Partially Filled, 2:Fully Filled,3:Submitting,4:Cancelling,)
Notes

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

Example Response
{
    "table": "spot/order",
    "data": [{
        "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",
        "state": "0",    
        "timestamp": "2018-12-19T09:20:24.608Z",
        "type": "limit",
        "last_fill_px": "1",
        "last_fill_qty": "1",
        "last_fill_time": "2018-12-19T09:20:24.608Z"
    }]
}

error code

error message format:

{"event”:”error”,” message”:” ",”errorCode”:”"}

Example
Description Code
OK_ACCESS_KEY cannot be blank 30001
OK_ACCESS_SIGN cannot be blank 30002
OK_ACCESS_PASSPHRASE cannot be blank 30004
Invalid OK_ACCESS_TIMESTAMP 30005
Invalid OK_ACCESS_KEY 30006
Timestamp request expired 30008
Invalid sign 30013
Requested too frequent; endpoint limit exceeded 30026
Login failure 30027
Unrecognized request 30039
{0} Channel : {1} doesn't exist 30040
User not logged in / User must be logged in 30041
Already logged in 30042
Internal system error 30043

Change Log

【2019-4-28】

Spot trading order status fetch is not available.

Spot, margin, futures and perpetual swap

rest: Get Order List, Get All Open Orders, Get Order Details, Add Parameters state String Order Status("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling, "6": Incomplete (open + partially filled), "7":Complete (cancelled + fully filled) )

ws:order add parameters state String Order Status("-2":Failed,"-1":Cancelled,"0":Open,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling, )

【2019-04-26】

spot:The return parameters in the depth channel,depth5 channel,trade channel of spot websocket will be unified into the String type.

【2019-04-24】

public error_code and error_message add:

30019 400 Api is offline or unavailable 30021 400 Json data format error 30022 401 Api has been frozen

【2019-3-27】

For spot and margin trading, use client_oid to cancel multiple orders. The order cancelation function has been upgraded from 1 order per trading pairs to 10 orders per trading pairs. Request example after the launch: 2018-10-12T07:30:49.664ZPOST/api/spot/v3/cancel_batch_orders[{"instrument_id":"btc-usdt","client_oids”:[“A1600593327162368”,”A1600593327162369”]},{“instrument_id":"ltc-usdt","client_oids”:[“A243464”,”A234465”]}]

Spot, margin

New parameters added in web socket order channel: "last_fill_px”, ”last_fill_qty”, and “last_fill_time”

【2019-01-21】

Spot, margin Modification: modified the return value format for kline endpoints

FAQ


 1、How do I withdraw tokens from my sub account to an external address?

First, transfer your tokens to your sub account’s wallet, you can then transfer them to your main account wallet through the fund transfer port and withdraw your tokens there.

2、Is there any limit on the numbers of API order cancellation?

There are no limitations.

3、How did Http status code 429 happen?

Your visit frequency is too high. Please lower the frequency.

4、My API v3 account generated a new key. Do I have to use API v3 to send requests?

Yes, v1 and v3 are independent APIs. You must use a V1 key for a v1 API and v3 key for v3 API.

5、Why I cannot check on order details using the order ID returned from a canceled order?

Only the history of the canceled unfulfilled orders in the last 2 hours are kept in our system.

6、Can I use v3 key with okcoin.co?

The API address on our documents has always been “www.okcoin.com”. The domain name “www.okcoin.co” was only created to allow mainland Chinese users to access our website without VPN. There are no contradictions in the two addresses. Please fill in your request address according to our documents.

7、Can I use the API of the main account to check the balance of my sub account?


No, main accounts and sub accounts use independent APIs.

8、How many API keys can I apply for an account?

50.

9、How many entries of historical data can the K charts API obtain?

The K charts API can only obtain the most recent 2,000 entries of data.

10、Can I change the leverage level of my perpetual swap and futures contracts through API?

Yes, you can.

11、Are the return data different when using different keys in the same account?

The data is the same as they point at the same account.


12、What is the order unit when using v3 to make an order?

The order unit is 1, or multiples of 1.

13、Do I have to fill in my IP address when creating an API v3 key?

No, it’s not mandatory to enter your IP address, but we suggest you do so to make your account more secure.

14、Why did my API timeout?

Your network has timeout. Please check your network and use the Hong Kong Alibaba Cloud server instead.

15、Can I increase margin with v3 API?

No, you can only do so on the website.


16、What is the okcoin API visit frequency limit based on?

The limit for public data is based on IP, and that for individual data is based on User ID.

17、Will my IP address be banned if the API exceeds the visit frequency? How long will it be banned?

No, you won’t be banned. You only have to lower your visit frequency.

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