README


Welcome to use CRYPTEX GLOBAL 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

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

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

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

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

Order Life Cycle

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

Token Trading Price Limit Rules

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

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

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

Futures Trading Price Limit Rules

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

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

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

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

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

Fees

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

  • Trading Fees
  • Deposit/Withdrawal Fees

Trading Fees

To encourage more order placement and liquidity, cryptexglobal 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.cryptexglobal.com/pages/products/fees.html)

Deposit/Withdrawal Fees

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

Data Centers

The database and servers of cryptexglobal 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.cryptexglobal.com/api We also provide WebSocket-stream. Subscribe to our WebSocket and you can get our market data push.

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

Errors

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

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

Success

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

Pagination

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

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

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.cryptexglobal.com/
    Endpoint string
    // The user's api key provided by cryptexglobal.
    ApiKey string
    // The user's secret key provided by cryptexglobal. 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 cryptexglobal API's config
    var config Config
    config.Endpoint = "https://www.cryptexglobal.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.cryptexglobal.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.cryptexglobal.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.cryptexglobal.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.cryptexglobal.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.cryptexglobal.com'
request_path = '/api/spot/v3/orders'

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

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

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

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

Timestamp

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

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

Getting Server Time

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

HTTP Requests

GET /api/general/v3/time

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

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

"epoch": 1420674445.201

}

Wallet API

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

Get Currencies

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

HTTP Requests

GET /api/account/v3/currencies

Request Sample

GET /api/account/v3/currencies

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

Wallet Information

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

HTTP Requests

GET /api/account/v3/wallet

Request Sample

GET /api/account/v3/wallet

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

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

Wallet of a Currency

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

HTTP Requests

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

Request Sample

GET /api/account/v3/wallet/btc

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

Funds Transfer

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

Limit: 3 times / s
HTTP Requests

POST /api/account/v3/transfer

Request Sample

POST /api/account/v3/transfer

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

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

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

OK06ETT can only be transferred between ETT and spot accounts

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

Withdrawal

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

HTTP Requests

POST /api/account/v3/withdrawal

Request Sample

POST /api/account/v3/withdrawal

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

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

Withdrawal Fees

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

HTTP Requests

GET /api/account/v3/withdrawal/fee

Request Sample

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

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

Recent Withdrawal History

This endpoint retrieves all recent withdrawal records.

HTTP Requests

GET /api/account/v3/withdrawal/history

Request Sample

GET /api/account/v3/withdrawal/history

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

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

Return Sample

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

Recent Withdrawal History of a Currency

This endpoint retrieves the withdrawal history of a specific token.

HTTP Request

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

Request Sample

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

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

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

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

Bills Details

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

HTTP Requests

GET /api/account/v3/ledger

Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
currency String No token ,information of all tokens will be returned if the field is left blank
type number No 1:deposit 2:withdrawal 13:cancel withdrawal 18: into futures account 19: out of futures account 20:into sub account 21:out of sub account 28: claim 29: into ETT account 30: out of ETT account 31: into C2C account 32:out of C2C account 33: into margin account 34: out of margin account 37: into spot account 38: out of spot account
from number No you would request pages after this page.
to number No you would request pages before this page
limit number No Number of results per request. Maximum 100. (default 100)
Return Parameters
Parameters Parameters Types Description
ledger_id number bill ID
currency String token
balance number remaining balance
amount number quantity
typename String type of bills
fee number service fees
timestamp String creation time
Return Sample
{
        "amount":0.00100941,
        "balance":0,
        "currency":"BTC",
        "fee":0,
        "ledger_id":9260348,
        "timestamp":"2018-10-19T01:12:21.000Z",
        "typename":"To: spot account"
    },
    {
        "amount":0.00051843,
        "balance":0.00100941,
        "currency":"BTC",
        "fee":0,
        "ledger_id":8987285,
        "timestamp":"2018-10-12T11:01:14.000Z",
        "typename":"Get from activity"
    }

Get Deposit Address

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

HTTP Requests

GET /api/account/v3/deposit/address

Request Sample

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

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

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

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

Return Sample

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

Get Deposit History of All Currencies

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

HTTP Requests

GET /api/account/v3/deposit/history

Request Sample

GET /api/account/v3/deposit/history

Return Parameters
Parameters Parameters Types Description
currency String token
amount number deposit amount
to String deposit address
txid String TXID
timestamp String deposit arrival date
status number The status of withdrawals (0: waiting for confirmation; 1: confirmation account; 2: recharge success);
Return Sample
{
        "amount":0.01044408,
        "txid":"1915737_3_0_0_WALLET",
        "currency":"BTC",
        "to":"",
        "timestamp":"2018-09-30T02:45:50.000Z",
        "status":2
    },
    {
        "amount":491.6784211,
        "txid":"1744594_3_184_0_WALLET",
        "currency":"OKB",
        "to":"",
        "timestamp":"2018-08-21T08:03:10.000Z",
        "status":2
    },
    {
        "amount":223.18782496,
        "txid":"6d892c669225b1092c780bf0da0c6f912fc7dc8f6b8cc53b003288624c",
        "currency":"USDT",
        "to":"39kK4XvgEuM7rX9frgyHoZkWqx4iKu1spD",
        "timestamp":"2018-08-17T09:18:40.000Z",
        "status":2
    }

