README


Welcome to use 大圣交易所 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

dasheng’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, dasheng 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.dasheng.com/pages/products/fees.html)

Deposit/Withdrawal Fees

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

Data Centers

The database and servers of dasheng 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.dasheng.world/ 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

dasheng 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 dasheng 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 dasheng; the Passphrase will be provided by you to further secure your API access. dasheng 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.dasheng.open.api.config.APIConfiguration;
import com.okcoin.commons.dasheng.open.api.constant.APIConstants;
import com.okcoin.commons.dasheng.open.api.enums.ContentTypeEnum;
import com.okcoin.commons.dasheng.open.api.enums.HttpHeadersEnum;
import com.okcoin.commons.dasheng.open.api.exception.APIException;
import com.okcoin.commons.dasheng.open.api.utils.DateUtils;
import com.okcoin.commons.dasheng.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.dasheng.open.api.bean.futures.result.*;
import com.okcoin.commons.dasheng.open.api.client.APIClient;
import com.okcoin.commons.dasheng.open.api.config.APIConfiguration;
import com.okcoin.commons.dasheng.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.dasheng.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.dasheng.open.api.bean.futures.result.*;
import com.okcoin.commons.dasheng.open.api.service.futures.FuturesMarketAPIService;
import com.okcoin.commons.dasheng.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 dasheng

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.dasheng.com/
    Endpoint string
    // The user's api key provided by dasheng.
    ApiKey string
    // The user's secret key provided by dasheng. 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 dasheng API's config
    var config Config
    config.Endpoint = "https://www.dasheng.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.dasheng.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.dasheng.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.dasheng.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.dasheng.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.dasheng.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 is used to transfer funds among the main account, sub accounts and various trading accounts, as well as getting deposit addresses and making withdrawals.

Get Currencies

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

Limit: 20 requests per 2 seconds

HTTP Request

GET /api/account/v3/currencies

Request Sample

GET /api/account/v3/currencies

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

Wallet Information

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

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/wallet

Example Request

GET /api/account/v3/wallet

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

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

Wallet of a Currency

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

Limit: 20 requests per 2 seconds
HTTP Request

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

Request Sample

GET /api/account/v3/wallet/XMR

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

Funds Transfer

This endpoint supports the transfer of funds 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

This endpoint supports the withdrawal of tokens

Limit: 20 requests per 2 seconds
HTTP Request

