README


Welcome to use RicherEx API.

API Summarize

Market overview and general information.

Matching Engine

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

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

Filled Price

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

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

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

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

Order Life Cycle

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

Token Trading Price Limit Rules

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

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

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

Fees

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

  • Trading Fees
  • Deposit/Withdrawal Fees

Trading Fees

To encourage more order placement and liquidity, richerex adopts a marker-taker fee schedule, which the maker fee is lower than the taker fee. The fee schedule is volume-based, to be eligible for a tier, you are required to meet the minimum trading volume requirements. The higher the tier you are in, the lower the fees you can enjoy. Aside from tiered-volume fees discount, our market maker program specifically rewards traders who intend to provide consistent liquidity and competitive bid-ask spread.

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

Deposit/Withdrawal Fees

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

Data Centers

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

Request

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

  • Introduction
  • Errors
  • Success

Introduction

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

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

Errors

Unless otherwise stated, errors to bad requests will respond with HTTP 4xx or status codes. The body will also contain a message parameter indicating the cause. Your language’s http library should be configured to provide message bodies for non-2xx requests so that you can read the message field from the body.

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

Success

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

Pagination

richerex uses cursor pagination for all REST requests which return arrays. Cursor pagination allows for fetching results before and after the current page of results and is well suited for real time data. Endpoints like /trades, /fills, /orders, return the latest items by default. To retrieve more results subsequent requests should specify which direction to paginate based on the data previously returned.

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

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

To request a page of records before the current one, use the from query parameter. Your initial request can omit this parameter to get the default first page.

The response will contain a OK-FROM header which will return the cursor id to use in your next request for the page before the current one. The page before is a newer page and not one that happened before in chronological time.

The response will also contain a OK-To header which will return the cursor id to use in your next request for the page after this one. The page after is an older page and not one that happened after this one in chronological time.

Example If the ID’s of the returned results are: 111, 112, 113, 114, 115, 116, 117, 118, 119, 120 Then they will be ordered in: 120, 119, 118, 117, 116, 115, 114, 113, 112, 111 The OK-FROM ID is now 120, and the OK-TO ID is now 111. If you want to access to updated data such as data after 120, then you will have to use the before parameters. For example: orders?from=120&limit=5 will return the 5 strings of data after 120, which is 125, 124, 123, 122, 121

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

GET /orders?from=2&limit=30

Rules

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

  • Timestamps
  • Numbers
  • IDs

Timestamps

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

Example

2014-11-06T10:34:47.123Z

Numbers

Decimal numbers are returned as strings to preserve full precision across platforms. When making a request, it is recommended that you also convert your numbers to strings to avoid truncation and precision errors.

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

IDs

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

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

Endpoints

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

  • Public Endpoints
  • Private Endpoints

Public Endpoints

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

Private Endpoints

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

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

Rate Limits

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

  • REST API
  • WebSocket

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

REST API

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

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

Special note: when placing multiple orders, every four trading pairs with 10 orders for each pair is counted as one request.

WebSocket

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

Authentication

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

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

Generating an API Key

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

API Key

Secret

Passphrase

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

Creating a Request

All REST requests must contain the following headers:

OK-ACCESS-KEY The api key as a string.

OK-ACCESS-SIGN The base64-encoded signature (see Signing a Message).

OK-ACCESS-TIMESTAMP A timestamp for your request.

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

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

Signing a Message

The OK-ACCESS-SIGN header is generated by creating a sha256 HMAC using the base64-decoded secret key on the prehash string timestamp + method + requestPath + body (where + represents string concatenation), secretKey and base64-encode the output. For example: sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(timestamp + 'GET' + '/users/self/verify', secretKey))

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

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

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

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

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

public enum ContentTypeEnum {

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


    private String contentType;

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

    public String contentType() {
        return contentType;
    }
}


public enum HttpHeadersEnum {

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

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

    private String header;

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

    public String header() {
        return header;
    }
}

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

public class APIHttpClient {

    private APIConfiguration config;
    private APICredentials credentials;

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

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

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

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

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

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

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

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

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

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



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

import java.util.List;

interface FuturesMarketAPI {

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

}

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



public class FuturesMarketAPIServiceImpl implements FuturesMarketAPIService {

    private APIClient client;
    private FuturesMarketAPI api;

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

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

}

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

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

public class APIClient {

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

}

public class FuturesAPIBaseTests extends BaseTests {

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

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

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

        return config;
    }

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



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

import java.util.List;

public class FuturesMarketAPITests extends FuturesAPIBaseTests {