Get Deposit History of a Currency

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

HTTP Requests

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

Request Sample

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

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

Token Trading API

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

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

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

Spot Trading Account

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

Rate limit: 20 /2s
HTTP Requests

GET /api/spot/v3/accounts

End Certificate Request Sample

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

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

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

Return Sample
[{
   "currency": "BTC”,
   "balance”: ”2.3”,    
    "hold”: "2”,
    "available": "0.3”,
    "id”:”344555”
}]

Spot Trading Account of a Currency

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

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

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

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

 "currency": "BTC”,

 "balance”: ”2.3”, 

 "hold”: "2”,

 "available": "0.3”,

 "id”:”344555”

}

Bills Details

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

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

2018-09-12T07:46:19.435ZGET/api/spot/v3/accounts/btc/ledger?limit=1&from=2&to=4

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

The following is the enumeration value for the parameters types

Type value Description
transfer funds transfer
trade funds moved as a result of a trade
fee fee as a result of a trade
rebate fee rebate as per our fee schedule
Return Sample
[
{
      "amount":"0.999",
       "currency":"USDT",
      "balance":"6.539194",
      "timestamp":"2018-06-20T02:31:00.000Z",
      "details":
     {"order_id”:7542,"instrument_id":"LTC-BTC"},
      "ledger_id": "912025447”,
      "type”:”"trade
},
{
      "amount":"1",
      "currency":"USDT",
      "balance":"31.797831",
      "timestamp":"2018-06-20T02:31:00.000Z",
      "details":
     {"order_id”:7542,"instrument_id":"LTC-BTC"},
      "ledger_id”:"912025427”,
      "type”:”trade"
},
…
]

Place an Order

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

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

Rate limit: 100/2s
HTTP Requests

POST /api/spot/v3/orders

End Certificate Request Sample

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

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

Request Parameters
Parameters Parameters Types Required Description
client_oid string No the order ID customized by yourself
type string Yes limit / market(default: limit)
side string Yes buy or sell
instrument_id string Yes trading pair
margin_trading byte Yes order type (The request value is 1)
Limit Order Parameters
Parameters Parameters Types Required Description
price string Yes price
size string Yes quantity bought or sold
Market Order Parameters
Parameters Parameters Types Required Description
size string Yes quantity sold. (for orders sold at market price only)
notional string Yes amount bought. (for orders bought at market price only)
Return Parameters
Parameters Parameters Types Description
order_id string order ID
client_oid string the order ID customised by yourself
result boolean result of the order. Error message will be returned if the order failed.
Explanation

instrument_id

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

client_oid

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

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

type

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

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

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

price

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

size

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

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

notional

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

hold

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

Order Lifecycle

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

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

Response

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

Return Sample
{
    "order_id": "234652",
    "client_oid": "23",
    "result": true
}

Cancel an Order

Cancelling an unfilled order.

Rate limit: 100/2s
HTTP Requests

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

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
instrument_id string Yes By providing this parameter, the corresponding order of a designated trading pair will be cancelled. If not providing this parameter, it will be back to error code.
client_oid string No the order ID created by yourself
order_id string Yes order ID
Return Parameters
Parameters Parameters Types Description
order_id string order ID
client_oid string the order ID created by yourself
result boolean order cancellation result. Error code will be returned if it failed
Explanation

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

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

Return Sample
{
"client_oid":"",
"order_id":1745,
"result":true
}

Cancel All Orders

With best effort, this endpoints supports cancelling all open orders for a specific trading pair or several trading pairs.

Rate limit: 20/2s
HTTP Requests

POST /api/spot/v3/cancel_batch_orders

End Certificate Request Sample

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

Request Parameters
Parameters Parameters Types Required Description
order_ids list<long> Yes order ID. You may cancel up to 4 orders of a trading pair
instrument_id string Yes by providing this parameter, the corresponding order of a designated trading pair will be cancelled. If not providing this parameter, it will be back to error code.
Return Parameters
Parameters Parameters Types Description
order_id list<string> order ID
client_oid string the order ID created by yourself
result boolean order cancellation result. Error code will be returned if it failed
Explanation

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

Return Sample
{
"btc_usdt”:{
"result":true,
"client_oid":"",
"order_id":["1747","1748"]
},
"ltc_eth”:{
"result":true,
"client_oid":"",
"order_id”:["1758”,”1779","1880"]
}
}

Get Order List

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

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/orders

End Certificate Request Sample

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

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

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

Return Parameters
Parameters Parameters Types Description
order_id string order ID
price string price
size string quantity
notional string the total buying amount. This value will be returned for market orders
instrument_id string trading pair
type string limit,market(defaulted as limit)
side string buy or sell
timestamp string trading pair
filled_size string quantity filled
filled_notional string amount filled
status string order status
Explanation

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

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

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

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

Get All Open Orders

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

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/orders_pending

End Certificate Request Sample

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

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

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

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

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