`POST /api/account/v3/withdrawal

Example Request

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

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

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

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

Withdrawal Fees

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

HTTP Requests

GET /api/account/v3/withdrawal/fee

Example Request

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

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

Recent Withdrawal History

This retrieves up to 100 recent withdrawal records.

Limit: 20 requests per 2 seconds

HTTP Request

GET /api/account/v3/withdrawal/history

Example Request

GET /api/account/v3/withdrawal/history

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

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

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

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

Example Response

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

Recent Withdrawal History of a Currency

This retrieves the withdrawal records of a specific currency.

Limit: 20 requests per 2 seconds

HTTP Request

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

Example Request

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

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

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

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

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

Example Response
[
    {
        "amount":"0.01105486",
        "withdrawal_id": "4703879",
        "fee":"0.00000000btc",
        "txid": "66602e279569ba319a929f5bda731d228962bc67cd89dfa0d432d82722681d66",
        "currency": "BTC",
        "from":"13426335357",
        "to":"13426335357",
        "timestamp":"2018-09-30T02:49:29.000Z",
        "status":"2"
    },
    {
        "amount":"0.01144408",
        "withdrawal_id": "4703859",
        "fee":"0.00000000btc",
        "txid": "66602e279569ba319a929f5bda731d228962456475467d89dfa0d432d82722681d66",
        "currency": "BTC",
        "from":"13426335357",
        "to":"13426335357",
        "timestamp":"2018-09-18T00:44:56.000Z",
        "status":"2"
    }
]

Bills Details

This endpoint retrieves the bill details of the Funding Account. All the information will be paged and sorted in reverse chronological order, which means the latest will be at the top. Please refer to the pagination section for additional records after the first page. 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 retrieves the deposit addresses of currencies, including previously used addresses.

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/deposit/address

Example Request

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

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

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

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

Example Response

[
    {
        "address": "okbtothemoon",
        "memo": "971668",
        "currency": "eos",
        "to": 6
    }
]

Get Deposit History of All Currencies

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

Limit: 20 requests per 2 seconds
HTTP Request

GET /api/account/v3/deposit/history

Example Request

GET /api/account/v3/deposit/history

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

Get Deposit History of a Currency

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

Limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

Parameters
Parameters Parameters Types Required Description
currency String Yes Token Symbol
Response
Parameters Parameters Types Description
amount String Deposit amount
from String Only internal OKEx account is returned,not the address on the blockchain
to String Deposit address
txid String Hash record of the deposit
timestamp String Time that the deposit is credited
currency String Token Symbol
state String Status of deposit (0: waiting for confirmation; 1: deposit credited; 2: deposit successful)
withdraw_id String Withdrawal ID
Example Response
[
    {
        "amount":"0.0835",
        "txid":"6d892c669225b1092c780bf0da0c6f912fc3e8f997dc8f6b8cc53b003288624c",
        "currency":"BTC",
        "from":"13800138000"
        "to":"39kK4XvgEuM7rX9frgyHoZkWqx4iKu1spD",
        "timestamp":"2018-06-09T07:57:09.000Z",
        "status":"2"
    },
    {
        "amount":"0.01",
        "txid":"590426_1_0_WALLET",
        "currency":"BTC",
        "from":""
        "to":"",
        "timestamp":"2018-05-30T01:33:40.000Z",
        "status":"2"
    }
]

Token Trading API

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

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

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

Spot Trading Account

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

Rate limit: 20 requests per 2 seconds
HTTP Requests

GET /api/spot/v3/accounts

Example Request

GET /api/spot/v3/accounts

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

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

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

Spot Trading Account of a Currency

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

Limit: 20 requests per 2 seconds
HTTP Request

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

Request Sample

GET /api/spot/v3/accounts/btc

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

{
    "frozen":"0",
    "hold":"0",
    "id":"",
    "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

GET /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 spot trading supports only limit and market orders. More order types will become available in the future. You can place an order only if you have enough funds.

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

Rate limit: 100 requests per 2 seconds
HTTP Request

POST /api/spot/v3/orders

Example Authenticated Request

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

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

client_oid

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

instrument_id

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

type

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

price

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

size

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

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

notional

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

hold

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

Order life cycle

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

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

Response

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

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

Cancel an Order

This is used to cancel an unfilled order.

Rate limit: 100 requests per 2 seconds
HTTP Request

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

Example Request with Authentication

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

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

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

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

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

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

Cancel All Orders

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

Rate limit: 20 requests per 2 seconds
HTTP Requests

POST /api/spot/v3/cancel_batch_orders

Example Request with Authentication

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

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

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

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

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

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

Get Order List

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/orders

Example Authenticated Request

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

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

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

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

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

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

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

]

Get All Open Orders

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/orders_pending

Example Authenticated Request

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

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

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

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

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

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

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

Get Order Details

Retrieve order details by order ID.Can get order information for nearly 3 months。 Unfilled orders will be kept in record for only two hours after it is canceled.

Rate limit: 20 requests per 2 seconds
HTTP Request

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

or

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

Example Authenticated Request

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

or

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

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

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

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

Unfilled order status may change according to the market conditions.

Example Response
{
    "client_oid":"oktspot70",
    "created_at":"2019-03-15T02:52:56.000Z",
    "filled_notional":"3.8886",
    "filled_size":"0.001",
    "funds":"",
    "instrument_id":"BTC-USDT",
    "notional":"",
    "order_id":"2482659399697408",
    "order_type":"0",
    "price":"3927.3",
    "price_avg":"3927.3",
    "product_id":"BTC-USDT",
    "side":"buy",
    "size":"0.001",
    "status":"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

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

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

Rate limit: 20 Requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments

Example Request

GET /api/spot/v3/instruments

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

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

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

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

Get Order Book

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

Parameters
Parameter Type Required Description
size String No Number of results per request. Maximum 200
depth String No Aggregation of the order book. e.g . 0.1, 0.001
instrument_id String No Trading pair symbol
Response
Parameter Type Description
asks List<String> Selling side
bids List<String> Buying side
timestamp String timestamp
Notes

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

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

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

Get All Token Pairs Information

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

Rate limit: 20 requests per 2 seconds
HTTP Request

GET /api/spot/v3/instruments/ticker

Example Request

GET /api/spot/v3/instruments/ticker

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

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

The open_24 is the opening price exactly 24 hours ago.

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

Get a Token Pair Information

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

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

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

The open_24 is the opening price exactly 24 hours ago.

Example Response
{
    "best_ask": "8120.6",
    "best_bid": "8120",
    "instrument_id": "BTC-USDT",
    "product_id": "BTC-USDT",
    "last": "8120",
    "ask": "8120.6",
    "bid": "8120",
    "open_24h": "8232.6",
    "high_24h": "8395.9",
    "low_24h": "8068.2",
    "base_volume_24h": "13508.4",
    "timestamp": "2019-10-03T15:49:38.506Z",
    "quote_volume_24h": "111036129.6"
}

Get Filled Orders Information

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

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

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

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

Get Market Data

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pairs symbol
start String No Start time in ISO 8601
end String No End time in ISO 8601
granularity String No Bar size in seconds, default 60, must be one of [60/180/300/900/1800/3600/7200/14400/21600/43200/86400/604800] or returns error
Response
Parameter Type Description
time String Start time
open String Open price
high String Highest price
low String Lowest price
close String Close price
volume String Trading volume
Notes

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

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

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

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

Example Response

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

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 are optimized by Deflate compression. Users are expected to decompress the messages by their own means. 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

Request format:

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

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

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

Successful response format:

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

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


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

Failure response format:

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

Subscription

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

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

Note: the value of <op> is subscribe

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

The <channelname> is composed of business/channel

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

Example:

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

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

Example :

send:

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

response:

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

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

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

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

Unsubscription

Users can cancel one or more channels.

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

send:

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

response:

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

Login

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

Login subscription format:

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

Response:

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

Example:

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

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

passphrase:The passphrase entered when creating the API key

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

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

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

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

methodis preset as'GET'。

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

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

Connect limit

Connection limit:once per second

Subscription limit:240 times per hour

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

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

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

Checksum

This function helps users verify the accuracy of depth data.

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

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

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

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


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

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

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

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

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

The pushed data of depth channel that user receives are:

First 200 entries


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

Increment:

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

Channel List

Channels that don't require login

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

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

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

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

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

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

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

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

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

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

Public-Kline

Retrieve the candlestick data

channel lists:

spot/candle60s // 1mins candlestick

spot/candle180s // 3mins candlestick

spot/candle300s // 5mins candlestick

spot/candle900s // 15mins candlestick

spot/candle1800s // 30mins candlestick

spot/candle3600s // 1hour candlestick

spot/candle7200s // 2hour candlestick

spot/candle14400s // 4hour candlestick

spot/candle21600s // 6hour candlestick

spot/candle43200s // 12hour candlestick

spot/candle86400s // 1day candlestick

spot/candle604800s // 1week candlestick

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

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

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

Public-Trade

Get the filled orders data

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

spot/trade is the channel nameETH-USDT is instrument_id

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

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

Public-Depth5

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

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

spot/depth5 is channel nameETH-USDT is instrument_id

response parameters
Parameter Type Description
asks List<String> Selling side
bids List<String> Buying side
timestamp String timestamp
instrument_id String trading pair

bids and asks value example: In ["411.8","10","8"], 411.8 is price depth, 10 is the amount at the price, 8 is the number of orders at the price.

response examples

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

Public-Depth

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

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

spot/depth is channel nameETH-USDT is trading pair

Response
Parameter Types Description
asks List<String> Selling side
bids List<String> Buying side
timestamp String timestamp
instrument_id String trading pair
checksum String Checksum

bids and asks value example: In ["411.8","10","8"], 411.8 is price depth, 10 is the amount at the price, 8 is the number of orders at the price.

Example Response
 First 200 entries 


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

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

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

Increment:

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

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