    private FuturesMarketAPIService marketAPIService;

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

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


}
package richerex

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.richerex.com/
    Endpoint string
    // The user's api key provided by richerex.
    ApiKey string
    // The user's secret key provided by richerex. The secret key used to sign your request data.
    SecretKey string
    // The Passphrase will be provided by you to further secure your API access.
    Passphrase string
    // Http request timeout.
    TimeoutSecond int
    // Whether to print API information
    IsPrint bool
    // Internationalization @see file: constants.go
    I18n string
}

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


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

    client := NewClient(config)
    return client
}



import "testing"

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

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

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

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

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

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

    delete []timestamp;
    return str;
}


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

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

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

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

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

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

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


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


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


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

    return url[0:-1]


# request example
# set the request url
base_url = 'https://www.richerex.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.richerex.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.richerex.com'
request_path = '/api/spot/v3/orders'

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

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

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

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

Timestamp

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

Your timestamp must be within 30 seconds of the api service time or your request will be considered expired and rejected. We recommend using the time endpoint to query for the API server time if you believe there many be time skew between your server and the API servers.

Getting Server Time

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

HTTP Requests

GET /api/general/v3/time

Return Parameters
Parameters Description
iso ISO 8601 format
epoch Unix Epoch in UTC
Return Sample
{

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

"epoch": 1420674445.201

}

Wallet API

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

Get Currencies

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

Limit: 20 times / 2s
HTTP Requests

GET /api/account/v3/currencies

Request Sample

GET /api/account/v3/currencies

Return Parameters
Parameters Parameters Types Description
currency String Token code
name String Token name
can_deposit String availability of depositing, 0 = not available,1 = available
can_withdraw String availability of withdrawal,0 = not available,1 = available
min_withdrawal String the minimum withdrawal limit
Return Sample
    {
         "can_deposit":"1",
         "can_withdraw":"1",
         "currency":"BTC",
         "min_withdrawal":"0.01",
         "name":""
     },
     {
         "can_deposit":"1",
         "can_withdraw":"1",
         "currency":"LTC",
         "min_withdrawal":"0.1",
         "name":""
     }

Wallet Information

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

Limit: 20 times / 2s
HTTP Requests

GET /api/account/v3/wallet

Request Sample

GET /api/account/v3/wallet

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

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

Wallet of a Currency

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

Limit: 20 times / 2s
HTTP Requests

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

Request Sample

GET /api/account/v3/wallet/XMR

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

Funds Transfer

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

Limit: 20 times / 2s
Limit: 1 time / 2s (Counted Per each token)
HTTP Requests

POST /api/account/v3/transfer

Request Sample

POST /api/account/v3/transfer

Request Parameters
Parameters Parameters Types Required Description
currency String Yes Token
amount String Yes Transfer amount
from String Yes the remitting account (0: sub account 1: spot 4:C2C 6: Funding Account )
to String Yes the beneficiary account(0: sub account 1:spot 4:C2C 6: Funding Account )
sub_account String No sub account name
instrument_id String No Margin trading pair transferred out, for supported pairs only
to_instrument_id String No Margin trading pair transferred in, for supported pairs only
Return Parameters
Parameters Parameters Types Description
transfer_id String Transfer ID
currency String Token to be transferred
from String The remitting account
amount String Transfer amount
to String The beneficiary account
result Boolean Transfer result. An error code will be displayed if it failed.
Explanation

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

When ‘from’ is 0, ‘to’ is only can be 6 (that is, the funding account of the sub-account can only be transferred to the funding account of the main account).

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

"to" is specified to 1-9, and when "sub_account" is filled with a sub-account ID, user may transfer fund from the main account to the sub-account's corresponding spot or derivative account directly.

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

Withdrawal

Limit: 20 times / 2s
HTTP Requests

POST /api/account/v3/withdrawal

Request Sample

POST /api/account/v3/withdrawal

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

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

Withdrawal Fees

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

Limit: 20 times / 2s
HTTP Requests

GET /api/account/v3/withdrawal/fee

Request Sample

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

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

Recent Withdrawal History

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

Limit: 20 times / 2s
HTTP Requests

GET /api/account/v3/withdrawal/history

Request Sample

GET /api/account/v3/withdrawal/history

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

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

Return Sample

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

Recent Withdrawal History of a Currency

This endpoint retrieves the withdrawal history of a specific token.

Limit: 20 times / 2s
HTTP Request

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

Request Sample

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

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

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

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

Bills Details

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

Limit: 20 times / 2s
HTTP Requests