Get Order Details

Get order details by order ID.

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

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

Requests Parameters
Parameters Parameters Types Description
instrument_id string [required]trading pair
order_id string [required] order ID
Return Parameters
Parameters Parameters Types Description
order_id string description ID
price string price
size string size of order
notional string buying amount (for market orders)
instrument_id string trading pair
side string buy or sell
type string limit,market(defaulted as limit)
timestamp string order creation date
filled_size string size filled
filled_notional string amount filled
status string order status(all, open, part_filled, canceling, filled, cancelled,ordering,failure )
Explanation

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

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

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

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

Get Transaction Details

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

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/fills

End Certificate Request Sample

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

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

Fees

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

Liquidity

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

Pagination

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

Return Sample
[{

    "exec_type": "T",
    "fee": "0.018",
    "instrument_id": "ETH-USDT",
    "ledger_id": "1706",
    "order_id": "1798782957193216",
    "price": "90",
    "side": "points_fee",
    "size": "0",
    "timestamp": "2018-11-14T08:14:09.000Z"
}, {

    "exec_type": "T",
    "fee": "10",
    "instrument_id": "ETH-USDT",
    "ledger_id": "1705",
    "order_id": "1798782957193216",
    "price": "90",
    "side": "buy",
    "size": "0.1",
    "timestamp": "2018-11-14T08:14:09.000Z"
}, {

    "exec_type": "T",
    "fee": "10",
    "instrument_id": "ETH-USDT",
    "ledger_id": "1704",
    "order_id": "1798782957193216",
    "price": "90",
    "side": "sell",
    "size": "9",
    "timestamp": "2018-11-14T08:14:09.000Z"
}]

Get Token Pair Details

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

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

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/instruments

End Certificate Request Sample

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

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

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

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

Return Sample
[{
"instrument_id": "BTC-USDT",

"base_currency": "BTC",

"quote_currency": "USDT",

"min_size": "0.001",

"size_increment": "0.00000001",

"tick_size": "0.0001"
}]

Get Order Book

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

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

2018-09-12T07:57:09.130ZGET/api/spot/v3/instruments/LTC-USDT/book?size=10&depth=0.001

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

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

Return Sample
{
    "timestamp": "2016-12-08T20:09:05.508883Z",

    "bids": [
        [ price, size, num_orders ],
        [ "295.96", "4.39088265", 2 ],
        ...
    ],
    "asks": [
        [ price, size, num_orders ],
        [ "295.97", "25.23542881", 12 ],
        ...
    ]
}

Get All Token Pairs Information

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

Rate limit: 20/2s
HTTP Requests

GET /api/spot/v3/instruments/ticker

End Certificate Request Sample

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

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

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

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

Return Sample
[{

"instrument_id": "BTC-USDT",
"last": "333.99",
"best_bid": "333.98",
"best_ask": "333.99",
"open_24h": "0.193",
"high_24h": "0.193",
"low_24h": "333.98",
"base_volume_24h": "5957.11914015",
"quote_volume_24h": "5957.11914015",
"timestamp": "2015-11-14T20:46:03.511Z"

},{

"instrument_id": "LTC-USDT",
"last": "333.99",
"best_bid": "333.98",
"best_ask": "333.99",
"open_24h": "0.193",
"high_24h": "0.193",
"low_24h": "333.98",
"base_volume_24h": "5957.11914015",
"quote_volume_24h": "5957.11914015",
" timestamp": "2015-11-14T20:46:03.511Z"
}]

Get a Token Pair Information

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

Rate limit: 20 / 2s
HTTP Requests

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

End Certificate Request Sample

2018-09-12T07:57:50.799ZGET/api/spot/v3/instruments/LTC-USDT/ticker

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

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

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

Return Sample
{
"instrument_id": "BTC-USDT",
"last": "333.99",
"best_bid": "333.98",
"best_ask": "333.99",
"high_24h": "0.193",
"open_24h": "0.193",
"low_24h": "333.98",
"base_volume_24h": "5957.11914015",
"quote_volume_24h": "5957.11914015",
"timestamp": "2015-11-14T20:46:03.511Z"
}

Get Filled Orders Information

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

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

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

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

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

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

Return Sample
[{

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

"trade_id": "3245601",

"price": "10.00000000",

"size": "0.01000000",

"side": "buy"

}, {

"timestamp": "2014-11-07T01:08:43.642Z",

"trade_id": "3245602",

"price": "100.00000000",

"size": "0.01000000",

"side": "sell"

}]

Get Market Data

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

Rate limit: 20/2s
HTTP Requests

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

End Certificate Request Sample

2018-09-12T07:59:45.977ZGET/api/spot/v3/instruments/btc-usdt/candles?granularity=60&start=2018-09-11T08%3A28%3A48.899Z&end=2018-09-11T09%3A28%3A48.899Z

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

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

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

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

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

Return Sample

[["2018-12-09T08:40:00.000Z", "3345", "3345", "3332.1", "3344.9", "7531"],["2018-12-09T08:40:00.000Z", "3345", "3345", "3332.1", "3344.9", "7531"]]

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