GET /api/account/v3/ledger

Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
currency String No token ,information of all tokens will be returned if the field is left blank
type String No 1:deposit 2:withdrawal 13:cancel withdrawal 20:into sub account 21:out of sub account 37: into spot account 38: out of spot account
from String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
to String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
ledger_id String bill ID
currency String token
balance String remaining balance
amount String quantity
typename String type of bills
fee String service fees
timestamp String creation time
Return Sample
{
        "amount":"0.00100941",
        "balance":0,
        "currency":"BTC",
        "fee":0,
        "ledger_id":9260348,
        "timestamp":"2018-10-19T01:12:21.000Z",
        "typename":"To: spot account"
    },
    {
        "amount":0.00051843,
        "balance":0.00100941,
        "currency":"BTC",
        "fee":0,
        "ledger_id":8987285,
        "timestamp":"2018-10-12T11:01:14.000Z",
        "typename":"Get from activity"
    }

Get Deposit Address

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

Limit: 20 times / 2s
HTTP Requests

GET /api/account/v3/deposit/address

Request Sample

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

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

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

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

Return Sample

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

Get Deposit History of All Currencies

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

Limit: 20 times / 2s
HTTP Requests

GET /api/account/v3/deposit/history

Request Sample

GET /api/account/v3/deposit/history

Return Parameters
Parameters Parameters Types Description
currency String token
amount String deposit amount
from String Deposit address, only display internal account transfer address, blockchain deposit address will not be displayed
to String Receiving Address
txid String TXID
timestamp String deposit arrival date
state String The state of deposit (0: waiting for confirmation; 1: confirmation account; 2: recharge success);
Return Sample
{
        "amount":"0.01044408",
        "txid":"1915737_3_0_0_WALLET",
        "currency":"BTC",
        "to":"",
        "timestamp":"2018-09-30T02:45:50.000Z",
        "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"
    }

Get Deposit History of a Currency

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

Limit: 20 times / 2s
HTTP Requests

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

Request Sample

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

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

Token Trading API

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

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

Please refer to the parameter description in the documentation,For example, the returned parameters of frozen, hold are the same with holds of spot trading account, take hold as the criterion.

Spot Trading Account

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

Rate limit: 20 /2s
HTTP Requests

GET /api/spot/v3/accounts

End Certificate Request Sample

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

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

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

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

Spot Trading Account of a Currency

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

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

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

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

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

Bills Details

All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first. This API can retrieve data in the last 3 months.

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

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

Parameters Parameters Types Required Description
currency String Yes token
from String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
to String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)
type String No 1 .Deposit 2 .Withdraw 7 .Buy 8 .Sell 13 .Canceled Withdrawal 20 .Transfer from Sub-account 21 .Transfer to Sub-account 25 .C2C Buy 26 .C2C Sell 29 .Transfer to Assets Account 30 .Transfer from Assets Account 31 .Transfer to C2C Account 32 .Transfer from C2C Account 46 .Transfer from Spot Account 47 .Transfer to Spot Account
Return Parameters
Parameters Parameters Types Description
ledger_id String bill ID
balance String balance
currency String token
amount String amount
type String type of bills
timestamp String creation time
details String if the type is trade or fee, order details will be included under this
order_id String order ID
instrument_id String trading pair
Explanation

The following is the enumeration value for the parameters types

Type value Description
transfer funds transfer
trade funds moved as a result of a trade
rebate fee rebate as per our fee schedule
Return Sample
[
    {
        "timestamp":"2019-03-18T07:26:50.000Z",
        "ledger_id":"3995466151",
        "created_at":"2019-03-18T07:26:50.000Z",
        "currency":"BTC",
        "amount":"0.0009985",
        "balance":"0.0049925",
        "type":"trade",
        "details":{
            "instrument_id":"BTC-USDT",
            "order_id":"2500723297813504",
            "product_id":"BTC-USDT"
        }
    },
    {
        "timestamp":"2019-03-18T07:26:50.000Z",
        "ledger_id":"3995466150",
        "created_at":"2019-03-18T07:26:50.000Z",
        "currency":"BTC",
        "amount":"0.0009985",
        "balance":"0.003994",
        "type":"trade",
        "details":{
            "instrument_id":"BTC-USDT",
            "order_id":"2500723297223680",
            "product_id":"BTC-USDT"
        }
    },
    {
        "timestamp":"2019-03-18T07:08:25.000Z",
        "ledger_id":"3995334780",
        "created_at":"2019-03-18T07:08:25.000Z",
        "currency":"BTC",
        "amount":"0.0009985",
        "balance":"0.0029955",
        "type":"trade",
        "details":{
            "instrument_id":"BTC-USDT",
            "order_id":"2500650881647616",
            "product_id":"BTC-USDT"
        }
    }
]

Place an Order

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

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

Rate limit: 100/2s
HTTP Requests

POST /api/spot/v3/orders

End Certificate Request Sample

2018-10-12T07:30:49.664ZPOST/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'}

Request Parameters
Parameters Parameters Types Required Description
client_oid String No the order ID customized by yourself , The client_oid type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported
type String No limit / market(default: limit),When posting orders at market price, order_type can only be 0 (regular order)
side String Yes buy or sell
instrument_id String Yes trading pair
order_type String No Fill in number for parameter,0: Normal limit order (Unfilled and 0 represent normal limit order) 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
Limit Order Parameters
Parameters Parameters Types Required Description
price String Yes price
size String Yes quantity bought or sold
Market Order Parameters
Parameters Parameters Types Required Description
size String Yes quantity sold. (for orders sold at market price only)
notional String Yes amount bought. (for orders bought at market price only)
Return Parameters
Parameters Parameters Types Description
order_id String order ID
client_oid String the order ID customised by yourself
result Boolean result of the order. Error message will be returned if the order failed.
error_code String Error code for order placement. Success = 0. Failure = error code
error_message String It will be blank if order placement is success. Error message will be returned if order placement fails.
Explanation

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

instrument_id

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

client_oid

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

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

type

When placing an order, you can specify the order type. The order type you specify will influence which other order parameters are required as well as how your order will be executed by the matching engine. If type is not specified, the order will default to a limit order.

limit orders are both the default and basic order type. A limit order requires specifying a price and size. The size is the number of tokens to buy or sell, and the price is the price per bitcoin. The limit order will be filled at the price specified or better. A sell order can be filled at the specified price per token or a higher price per token and a buy order can be filled at the specified price or a lower price depending on market conditions. If market conditions cannot fill the limit order immediately, then the limit order will become part of the open order book until filled by another incoming order or cancelled by the user.

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

price

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

size

Size is the quantity of buying or selling and must be larger than the min_size. size_increment is the minimum increment size. The above parameters 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 quote currency when placing market orders, it is required for market orders. For example, a market buy for BTC-USDT with funds specified as 5000 will spend 5000 USDT to buy BTC.

hold

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

Order Lifecycle

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

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

Response

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

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

Cancel an Order

Cancelling an unfilled order.

Rate limit: 100/2s
HTTP Requests

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

or

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

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes By providing this parameter, the corresponding order of a designated trading pair will be cancelled. If not providing this parameter, it will be back to error code.
client_oid String Yes the order ID created by yourself, The client_oid type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported
order_id String Yes order ID
Return Parameters
Parameters Parameters Types Description
order_id String order ID
client_oid String the order ID created by yourself
result Boolean order cancellation result. Error code will be returned if it failed
Explanation

Only fill in either parameter client_oid or order_id

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

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

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, this endpoints supports cancelling all open orders for a specific trading pair or several trading pairs. Maximum 10 orders can be cancelled at a time for each trading pair

Rate limit: 50/2s
HTTP Requests

POST /api/spot/v3/cancel_batch_orders

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
order_ids list<String> Yes order ID. You may cancel up to 4 orders of a trading pair
instrument_id String Yes by providing this parameter, the corresponding order of a designated trading pair will be cancelled. If not providing this parameter, it will be back to error code.
client_oids List<String> Yes The client_oid type should be comprised of alphabets + numbers or only alphabets within 1 – 32 characters, both uppercase and lowercase letters are supported
Return Parameters
Parameters Parameters Types Description
order_id list<String> order ID
client_oid String the order ID created by yourself
result Boolean order cancellation result. Error code will be returned if it failed
Explanation

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

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

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

Return Sample
{
    "btc-usdt":[
    {
       "result":true,
        "client_oid":"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

List your orders. Cursor pagination is used. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.This API can retrieve data in the last 3 months.

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/orders

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes list the orders of specific trading pairs
after String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
before String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)
state String No Order state("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling,"6": Incomplete(open+partially filled),"7":Complete(cancelled+fully filled))
Return Parameters
Parameters Parameters Types Description
order_id String order ID
client_oid String the order ID customised by yourself
price String price
size String quantity
notional String the total buying amount. This value will be returned for market orders
instrument_id String trading pair
type String limit,market(defaulted as limit)
side String buy or sell
timestamp String trading pair
filled_size String quantity filled
filled_notional String amount filled
state String order state
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
state String Order state("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully Filled,"3":Submitting,"4":Cancelling,)
price_avg String Average price
Explanation

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

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

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

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

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

Return Sample
[
    [
        {
            "client_oid":"oktspot76",
            "created_at":"2019-03-18T07:26:49.000Z",
            "filled_notional":"3.9734",
            "filled_size":"0.001",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2500723297813504",
            "order_type":"0",
            "price":"4013",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "state":"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",
            "state":"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",
            "state":"filled",
            "state": "2",     
            "timestamp":"2019-03-18T07:08:24.000Z",
            "type":"limit"
        }
    ],
    {
        "before":"2500723297813504",
        "after":"2500650881647616"
    }
]

Get All Open Orders

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

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/orders_pending

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id String Yes trading pair
after String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
before String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
order_id String order ID
client_oid String the order ID customised by yourself
price String price
size String quantity
notional String the total buying amount. This value will be returned for market orders
instrument_id String trading pair
side String buy or sell
type String limit,market(defaulted as limit)
timestamp String order creation date
filled_size String quantity filled
filled_notional String amount filled
state String Order Status("0":Open ,)
Explanation

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

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

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

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

Return Sample
[
    [
        {
            "client_oid":"oktspot86",
            "created_at":"2019-03-20T03:28:14.000Z",
            "filled_notional":"0",
            "filled_size":"0",
            "funds":"",
            "instrument_id":"BTC-USDT",
            "notional":"",
            "order_id":"2511109744100352",
            "order_type":"0",
            "price":"3594.7",
            "product_id":"BTC-USDT",
            "side":"buy",
            "size":"0.001",
            "state":"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",
            "state":"open",
            "state": "0",     
            "timestamp":"2019-03-20T03:28:10.000Z",
            "type":"limit"
        }
    ],
    {
        "before":"2511109744100352",
        "after":"2511109459543040"
    }

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/spot/v3/orders/<order_id>

or

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

End Certificate Request Sample

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

or

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

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

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

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

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

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

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

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

Get Transaction Details

Get details of the recent filled orders. Cursor pagination is used. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first. This API can retrieve data in the last 3 months.

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/fills

End Certificate Request Sample

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

Requests Parameters
Parameters Parameters Types Required Description
order_id String Yes order ID
instrument_id String Yes trading pair
from String No Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
to String No Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
ledger_id String bill ID
instrument_id String trading pair
price String price
size String quantity
order_id String order ID
timestamp String create date
exec_type String liquidity side (T or M)
fee String liquidity side
side String bills side(buy ,sell or points_fee)
Explanation

Liquidity

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

Pagination

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

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

Get Token Pair Details

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

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

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/instruments

End Certificate Request Sample

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

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

Min_size is the quantity of buying or selling . Base_increment is the minimum increment size. If the base_increment is 0.000001, entering a size of 0.0.0000126 will be adjusted to 0.000012.

The tick size is the smallest unit of price. The order price must be a multiple of the tick_size. If the tick_size is 0.0001, entering a price of 0.02237 will be adjusted to 0.0223 instead.

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

Get Order Book

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

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

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

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

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

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

Get All Token Pairs Information

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

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/instruments/ticker

End Certificate Request Sample

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

Return Parameters
Parameters Parameters Types Description
instrument_id String trading pair
last String last traded price
best_bid String best bid price
best_ask String best ask price
open_24h String 24 hour open
high_24h String 24 hour high
low_24h String 24 hour low
base_volume_24h String 24 trading volume of the base currency
quote_volume_24h String 24 trading volume of the quote currency
timestamp String timestamp
Explanation

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

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

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

Get a Token Pair Information

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

Rate limit: 20 / 2s
HTTP Requests

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

End Certificate Request Sample

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

Requests Parameters
Parameters Parameters Types Description
instrument_id String [required]trading pair
Return Parameters
Parameters Parameters Types Description
instrument_id String trading pair
last String last traded price
best_bid String best bid price
best_ask String best ask price
open_24h String 24 hour open
high_24h String 24 hour high
low_24h String 24 hour low
base_volume_24h String 24 trading volume of the base currency
quote_volume_24h String 24 trading volume of the quote currency
timestamp String timestamp
Explanation

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

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

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

Get Filled Orders Information

Get the recent 60 transactions of all trading pairs. Cursor pagination is used. All paginated requests return the latest information (newest) as the first page sorted by newest (in chronological time) first.

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

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

Requests Parameters
Parameters Parameters Types Description
after String Request page before (older) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
before String Request page after (newer) this pagination id,the parameter are order_id, ledger_id or trade_id of the endpoint, etc.
limit String Number of results per request. Maximum 100. (default 100)
instrument_id String [required] trading pairs
Return Parameters
Parameters Parameters Types Description
timestamp String filled time
trade_id String transaction time ID
price String filled price
size String filled size
side String filled side
Explanation

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

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

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

Get Market Data

Get the charts of the trading pairs.This API can retrieve the latest 2000 entries of data. Charts are returned in grouped buckets based on requested granularity,Maximum 2,000 recent Strings of chart data can be retrieved.

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

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

Requests Parameters
Parameters Parameters Types Description
start String [optional]start time in ISO 8601
end String [optional] end time in ISO 8601
granularity String [optional] desired timeslice in seconds
instrument_id String [required] trading pairs
Return Parameters
Parameters Parameters Types Description
time String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
Explanation

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

The granularity field must be one of the following values: {60, 180, 300, 900, 1800, 3600, 7200, 14400, 43200, 86400, 604800}. Otherwise, your request will be rejected. These values correspond to timeslices representing one minute, three minutes, five minutes, fifteen minutes, thirty minutes, one hour, two hours, six hours, twelve hours, one day, and 1 week respectively.

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

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

Return Sample

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

WebsocketAPI

Spot

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

General

WebSocket protocol is a new HTML5 protocol, which provides full-duplex communication between web browsers and web servers. Connection can be established after one handshake. Web server can then push business logic data to web browsers.Advantages:

Request header is small in size (around 2 bytes) during communication Since there is no need to create and delete TCP connection repeatedly, it saves resources We strongly recommend developers to use Websocket API to access market related information and trading depth. Should you have any questions, feel free to contact our support team.

We strongly recommend developers to use Websocket API to access market related information and trading depth.

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

The connection will break automatically when a network problem occurs

url:wss://real.okex.com:8443/ws/v3?brokerId=

Command Format

send format:

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

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

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

Successful response format:

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

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


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

Failure response format:

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

Subscription

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

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

Description : the value of op is subscribe

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

The channel name is composed of business/channel

spot push business is spot, channel for each specific name under this business, If a channel name consists of two separate words, they will be connected with an underscore " _ "

Example:

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

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

Example :

send:

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

response:

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

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

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

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

Unsubscription

Users can cancel one or more channels.

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

send:

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

response:

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

Login

The login method description can be found in the verification part in the API overview

Login subscription format:

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

Response:

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

Example:

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

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

passphrase:The passphrase entered when subscribing the apikey

timestamp: Must be number of seconds since unix-epoch in UTC Decimal values are allowed,your timestamp must be within 30 seconds of the api service time or your request will be considered expired and rejected, We recommend using the time endpoint to query for the API server time if you believe there many be time skew between your server and the API servers.

sign:is a signing String. The signing rules can be seen in the request description (API overview and validation part).A passphrase should be filled when applying for v3 API

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

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

methodis preset as'GET'。

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

If the login fails, the link will be automatically disconnected.

Connect limit

Connection limit:1 times/s

Subscription limit:240 times/hour

if there is no data return after connecting to ws, the connection will break in 30s.Users are advised to do the followings:

Set a timer after receiving a message. If the timer is triggered (no new message received within N seconds) send the String 'ping'.Expect a text String 'pong' as a response. If you do not receive it within 5 seconds, please issue an error or reconnect.

Checksum

This function can help users verify the accuracy of depth data.

Checksum rule: Every time when depth data is pushed, a timestamp and a checksum check are added. Take the price and quantity in the first 25 entries of bids and asks data out of the 200 entries of depth data after each data merge, and use the crc32 value of the String comprised of the price and number connected by a colon. User can compare the value of their checksum with the checksum value of the subscription. If there is no match, the users can re-subscribe. This function can help users verify the accuracy of depth data.

Instructions of depth merge: 200 entries of depth data for the first time, Then take the data of each increment and scan the prices in the asks and bids in the 200 entries. If the prices match, look at the quantity. If the quantity is 0, then delete the depth data; if the quantity has changed, replace the original data; if the price cannot be matched, sort the entry by the price.

Calculation Description: A checksum message will be sent every book iteration,where CHECKSUM is a signed integer (32-bit)

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

(see the following example)


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

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

2,If bid and ask data does not align , the checksum String will be bid:ask:ask:ask:.... (see the following example)

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

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

The push data depth channel users receive is:

First 200 amount


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

Increment:

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

Channel List

Channels that don't require login

spot/ticker // ticker channel

spot/candle60s // 1mins kline channel

spot/candle180s // 3mins kline channel

spot/candle300s // 5mins kline channel

spot/candle900s // 15mins kline channel

spot/candle1800s // 30mins kline channel

spot/candle3600s // 1hour kline channel

spot/candle7200s // 2hour kline channel

spot/candle14400s // 4hour kline channel

spot/candle21600 // 6hour kline channel

spot/candle43200s // 12hour kline channel

spot/candle86400s // 1day kline channel

spot/candle604800s // 1week kline channel

spot/trade // trade information

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

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

Channels that require login

spot/account //User's account information

spot/order //User's order information

User Spot Account

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

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

spot/account is channel name ,BTC is token

response parameters
Parameters Parameters type Description
currency String token
balance String balance
hold String amount on hold(not available)
available String available amount for trading or transfer
id String account id
response examples
{
    "table":"spot/account",
    "data":[
        {
            "balance":"244.39253519655",
            "available":"244.39253519655",
            "currency":"USDT",
            "id":"9150707",
            "hold":"0"
        }
    ]
}

User Orders

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

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

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

response parameters
Parameters Parameters type Description
order_id String order ID
client_oid String the order ID customised by yourself
price String price
size String size of order
notional String size of order
instrument_id String trading pair
side String buy or sell
type String limit,market(defaulted as limit)
timestamp String order creation date
filled_size String size filled
filled_notional String amount filled
margin_trading String 1 spot order.
order_type String 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel
last_fill_px String Last transaction price (if none, push 0))
last_fill_qty String Last transaction amount (if none, push 0)
last_fill_time String Last transaction time (if none, push 0)
state String Order 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".

response examples
{
    "table":"spot/order",
    "data":[
        {
            "client_oid":"oktspot5",
            "filled_notional":"0",
            "filled_size":"0",
            "instrument_id":"BTC-USDT",
            "last_fill_px":"0",
            "last_fill_qty":"0",
            "last_fill_time":"1970-01-01T00:00:00.000Z",
            "margin_trading":"2",
            "notional":"",
            "order_id":"2666285202473984",
            "order_type":"3",
            "price":"4535.8",
            "side":"buy",
            "size":"0.001",
            "status":"cancelled",
            "timestamp":"2019-04-16T13:11:23.000Z",
            "type":"limit"
        }
    ]
}

Public-Ticker

To capture the latest traded price, best-bid price, best-ask price, and 24-hour trading volume of all perpetual swap contracts on the platform.

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

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

response parameters
Parameters Parameters type Description
instrument_id String trading pair
last String last traded price
best_bid String best bid price
best_ask String best ask price
open_24h String 24 hour open
high_24h String 24 hour high
low_24h String 24 hour high
base_volume_24h String 24 trading volume of the base currency
quote_volume_24h String 24 trading volume of the quote currency
timestamp String timestamp
response examples
{
    "table":"spot/ticker",
    "data":[
        {
            "instrument_id":"ETH-USDT",
            "last":"162.09",
            "best_bid":"162.1",
            "best_ask":"162.12",
            "open_24h":"165.35",
            "high_24h":"166.55",
            "low_24h":"155.69",
            "base_volume_24h":"620062.9352195",
            "quote_volume_24h":"100084770.34604578",
            "timestamp":"2019-04-16T10:44:06.090Z"
        }
    ]
}

Public-Kline

Kline information for spot business

channel lists:

spot/candle60s // 1mins kline channel

spot/candle180s // 3mins kline channel

spot/candle300s // 5mins kline channel

spot/candle900s // 15mins kline channel

spot/candle1800s // 30mins kline channel

spot/candle3600s // 1hour kline channel

spot/candle7200s // 2hour kline channel

spot/candle14400s // 4hour kline channel

spot/candle21600 // 6hour kline channel

spot/candle43200s // 12hour kline channel

spot/candle86400s // 1day kline channel

spot/candle604800s // 1week kline channel

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

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

response parameters
Parameters Parameters Types Description
timestamp String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
currency_volume String The trading volume in a specific token
instrument_id String trading pair
response examples
{
    "table":"spot/candle60s",
    "data":[
        {
            "candle":[
                "2019-04-16T10:49:00.000Z",
                "162.03",
                "162.04",
                "161.96",
                "161.98",
                "336.452694"
            ],
            "instrument_id":"ETH-USDT"
        }
    ]
}

Public-Trade

Get the filled orders data

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

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

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

{
    "table":"spot/trade",
    "data":[
        {
            "instrument_id":"ETH-USDT",
            "price":"162.12",
            "side":"buy",
            "size":"11.085",
            "timestamp":"2019-04-16T10:58:17.122Z",
            "trade_id":"1210447366"
        },
        {
            "instrument_id":"ETH-USDT",
            "price":"162.12",
            "side":"buy",
            "size":"8.31375",
            "timestamp":"2019-04-16T10:58:17.122Z",
            "trade_id":"1210447371"
        }
    ]
}

Public-Depth5

Back to the previous five entries of depth data

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

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

response parameters
Parameters Parameters Types Description
asks String Selling side
bids String Buying side
timestamp String timestamp
num_orders String total orders in the book
instrument_id String trading pair

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

response examples

{
    "table":"spot/depth5",
    "data":[
        {
            "asks":[
                [
                    "161.96",
                    "7.37567",
                    3
                ],
                [
                    "161.97",
                    "1.308",
                    1
                ],
                [
                    "161.98",
                    "2.463509",
                    1
                ],
                [
                    "161.99",
                    "5.185",
                    2
                ],
                [
                    "162",
                    "29.184592",
                    5
                ]
            ],
            "bids":[
                [
                    "161.94",
                    "4.552355",
                    1
                ],
                [
                    "161.91",
                    "7.949",
                    3
                ],
                [
                    "161.9",
                    "2.213",
                    1
                ],
                [
                    "161.89",
                    "11.999998",
                    1
                ],
                [
                    "161.88",
                    "6.585142",
                    3
                ]
            ],
            "instrument_id":"ETH-USDT",
            "timestamp":"2019-04-16T11:03:03.712Z"
        }
    ]
}

Public-Depth

First time return 200 entries, followed by increment data

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

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

response parameters
Parameters Parameters Types Description
asks String Selling side
bids String Buying side
timestamp String timestamp
num_orders String total orders in the book
instrument_id String trading pair
checksum String checksum

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

response examples
 First 200 entries 


{
    "table":"spot/depth",
    "action":"partial",
    "data":[
        {
            "instrument_id":"ETH-USDT",
            "asks":[
                [
                    "162.5",
                    "14.29884",
                    2
                ],
                [
                    "162.51",
                    "2.084362",
                    1
                ],
               ...

                [
                    "168.51",
                    "7.760755",
                    2
                ],
                [
                    "168.57",
                    "0.02",
                    1
                ]
            ],
            "bids":[
                [
                    "162.49",
                    "1.556106",
                    3
                ],
                [
                    "162.47",
                    "0.00913",
                    1
                ],
               ...

                [
                    "155.15",
                    "70",
                    1
                ],
                [
                    "155.13",
                    "3",
                    1
                ]
            ],
            "timestamp":"2019-04-16T10:17:28.507Z",
            "checksum":1141851215
        }
    ]
}

Increment:

{
    "table":"spot/depth",
    "action":"update",
    "data":[
        {
            "instrument_id":"ETH-USDT",
            "asks":[
                [
                    "162.5",
                    "0",
                    0
                ],
                [
                    "162.51",
                    "0",
                    0
                ],
                [
                    "162.52",
                    "0",
                    0
                ],
                [
                    "162.53",
                    "232.105791",
                    1
                ],
                [
                    "162.59",
                    "8",
                    1
                ],
                [
                    "168.66",
                    "0.0016",
                    1
                ],
                [
                    "168.69",
                    "0.006",
                    1
                ],
                [
                    "168.73",
                    "0.002082",
                    1
                ]
            ],
            "bids":[
                [
                    "162.49",
                    "1.512544",
                    2
                ],
                [
                    "162.47",
                    "0.05333",
                    2
                ],
                [
                    "162.3",
                    "5.353085",
                    5
                ],
                [
                    "162.29",
                    "6.569261",
                    12
                ],
                [
                    "162.25",
                    "8.308575",
                    3
                ]
            ],
            "timestamp":"2019-04-16T10:17:29.045Z",
            "checksum":227291232
        }
    ]
}

WS Public Index

websocket API public index channel

Ticker

This channel is a public index channel that includes the k-lines and tickers for indices.

The indices currently available are all USD-denominated. The asset list includes: BTC, LTC, ETH, ETC, XRP, EOS, BTG.

Get the public index ticker data

send examples
{"op": "subscribe", "args": ["index/ticker:BTC-USD"]}

index/ticker is channel name ,BTC-USD is token index

response parameters
Parameters Parameters Description
instrument_id String e.g. BTC-USD
last String Last traded price
high_24h String 24 hour high
low_24h String 24 hour low
timestamp String timestamp
open_24h String 24 hour open
response examples
{"table":"index/ticker","data":[{"last":"3649.76","high_24h":"3955.4","low_24h":"10","instrument_id":"BTC-USD","open_24h":"3888.68","timestamp":"2018-11-27T10:01:23.341Z"}]}

Kline

Get the kline information

Channel list:

index/candle60s // 1mins kline channel

index/candle180s // 3mins kline channel

index/candle300s // 5mins kline channel

index/candle900s // 15mins kline channel

index/candle1800s // 30mins kline channel

index/candle3600s // 1hour kline channel

index/candle7200s // 2hour kline channel

index/candle14400s // 4hour kline channel

index/candle21600 // 6hour kline channel

index/candle43200s // 12hour kline channel

index/candle86400s // 1day kline channel

index/candle604800s // 1week kline channel

send examples
{"op": "subscribe", "args": ["index/candle60s:BTC-USD"]}

index/candle60s is channel name ,BTC-USD is token index

response parameters
Parameters Parameters Types Description
timestamp String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
currency_volume String The trading volume in a specific token
instrument_id String e.g.BTC-USD
response examples

{"table":"index/candle60s","data":[{"instrument_id":"BTC-USD","candle":["2018-11-27T10:01:23.341Z","3811.31","3811.31","3811.31","3811.31","0"]}]}

error code

error message format:

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

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

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