INTRODUCTION


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

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

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

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

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

  • historical price of trading pairs

After registering an account on OKCoinJapan, you can create APIKeys with different permissions to allow you to separate privileges for your APIKeys where one APIKey can trade while another can withdraw.

Getting Access

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

Endpoints Configurations

OKCoinJapan offers both REST and WebSocket APIs. Either can be used for viewing market data,trading, or withdrawals.

Refer to SDK for more information

Rest API

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

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

Support of HTTP/2


HTTP/2 is the latest version of the HTTP protocol, which is upgraded from HTTP/1.1 based on multiplexing. The updates involved are as follows:

  1. Our website and API will support both HTTP/1.1 and HTTP/2.
  2. HTTP/2 will be automatically enabled on compatible clients by default.
  3. Compatibility for browsers or program libraries of older versions will be maintained by supporting HTTP/1.1.
WebSocket API

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

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

Change Log

2024-04-09

Updated on: April, 2024

  • Now support Stop Order in below API:
    • Spot Trading API - Place Algo Order
    • Spot Trading API - Cancel Algo Order
    • Spot Trading API - Get Algo Order List
    • WebSocket API - User Algo Orders



2024-04-01

Updated on: April, 2024

  • The following API Logic Optimization:
    • Funding Account API - Fiat Withdrawal
      • This endpoint supports the withdrawal of Japanese Yen. By default, funds will be withdrawn to the bank card used in the last withdrawal. If this card is unavailable, the withdrawal will be redirected to the most recently added or modified bank card.

2024-02-15

Updated on: February, 2024

  • The following API add history order status:
    • Funding Account API - Fiat Withdrawal History
      • withdrawal status
        5:Cancellation in Progress

2023-11-22

Updated on: November, 2023

  • The following API updates history order status:
    • Funding Account API - Fiat Withdrawal History
      • Before: withdrawal status
        3:success
        0:processing
        -1:failed
        -2:disabled
        -3:cancelled
        -5:refunded
      • After: withdrawal status
        1:Waiting for processing
        2:Withdrawal in Progress
        4:Success
        6:Cancelled
        7:Unsuccessful
        8:TFS refund
        9:Disabled
    • Funding Account API - Fiat Deposit History
      • Before: deposit status
        3:success
        0:processing
        -3:refunded
      • After: deposit status
        1:Awaiting processing
        2:Processing
        4:Success
        8:Refund processed
    • Funding Account API - Withdrawal History & Withdrawal History of a Currency
      • Before: Status of withdrawal.
        -6:Confirmation Failed;
        -5:Confirmation Failed;
        -4:Refunded;
        -3:Cancellation in Progress;
        -2:Cancelled;
        -1:Withdrawal Failed;
        0:Awaiting withdrawal;
        1:Withdrawal in Progress;
        2:Withdrawal Completed;
        3:Awaiting Email Confirmation;
        4:Awaiting CS Confirmation;
        7:Awaiting CS Confirmation;
        10:Awaiting CS Confirmation;
        11:Awaiting CS Confirmation;
        12:Awaiting CS Confirmation;
      • After: Status of withdrawal.
        1:Awaiting withdrawal
        2:Withdrawal in Progress
        3:CS Reviewing
        4:Withdrawal Completed
        5:Cancellation in Progress
        6:Cancelled
        7:Withdrawal Failed
        8:Have a refund
    • Funding Account API - Deposit History & Deposit History of a Currency
      • Before: Status of deposit
        0:Waiting confirmation
        1:Deposit confirmation
        2:Success
      • After: Status of deposit
        1:Waiting confirmation
        2:Deposit confirmation
        3:CS Reviewing
        4:Success
        7:Deposit Failed



2022-05-12

Updated on: May, 2022

  • Now support multiple chain in below API:
    • Funding Account API - Get Currencies
    • Funding Account API - Withdrawal
    • Funding Account API - Withdrawal History
    • Funding Account API - Withdrawal History of a Currency
    • Funding Account API - Deposit Address
    • Funding Account API - Deposit History
    • Funding Account API - Deposit History of a Currency
    • Funding Account API - Withdrawal Fees



2021-07-28

Updated on: July, 2021

  • Now support Internal Token Transfer via below API:
    • Funding Account API - Withdrawal



2020-10-14

Updated on: October, 2020

  • Added the following interface:

    • Funding Account API - Withdrawal
    • Funding Account API - Fiat Withdrawal
    • Funding Account API - Fiat Withdrawal History
    • Funding Account API - Fiat Deposit History
  • Added Advanced Limit Order Type(Post Only, Fill Or Kill, Immediate Or Cancel) to below spot order API:

    • Spot Trading API - Place Order
    • Spot Trading API - Batch Orders



API Summary

Market overview and general information.

Trade

1)Currency

Currency refers to the basic unit that can be transferred in and out, such as BTC, ETH, BCH, etc.

2)Trading pairs

A trading pair is composed of the trading currency and the pricing currency. Taking BTC / JPY as an example, BTC is the trading currency, and JPY is the pricing currency. Trading pairs are mainly used in the spot trading market.

1)order_id

Order ID: the order ID for the same trading pair of each business line is unique.

2)client_oid

The customer-defined ID is a non-required parameter when placing an order. The format is letters (case-sensitive) + numbers or letters (case-sensitive), 1-32 characters. It is recommended that user-defined client_oid not be repeated, or the latest order_id will be returned when querying if there are multiple order_ids correspond to the same client_oid.

3)trade_id

The unique ID of a transaction.

4)ledger_id

The unique ID of the bill

Order types

1)limit

The limit order defines the highest price the user is willing to buy or the lowest price that the user is willing to sell. After the user sets the price limit, the order will be filled at a price that is favorable to the user.

2)market

Market orders only needed to be set the order amount or order quantity, and the price is not needed setting. When the order is being matched, the order will be directly filled with the counterparty until the amount or quantity is lower than the minimum transaction amount or quantity. Market order is also restricted by the price limit mechanism.

Order status

1) Failed:

Due to insufficient balance and other reasons, orders in this status cannot be verified and sent into the matching queue;

2) Pending order:

the order in the status has been in the matching queue;

3) Partially filled:

the order in the status is in the matching queue. Part of the order has been filled, and the rest is waiting for being filled;

4) Fully filled:

the order in the status has been fully filled with the counterparty in the matching queue;

5) Order placing:

the order is in the status of being placed. As the order needs to be placed in the matching queue before being successfully placed, this status is a transitional;

6) Under cancellation:

the order is in the status of being canceled. As the order needs to be removed from the matching queue before it is truly canceled, this status is a transitional.

Matching Engine

This section explains the matching engine based on the following:

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

Filled Price

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

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

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

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

Order Life Cycle

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

Token Trading Price Limit Rules

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

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

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

Fees

This sections explains the fee details for the following:

  • Trading Fees
  • Deposit/Withdrawal Fees

Trading Fees

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

Please see here for details

Deposit/Withdrawal Fees

OKCoinJapan does not charge any withdrawal or deposit fees. However, mining fees will be levied by miners for any withdrawals out of OKCoinJapan.

Server Location

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

Requests

This section explains the requests details based on the following:

  • Introduction
  • Errors
  • Success

Introduction

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

Rest API URL https://www.okcoin.jp/

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

WebSocket API URL wss://connect.okcoin.jp:443/ws/v3

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

Errors

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

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

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

Success

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

Pagination

1、Pagination

OKCoinJapan uses cursor pagination for REST requests that return arrays. The cursor pagination allows for fetching results before and after the current page and is suitable for real-time data. The endpoints like /trades, /fills, /orders, return the latest 100 records by default. To retrieve more results, subsequent requests should specify the direction to paginate result relative to the data previously returned.

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

Example: GET/api/spot/v3/orders?before=2&limit=30

Parameters
Parameter Type Required Description
after String Yes Pagination of data to return records earlier than the requested order_id, ledger_id, or trade_id.
before String Yes Pagination of data to return records newer than the requested order_id, ledger_id, or trade_id.
limit String Yes Number of results per request. The maximum is 100; the default is 100

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

The response will contain an OK-BEFORE header which will return the cursor ID, which can be used in your next request for the page before the current one. The page before is a newer page and not one that happened before chronologically. The response will also contain an OK-AFTER header which will return the cursor ID, which can be used 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 chronologically.

For example,

  1. GET/api/spot/v3/orders/BTC-JPY?state=2 (The latest 100 transactions)

  2. GET/api/spot/v3/orders/BTC-JPY?state=2&limit=20 (The latest 20 transactions )

  3. GET/api/sopt/v3/orders/BTC-JPY?state=2&after=251266960551&limit=20 (The 20 transaction data filled earlier than the contract ‘order_id=251266960551’ will be returned, without the order 25126696055)

  4. GET/api/spot/v3/orders/BTC-JPY?state=2&before=2512669605532&limit=20 (The 20 transaction data filled later than the contract ‘order_id=2512669605532’ will be returned, with the order 2512669605532 not included)

Rules

This section explains the standard specifications for the following:

  • Timestamps
  • Numbers
  • IDs

Timestamps

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

Example

2014-11-06T10:34:47.123Z

Numbers

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

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

IDs

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

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

Endpoints

This section explains the endpoint details:

  • Public Endpoints
  • Private Endpoints

Public Endpoints

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

Private Endpoints

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

Rate Limits

This section explains the rate limit details for the following:

  • Rest API

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

Rest API

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

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

Authentication

This section explains the authentication details:

  • Generating an APIKey
  • Making Requests
  • Signing Messages
  • Timestamps
  • Getting Server Time

Generating an APIKey

Before being able to sign any requests, you must create an APIKey on OKCoinJapan. Upon creating a key you will have 3 pieces of information which you must remember:

APIKey

SecretKey

Passphrase

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

Making Requests

All private REST requests must contain the following headers:

OK-ACCESS-KEY The APIKey as a String.

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

OK-ACCESS-TIMESTAMP The timestamp of your request.

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

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

Signing Messages

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

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

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

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

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

The requestPath is the path of requesting an endpoint.

Example: /api/spot/v3/orders?instrument_id=BTC-JPY&state=2

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

Example: {"product_id":"BTC-JPY","order_id":"377454671037440"}

The Secret is generated when you create an APIKey.

Example: 22582BD0CFF14C41EDBF1AB98506286D

public enum ContentTypeEnum {

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


    private String contentType;

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

    public String contentType() {
        return contentType;
    }
}


public enum HttpHeadersEnum {

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

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

    private String header;

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

    public String header() {
        return header;
    }
}

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

public class APIHttpClient {

    private APIConfiguration config;
    private APICredentials credentials;

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

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

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

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

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

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

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

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

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

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



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

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

public class APIClient {

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

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


# Example Request 
# set the request url
base_url = 'https://www.okcoin.jp'
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())


########################################################
# take order
base_url = 'https://www.okcoin.jp'
request_path = '/api/spot/v3/orders'

# request params
params = {'type': 'market', 'side': 'buy', 'instrument_id': 'BTC-JPY', 'size': '0.01', 'client_oid': '', 'price': '4500000'}

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

# request header and body
header = get_header('your_api_key', signature('timestamp', 'POST', request_path, 'your_secret_key'), 'timestamp', 'your_passphrase')
body = json.dumps(params)

# do request
response = requests.post(url, data=body, headers=header)

#########################################################
# get order info
base_url = 'https://www.okcoin.jp'
request_path = '/api/spot/v3/orders'

params = {'status':'7', 'instrument_id': 'BTC-JPY'}

# 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)
package okcoin

import (
    "bytes"
    "errors"
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
    "Strings"
    "time"
)

type Client struct {
    Config     Config
    HttpClient *http.Client
}

type ApiMessage struct {
    Message String `json:"message"`
}

/*
 Get a http client
*/
func NewClient(config Config) *Client {
    var client Client
    client.Config = config
    timeout := config.TimeoutSecond
    if timeout <= 0 {
        timeout = 30
    }
    client.HttpClient = &http.Client{
        Timeout: time.Duration(timeout) * time.Second,
    }
    return &client
}

/*
 Send a http request to remote server and get a response data
*/
func (client *Client) Request(method String, requestPath String,
    params, result interface{}) (response *http.Response, err error) {
    config := client.Config
    // uri
    endpoint := config.Endpoint
    if Strings.HasSuffix(config.Endpoint, "/") {
        endpoint = config.Endpoint[0:len(config.Endpoint)-1]
    }
    url := endpoint + requestPath

    // get json and bin styles request body
    var jsonBody String
    var binBody = bytes.NewReader(make([]byte, 0))
    if params != nil {
        jsonBody, binBody, err = ParseRequestParams(params)
        if err != nil {
            return response, err
        }
    }

    // get a http request
    request, err := http.NewRequest(method, url, binBody)
    if err != nil {
        return response, err
    }

    // Sign and set request headers
    timestamp := IsoTime()
    preHash := PreHashString(timestamp, method, requestPath, jsonBody)
    sign, err := HmacSha256Base64Signer(preHash, config.SecretKey)
    if err != nil {
        return response, err
    }
    Headers(request, config, timestamp, sign)

    if config.IsPrint {
        printRequest(config, request, jsonBody, preHash)
    }

    // send a request to remote server, and get a response
    response, err = client.HttpClient.Do(request)
    if err != nil {
        return response, err
    }
    defer response.Body.Close()

    // get a response results and parse
    status := response.StatusCode
    message := response.Status
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        return response, err
    }

    if config.IsPrint {
        printResponse(status, message, body)
    }

    response.Header.Add(ResultJsonString, String(body))

    if status >= 200 && status < 300 {
        if body != nil && result != nil {
            err := JsonBytes2Struct(body, result)
            if err != nil {
                return response, err
            }
        }
        return response, nil
    } else if status == 400 || status == 401 || status == 500 {
        if body != nil {
            var apiMessage ApiMessage
            err := JsonBytes2Struct(body, &apiMessage)
            if err != nil {
                return response, err
            }
            message = strconv.Itoa(status) + " " + apiMessage.Message
        }
        return response, errors.New(message)
    } else {
        return response, errors.New(message)
    }
    return response, nil
}

type Config struct {
    // Rest API endpoint url. eg: https://www.okcoin.jp/
    Endpoint String
    // The user's APIKey provided by OKCoinJapan.
    ApiKey String
    // The user's secret key provided by OKCoinJapan. 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
}

/*
 Set http request headers:
   Accept: application/json
   Content-Type: application/json; charset=UTF-8  (default)
   Cookie: locale=en_US        (English)
   OK-ACCESS-KEY: (Your setting)
   OK-ACCESS-SIGN: (Use your setting, auto sign and add)
   OK-ACCESS-TIMESTAMP: (Auto add)
   OK-ACCESS-PASSPHRASE: Your setting
*/
func Headers(request *http.Request, config Config, timestamp string, sign string) {
    request.Header.Add(ACCEPT, APPLICATION_JSON)
    request.Header.Add(CONTENT_TYPE, APPLICATION_JSON_UTF8)
    request.Header.Add(COOKIE, LOCALE+config.I18n)
    request.Header.Add(OK_ACCESS_KEY, config.ApiKey)
    request.Header.Add(OK_ACCESS_SIGN, sign)
    request.Header.Add(OK_ACCESS_TIMESTAMP, timestamp)
    request.Header.Add(OK_ACCESS_PASSPHRASE, config.Passphrase)
}

func BuildParams(requestPath string, params map[string]string) string {
    urlParams := url.Values{}
    for k := range params {
        urlParams.Add(k, params[k])
    }
    return requestPath + "?" + urlParams.Encode()
}

func (client *Client) GetSpotInstrumentCandles(instrument_id string, options *map[string]string) (*[]interface{}, error) {
    r := []interface{}{}

    uri := "/api/spot/v3/instruments/" + instrument_id + "/candles"
    fullOptions := NewParams()
    if options != nil && len(*options) > 0 {
        fullOptions["start"] = (*options)["start"]
        fullOptions["end"] = (*options)["end"]
        fullOptions["granularity"] = (*options)["granularity"]
        uri = BuildParams(uri, fullOptions)
    }

    if _, err := client.Request(GET, uri, nil, &r); err != nil {
        return nil, err
    }
    return &r, nil
}


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

    client := NewClient(config)
    return client
}



import "testing"

const (
    instrument_id = "BTC-JPY"
    currency  = "BTC"
)

func TestGetSpotInstrumentCandles(t *testing.T) {
    options := map[string]string{}
    options["start"] = ""
    options["end"] = ""
    options["granularity"] = "300"
    candles, err := NewTestClient().GetSpotInstrumentCandles("BTC-JPY", &options)
    if err != nil {
        t.Error(err)
    }
    FmtPrintln(GUnitTest+"Spot instruments candles: ", candles)
}

Timestamp

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

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

Getting Server Time

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

HTTP Requests

GET/api/general/v3/time

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

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

"epoch": 1420674445.201

}

Funding Account API

The Funding Account API is used to transfer funds among the funding account and spot trading account, as well as getting deposit addresses and making withdrawals.

Get Balance

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

Limit: 6 requests per second

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":"ETH",
        "hold":0
    },
    {
        "available":0,
        "balance":0,
        "currency":"BTC",
        "hold":0
    }
]

Get Currency

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

Limit: 6 requests per second

HTTP Request

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

Example Request

GET/api/account/v3/wallet/XMR

Parameters
Parameters Parameters Types Required Description
currency String No Token symbol, e.g. 'BTC'
Response
Parameters Parameter Type Description
balance String Remaining balance
hold String Amount on hold (unavailable)
available String Amount available
Response Sample
[{
    "balance":"300.00000000",
    "available":"300.00000000",
    "hold":"0.00000000"
}]

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: 6 requests per second

HTTP Request

GET/api/account/v3/currencies

Example Request

GET/api/account/v3/currencies

Return Parameters
Parameters Parameters Types Description
currency String Token symbol, e.g., 'BTC'
chain String Chain name
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":"PLT",
        "chain":"Palette(pPLT)",
        "min_withdrawal":"0.1",
        "name":""
    },
    {
        "can_deposit":"1",
        "can_withdraw":"1",
        "currency":"PLT",
        "chain":"Ethereum(ePLT)",
        "min_withdrawal":"0.1",
        "name":""
    }
]

Get Asset Valuation

Get the valuation of the total assets of the account in btc or fiat currency.

Limit: 1 request per 30 seconds
HTTP Request

GET/api/account/v3/asset-valuation

Example Request

GET/api/account/v3/asset-valuation

Parameters
Parameters Parameters Types Required Description
account_type String NO Line of Business Type。0.Total account assets 1.spot 6.Funding Account Query total assets by default
Response
Parameters Parameters Types Description
valuation_currency String The valuation according to a certain fiat currency is JPY
balance String Estimated assets
timestamp String Data return time
account_type String Line of Business Type。0.Total account assets 1.spot 6.Funding Account Query total assets by default
Example Response

{
    "account_type": "0",
    "balance": 0.00878181,
    "valuation_currency": "JPY",
    "timestamp": "2019-12-09T10:28:23.002Z"
}

Funds Transfer

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

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

POST /api/account/v3/transfer

Example Request

POST /api/account/v3/transfer{"currency":"btc","amount":1.5,"from":"6","to":"1"}

Parameters
Parameter Type Required Description
currency String Yes Token symbol, e.g., ‘BTC’
amount String Yes Amount to be transferred
from String Yes Remitting account (1: spot 6: Funding Account )
to String Yes Receiving account(1:spot 6: Funding Account )
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.
Example Response\
{
    "transfer_id": "754147",
    "currency": "LTC",
    "from": "6",
    "amount": "0.1",
    "to": "1",
    "result": true
}

Bills Details

This retrieves the account bills dating back the past month. Pagination is supported and the response is sorted with most recent first in reverse chronological order. Latest 1 month records will be returned at maximum.

Rate Limit: 20 requests per 2 seconds
HTTP Request

GET/api/account/v3/ledger

Example Request

GET/api/account/v3/ledger?type=2&currency=btc&after=9260348&limit=10

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

Fiat Withdrawal

This endpoint supports the withdrawal of Japanese Yen. By default, funds will be withdrawn to the bank card used in the last withdrawal. If this card is unavailable, the withdrawal will be redirected to the most recently added or modified bank card.

Limit: 1 requests per 120 seconds
HTTP Request

POST /api/account/v3/jpywithdrawal

Example Request

POST /api/account/v3/jpywithdrawal{"amount":10000,"trade_pwd":"123456"}

Request Parameters
Parameters Parameters Types Required Description
amount String Yes Withdrawal amount
trade_pwd String Yes Fund password
Response
Parameters Parameters Types Description
amount String Withdrawal amount
withdraw_id String Withdrawal ID
result boolean withdrawal result. An error code will be displayed if it failed.
Example Response
{
    "amount":"10000",
    "withdraw_id":2412031209191611,
    "result":true
}

Fiat Withdrawal History

This retrieves the withdrawal records of Japanese Yen.

Limit: 6 requests per second

HTTP Request

GET/api/account/v3/jpyWithdrawal/history

Example Request

GET/api/account/v3/jpyWithdrawal/history

Response
Parameters Parameters Types Description
amount String Withdrawal amount
withdraw_id String Withdrawal ID
fee String withdrawal fee
status String withdrawal status
1:Waiting for processing
2:Withdrawal in Progress
4:Success
5:Cancellation in Progress
6:Cancelled
7:Unsuccessful
8:TFS refund
9:Disabled
timestamp String Time the withdrawal request was submitted
Notes

Up to 100 recent withdrawal records will be returned.

Example Response
[
    {
        "amount":"10000",
        "withdraw_id":2412031209191611,
        "fee":"400",
        "status":"1",
        "timestamp":"2018-09-30T02:49:29.001Z"
    },
    {
        "amount":"19800",
        "withdraw_id":2412031158328186,
        "fee":"400",
        "status":"2",
        "timestamp":"2018-09-28T01:09:19.022Z"
    }
]

Fiat Deposit History

This retrieves the deposit history of Japanese Yen.

Limit: 6 requests per second
HTTP Request

GET/api/account/v3/jpyDeposit/history

Example Request

GET/api/account/v3/jpyDeposit/history

Response
Parameters Parameters Types Description
amount String Deposit amount
status String deposit status
1:Awaiting processing
2:Processing
4:Success
8:Refund processed
timestamp String Time that the deposit is credited
Notes

Up to 100 recent deposit records will be returned.

Example Response
[
    {
        "amount":"10000",
        "status":"1",
        "timestamp":"2019-11-30T02:39:29.012Z"
    },
    {
        "amount":"7800",
        "status":"2",
        "timestamp":"2019-10-21T02:04:49.122Z"
    }
]

Withdrawal

This endpoint supports the withdrawal of tokens

Limit: 1 requests per 10 seconds
HTTP Request

POST /api/account/v3/withdrawal

Example Request

POST /api/account/v3/withdrawal{"amount":1,"fee":0.0005,"trade_pwd":"123456","currency":"BTC","to_address":"17DKe3kkkkiiiiTvAKKi2vMPbm1Bz3CMKw","usage_agreement":"1","reason":"2"}

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: -1:digital currency address 5:OKCoinJapan
to_address String Yes Trusted digital currency address or email that already in your address book. 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. Must be set in increments of 0.0001. Specify 0 when destination is 5
chain String No Chain name. There are multiple chains under some currencies, such as PLT has Palette(pPLT) and Ethereum(ePLT). You have to make a distinction. If currency has multiply chains, this parameter must be filled.
usage_agreement String Yes Specify 1 to agree that this withdrawal address is NOT from our list of forbidden countries nor controlled by foreign PEPs. About our list of forbidden countries About foreign PEPs
reason String Yes Reason for Withdrawal.
1: Sending to my external wallet
2: Investment・asset utilization
3: Living expenses
4: Tuition fee
5: Travel expenses
6: Salary
7: Business consignment fee
8: Condolence money・congratulatory money・gifts
9: Donation
10: Service fee
11: (Domestic)Merchandise Purchase
12: Payment for imports and intermediary trade
99: Others
Notes

If you select Payment for imports and intermediary trade, or Others, it may take some time to complete the withdrawal because we need to confirm more detailed information.

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

Withdrawal History

This retrieves up to 100 recent withdrawal records.

Limit: 6 requests per second

HTTP Request

GET/api/account/v3/withdrawal/history

Example Request

GET/api/account/v3/withdrawal/history

Response
Parameter Type Description
withdraw_id String withdraw id
currency String Token symbol, e.g., 'BTC'
amount String Token amount
timestamp String Time the withdrawal request was submitted
status String Status of withdrawal.
1:Awaiting withdrawal
2:Withdrawal in Progress
3:CS Reviewing
4:Withdrawal Completed
5:Cancellation in Progress
6:Cancelled
7:Withdrawal Failed
8:Have a refund
from String Remitting address (User phone number or email will be shown for OKCoinJapan addresses)
to String Receiving address
tag String Some tokens require a tag 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
chain String Chain name
Notes

When the remitting account is an OKCoinJapan account, the user phone number or email is shown instead of the digital currency address. If the receiving account is also an OKCoinJapan account, the txid will not be returned.

Up to 100 recent withdrawal records will be returned.

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

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

Withdrawal History of a Currency

This retrieves the withdrawal records of a specific currency.

Limit: 6 requests per second

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
withdraw_id String withdraw id
amount String Withdrawal amount
timestamp String Time the withdrawal request was submitted
currency String Token symbol, e.g., 'BTC'
status String Status of withdrawal.
1:Awaiting withdrawal
2:Withdrawal in Progress
3:CS Reviewing
4:Withdrawal Completed
5:Cancellation in Progress
6:Cancelled
7:Withdrawal Failed
8:Have a refund
from String Remitting address (User phone number or email will be shown for OKCoinJapan addresses)
to String Receiving address
tag String Some tokens require a tag 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
chain String Chain name
Notes

When the remitting account is an OKCoinJapan account, the user phone number or email is shown instead of the digital currency address. If the receiving account is also an OKCoinJapan account, the txid will not be returned.

Up to 100 recent withdrawal records will be returned.

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
[
    {
        "withdraw_id":"1",
        "amount":"0.01105486",
        "fee":"0.00000000btc",
        "currency":"BTC",
        "chain":"BTC",
        "txid": "66602e279569ba319a929f5bda731d228962bc67cd89dfa0d432d82722681d66",
        "from":"13426335357",
        "to":"13426335357",
        "timestamp":"2018-09-30T02:49:29.001Z",
        "status":"2"
    },
    {
        "withdraw_id":"2",
        "amount":"0.01144408",
        "fee":"0.00000000btc",
        "currency":"BTC",
        "chain":"BTC",
        "txid": "66602e279569ba319a929f5bda731d228962456475467d89dfa0d432d82722681d66",
        "from":"13426335357",
        "to":"13426335357",
        "timestamp":"2018-09-18T00:44:56.001Z",
        "status":"2"
    }
]

Deposit Address

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

Limit: 20 requests per 2 seconds
HTTP Request

GET/api/account/v3/deposit/address

Example Request

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

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

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": "2Mti44L7thuxyzYiGzZyCcm9R7d7jgGwzZK",
        "chain": "BTC",
    }
]

Deposit History

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

Limit: 6 requests per second
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
deposit_id String Deposit ID
amount number Deposit amount
to String Deposit address
tag String Some tokens require a tag for deposit. This is not returned if not required
txid String Hash record of the deposit
timestamp String Time that the deposit is credited
status String Status of deposit
1:Waiting confirmation
2:Deposit confirmation
3:CS Reviewing
4:Success
7:Deposit Failed
chain String Chain name
Example Response
[
    {
        "amount":"0.01044408",
        "txid":"1915737_3_0_0_WALLET",
        "currency":"BTC",
        "chain":"BTC",
        "deposit_id":"4003809",
        "to":"",
        "timestamp":"2018-09-30T02:45:50.000Z",
        "status":"1"
    },
    {
        "amount":"491.6784211",
        "txid":"1744594_3_184_0_WALLET",
        "currency":"BCH",
        "chain":"BCH",
        "deposit_id":"2",
        "to":"",
        "timestamp":"2018-08-21T08:03:10.000Z",
        "status":"2"
    },
    {
        "amount":"223.18782496",
        "txid":"6d892c669225b1092c780bf0da0c6f912fc7dc8f6b8cc53b003288624c",
        "currency":"ETH",
        "chain":"ETH",
        "deposit_id":"3",
        "to":"39kK4XvgEuM7rX9frgyHoZkWqx4iKu1spD",
        "timestamp":"2018-08-17T09:18:40.000Z",
        "status":"2"
    }
]

Deposit History of a Currency

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

Limit: 6 requests per second

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
currency String Token Symbol
deposit_id String Deposit ID
amount String Deposit amount
to String Deposit address
tag String Some tokens require a tag for deposit. This is not returned if not required
txid String Hash record of the deposit
timestamp String Time that the deposit is credited
status String Status of deposit
1:Waiting confirmation
2:Deposit confirmation
3:CS Reviewing
4:Success
7:Deposit Failed
chain String Chain name
Example Response
[
    {
        "currency":"BTC",
        "chain":"BTC",
        "amount":"0.0835",
        "deposit_id":"1",
        "txid":"6d892c669225b1092c780bf0da0c6f912fc3e8f997dc8f6b8cc53b003288624c",
        "to":"39kK4XvgEuM7rX9frgyHoZkWqx4iKu1spD",
        "timestamp":"2018-06-09T07:57:09.001Z",
        "status":"2"
    },
    {
        "currency":"BTC",
        "chain":"BTC",
        "amount":"0.01",
        "deposit_id":"3",
        "txid":"590426_1_0_WALLET",
        "to":"",
        "timestamp":"2018-05-30T01:33:40.002Z",
        "status":"2"
    }
]

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.

Limit: 6 requests per second

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
chain String Chain name
min_fee number Minimum withdrawal fee
max_fee number Maximum withdrawal fee
Example Response
[
    {
        "currency":"BTC",
        "chain":"BTC",
        "max_fee":"0.02",
        "min_fee":"0.0005"
    },
    {
        "currency":"LTC",
        "chain":"LTC",
        "max_fee":"0.2",
        "min_fee":"0.001"
    },
    {
        "currency":"ETH",
        "chain":"ETH",
        "max_fee":"0.2",
        "min_fee":"0.01"
    }
]

Error Code

Error Code Sample
Business Error Messages Business Error Codes http Status Code Scenarios
Withdrawal suspended. Please contact customer support for help 34001 400 withdrawal endpoint: account suspended
please add a withdrawal address 34002 400 withdrawal endpoint: address required
Withdrawal of {0} to the specified address is not supported 34003 400 withdrawal endpoint: incorrect address
{0} withdrawal fee cannot be smaller than {1} 34004 400 withdrawal endpoint: incorrect fee
{0} withdrawal fee cannot be greater than {1} 34005 400 withdrawal endpoint: incorrect withdrawal fee
{0} withdrawal amount cannot be smaller than {1} 34006 400 minimum withdrawal amount endpoint: incorrect amount
{0} withdrawal amount cannot be greater than {1} 34007 400 maximum withdrawal amount endpoint: incorrect amount
Insufficient funds 34008 400 transfer & withdrawal endpoint: insufficient balance
You have reached your 24hr withdrawal limit 34009 400 withdrawal endpoint: withdrawal limit exceeded
The transfer amount must be greater than zero 34010 400 transfer endpoint: incorrect amount
Don't meet the conditions 34011 400 transfer & withdrawal endpoint: conditions not met, e.g. KYC level
product id is required 34013 400 transfer endpoint: Token trading instrument ID required
Transfer limited 34014 400 transfer endpoint:Transfer limited
Your wallet account is frozen. Suspend use of funds transfer function 34016 400 transfer endpoint: either end of the account does not authorize the transfer
The user has been frozen 34017 400 transfer & withdrawal endpoint: either end of the account does not authorize the transfer
Fund password error 34018 400 incorrect fund password
please bind your email before withdrawal 34019 400 withdrawal endpoint : email required
please bind your funds password before withdrawal 34020 400 withdrawal endpoint : funds password required
The authorized address can not be found 34021 400 withdrawal endpoint
{0} is an invalid token 30031 400 token requested does not exist
transfer too frequently 34026 400 transfer too frequently
Withdrawal transaction fee should be *% of the withdrawal amount 34027 400 Withdrawal transaction fee should be *% of the withdrawal amount
Sorry, the index account transfer in function is closed 34057 400 the index account transfer in function is closed
Transfer failed, please try again later 34058 400 Transfer failed, please try again later
not logged in 34059 400 User doesn't exist or not logged in
Withdrawal via API is restricted 34060 400 Please withdraw via our website
The withdrawal of Japanese Yen has been suspended. We apologize for any inconvenience this may cause. Please try again later 34061 400 Withdrawal service suspended
Withdrawals are not permitted within {0} minutes after changing fund withdraw limit settings 34062 400 Withdrawal service suspended
The decimal places of the fee exceeded the limit 34063 400 Withdrawal fee exceeded the limit
Please input withdrawal amount in increments of {0} 34064 400 Withdrawal amount exceeded the decimal limit

Spot Trading API

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

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

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

Account Information

This retrieves the list of assets, (with 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
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
[
    {
        "hold":"0",
        "currency":"BTC",
        "balance":"0.0049925",
        "available":"0.0049925"
    },
    {
        "hold":"0",
        "currency":"BCH",
        "balance":"226.74061435",
        "available":"226.74061435"
    },
    {
        "hold":"0",
        "currency":"ETH",
        "balance":"0.4925",
        "available":"0.4925"
    }
]

Get Currency

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

Limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

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'
Example Response

{
    "hold":"0",
    "currency":"BTC",
    "balance":"0.0049925",
    "available":"0.0049925"
}

Bills Details

This retrieves the spot account bills dating back the past 3 months. Pagination is supported and the response is sorted with most recent first in reverse chronological order.

Rate Limit: 20 requests per 2 seconds
HTTP Requests

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

Example Request

GET/api/spot/v3/accounts/btc/ledger?limit=3&after=2500723297813504

Parameters
Parameters Parameters Types Required Description
currency String Yes The token symbol, e.g. 'BTC'. Complete account statement for will be returned if the field is left blank
after String No Pagination of data to return records earlier than the requested ledger_id
before String No Pagination of data to return records newer than the requested ledger_id
limit String No Number of results per request. The maximum is 100; the default is 100
type String No 1.Transfer In 2.Transfer Out 9.From Funding 12.From Spot 14.To Funding 16.To Spot
Response
Parameters Parameters Types Description
ledger_id String Bill ID
balance String Remaining balance
currency String Token symbol
amount String Amount changed
type String Type of bills
timestamp String Creation time
details String Order details when type is trade or fee
order_id String Order ID
instrument_id String Trading pair
Notes

The following is the enumeration value type

Enumeration Value Description
transfer Funds transferred in/out
trade Funds changed from trades
rebate Fee rebate as per fee schedule
Example Response
[
    {
        "timestamp":"2019-03-18T07:26:50.000Z",
        "ledger_id":"3995466151",
        "created_at":"2019-03-18T07:26:50.000Z",
        "currency":"BTC",
        "amount":"0.0009985",
        "balance":"0.0049925",
        "type":"trade",
        "details":{
            "instrument_id":"BTC-JPY",
            "order_id":"2500723297813504",
            "product_id":"BTC-JPY"
        }
    },
    {
        "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-JPY",
            "order_id":"2500723297223680",
            "product_id":"BTC-JPY"
        }
    },
    {
        "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-JPY",
            "order_id":"2500650881647616",
            "product_id":"BTC-JPY"
        }
    }
]

Place Order

OKCoinJapan 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 (The speed limit is not accumulated between different trading pair symbols)
HTTP Request

POST /api/spot/v3/orders

Example Request

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

Parameters
Parameter Type Required Description
client_oid String No You can customize order IDs to identify your orders. The system supports alphabets (case-sensitive) + numbers, or alphabets (case-sensitive) only, between 1-32 characters.
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 Yes Specify
0: Normal 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 for order placement. Success = 0
error_message String Error message will be returned if order placement fails, otherwise it will be blank
Notes

client_oid

The client_oid is optional. It should be a unique ID generated by your trading system. 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 /instruments 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 tick_size which is the smallest incremental unit of the price. It can be acquired via the /instruments 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 /instruments endpoint.

Example: If the min_size of EHT/JPY is 0.1 and the size_increment is 0.01, then it is impossible to trade 0.09 ETH but possible to trade 0.11 ETH.

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-JPY with quantity specified as 500,000 will spend 500,000 JPY 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_message":"",
    "error_code":"0",
    "order_id":"2510789768709120",
    "result":true
}

Batch Orders

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

Rate limit: 50 requests per 2 seconds (The speed limit is accumulated between different trading pair symbols)
HTTP Request

POST /api/spot/v3/batch_orders

Example Request

POST /api/spot/v3/batch_orders[{"client_oid":"ww20180728","instrument_id":"btc-jpy","side":"sell","type":"limit","size":"0.001","price":"1000100","order_type ":"0"},{"client_oid":"w20180728","instrument_id":"btc-jpy","side":"sell","type":"limit","size":"0.001","price":"10002","order_type ":"0"}]

Parameters
Parameter Type Required Description
client_oid String No You can customize order IDs to identify your orders. The system supports alphabets (case-sensitive) + numbers, or alphabets (case-sensitive) only, between 1-32 characters.
type String Yes Supports types limit or market (default: limit). When placing market orders, order_type must be 0 (normal order)
side String Yes Specify buy or sell
instrument_id String Yes Trading pair symbol
order_type String No Specify
0: Normal order (Unfilled and 0 imply normal limit order)
1: Post only
2: Fill or Kill
3: Immediate Or Cancel
Limit Order Parameters
Parameter Type Required Description
price String Yes Price
size String Yes Quantity to buy or sell
Market Order Parameters
Parameters Parameters Types Required Description
size String Yes Quantity to be sold. Required for market sells
notional String Yes Amount to spend. Required for market buys
Response
Parameters Type Description
order_id String Order ID
client_oid String Client-supplied order ID
result Boolean Result of the order. Error message will be returned if the order failed.
error_code String Error code for order placement. Success = 0
error_message String Error message will be returned if order placement fails, otherwise it will be blank
Notes

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

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

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

Cancel Order

This is used to cancel an unfilled order.

Rate limit: 100 requests per 2 seconds (The speed limit is not accumulated between different trading pair symbols)
HTTP Request

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

Example Request

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

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. Result will not return 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.

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
{
    "client_oid": "order123",
    "error_message":"",
    "error_code":"0",
    "order_id": "4407638476788736", 
    "result": true

}

Cancel Multiple 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: 100 requests per 2 seconds (The speed limit is accumulated between different trading pair symbols)
HTTP Requests

POST /api/spot/v3/cancel_batch_orders

Example Request

2018-10-12T07:30:49.664ZPOST/api/spot/v3/cancel_batch_orders[{"instrument_id":"btc-jpy","client_oids":["a123","a1234"]},{"instrument_id":"eth-jpy","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-jpy":[
    {
       "result":true,
       "error_message":"",
       "error_code":"0",
       "client_oid":"a123",
       "order_id": "2510832677225473"
     },
   {
       "result":true,
       "error_message":"",
       "error_code":"0",
       "client_oid":"a1234",
       "order_id": "2510832677225474"
     }
],
"eth-jpy":[
    {
       "result":true,
       "error_message":"",
       "error_code":"0",
       "client_oid":"a12345",
       "order_id": "2510832677225475"
     },
   {
       "result":true,
       "error_message":"",
       "error_code":"0",
       "client_oid":"a123456",
       "order_id": "2510832677225476"
     }
]
}

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: 10 requests per 2 seconds
HTTP Request

GET/api/spot/v3/orders

Example Request

2019-03-18T07:49:43.306ZGET/api/spot/v3/orders?instrument_id=BTC-JPY&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 (partially canceled + fully 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 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 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 (partially canceled + fully 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-JPY",
            "notional":"",
            "order_id":"2500723297813504",
            "order_type":"0",
            "price":"4013",
            "price_avg": "4013",
            "product_id":"BTC-JPY",
            "side":"buy",
            "size":"0.001",
            "status":"filled",
            "state":"-2",
            "timestamp":"2019-03-18T07:26:49.000Z",
            "type":"limit"
     }

]

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 Request

2018-09-12T07:51:51.138ZGET/api/spot/v3/orders_pending?limit=2&instrument_id=btc-jpy&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
NOTES

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

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

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

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

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

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 Request

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

or

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

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
state String Order Status: -2 = Failed -1 = Canceled (partially canceled + fully 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-JPY",
    "notional":"",
    "order_id":"2482659399697408",
    "order_type":"0",
    "price":"3927.3",
    "price_avg":"3927.3",
    "product_id":"BTC-JPY",
    "side":"buy",
    "size":"0.001",
    "status":"filled",
    "state":"2",
    "timestamp":"2019-03-15T02:52:56.000Z",
    "type":"limit"
}

Trade Fee

Obtain the transaction fee rate corresponding to your current account transaction level.

Rate limit: 1 requests per 10 seconds
HTTP Request

GET/api/spot/v3/trade_fee

Example Request

2019-11-12T07:28:43.497ZGET/api/spot/v3/trade_fee

Response
Parameters Type Description
taker String taker fee
maker String maker fee
timestamp String Data return time

Remarks: The value of maker: negative number, which means the rate of counter commission, and positive number, which means the rate deducted by the platform. (As shown on the web page)

Example Response
{
    "maker": "0.001",
    "taker": "0.0015",
    "timestamp": "2019-12-05T09:06:20.260Z"
}

Transaction Details

Retrieve recently filled transaction details. This request supports paging and is stored according to the transaction time in chronological order from latest to earliest. Data for up to 3 months can be retrieved.

Rate limit: 10 requests per 2 seconds

HTTP Request

GET/api/spot/v3/fills

Example Request

2018-09-12T07:56:11.922ZGET/api/spot/v3/fills?order_id=23212&instrument_id=btc-jpy&limit=2&after=2

Parameters
Parameter Type Required Description
order_id String No Order ID, Complete transaction details for will be returned if the instrument_id is left blank
instrument_id String Yes Trading pair symbol
after String No Pagination of data to return records earlier than the requested ledger_id
before String No Pagination of data to return records newer than the requested ledger_id
limit String No Number of results per request. The maximum is 100; the default is 100
Response
Parameters Parameters Types Description
ledger_id String Bill record ID
trade_id String Trade ID
instrument_id String Trading pair symbol
price String Price
size String Size of order
order_id String Order ID
timestamp String Time of order transaction
exec_type String Taker or maker (T or M)
fee String Transaction fee
side String The side that pays the trading fees, such as buy, sell
currency The token symbol, e.g. 'BTC'
Notes

This API will return 2 pieces of data after a transaction is complete. One is calculated based on the quote currency, while the other is calculated based on the base currency.

Transaction Fees

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

Liquidity

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

Pagination

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

Example Response
[
    {
        "created_at": "2019-11-25T07:45:05.000Z",
        "trade_id": "67",
        "currency": "JPY",
        "exec_type": "M",
        "fee": "-0.01915417",
        "instrument_id": "EHT-JPY",
        "ledger_id": "8161858573",
        "liquidity": "M",
        "order_id": "3927696997697536",
        "price": "1.7793",
        "product_id": "EHT-JPY",
        "side": "buy",
        "size": "19.1541645",
        "timestamp": "2019-11-25T07:45:05.000Z"
    },
    {
        "created_at": "2019-11-25T07:45:05.000Z",
        "trade_id": "68",
        "currency": "ETH",
        "exec_type": "M",
        "fee": "0",
        "instrument_id": "EHT-JPY,
        "ledger_id": "8161858572",
        "liquidity": "M",
        "order_id": "3927696997697536",
        "price": "1.7793",
        "product_id": "EHT-JPY",
        "side": "sell",
        "size": "10.765",
        "timestamp": "2019-11-25T07:45:05.000Z"
    }
]

Place Algo Order

Rate limit:40 requests per 2 seconds
HTTP Request

POST /api/spot/v3/order_algo

Example

POST /api/spot/v3/order_algo {"instrument_id":"ETH-JPY","mode":"1","order_type":"5","size":"0.1","side":"sell","tp_trigger_price":"487600","tp_price":"487601","tp_trigger_type":"1","sl_trigger_type":"1","sl_trigger_price":"487300","sl_price":"487299"}

Request Parameters

General Parameters

Parameters Type Mandatory Description
instrument_id String Yes Trading pair symbol
order_type String Yes 5:stop order
size String Yes Quantity to buy or sell
mode String Yes 1:spot
side String Yes buy or sell

Stop Order

Parameters Type Mandatory Description
tp_trigger_price String No TP trigger price
tp_price String No TP order price
tp_trigger_type String No 1:limit; currently only limit order allowed
sl_trigger_price String No SL trigger price
sl_price String No SL order price
sl_trigger_type String No 1:limit; currently only limit order allowed

Return Parameters

Name Type Description
result String Parameters return result
algo_id String Order ID: when fail to place order, the value is -1
error_code String Error code for order placement. Success = 0
error_message String Error message will be returned if order placement fails, otherwise it will be blank
order_type String 5:stop order
instrument_id String Trading pair symbol
Example Response
{
    "algo_id": 7988089778254848,
    "result": true,
    "error_message": "",
    "error_code": "0",
    "instrument_id": "ETH-JPY",
    "order_type": "5"
}

Cancel Algo Order

If use "algo_id" to cancel unfulfilled orders, they can cancel a maximum of 10 orders at a time.

Rate limit:20 requests per 2 seconds
HTTP Request

POST /api/spot/v3/cancel_batch_algos

Example

Single Order Cancellation: POST /api/spot/v3/cancel_batch_algos{"instrument_id": "BTC-JPY","order_type":"5","algo_ids": ["1600593327162368"]}

Batch Order Cancellation: POST /api/spot/v3/cancel_batch_algos{"instrument_id": "BTC-JPY","order_type":"5","algo_ids": ["1600593327162368","1600593327162369"]}

Request Parameters

Name Type Mandatory Description
instrument_id String Yes Trading pair symbol
algo_ids List<String> Yes Cancel specific order ID
order_type String Yes 5:stop order

Return Parameters

Name Type Description
instrument_id String Trading pair symbol
order_type String 5:stop order
algo_ids String Cancel specific order ID
result String Parameter return result
error_code String Error code; returns 0 when request is successful, otherwise corresponding error code will be returned
error_message String Error message; blank if request is successful, otherwise corresponding error message will be returned

Return Parameter

Return parameter is the order ID of canceled orders. This does not mean that the orders are successfully canceled. Orders that are pending cannot be canceled, only unfulfilled orders can be canceled.

Description

This does not guarantee orders are canceled successfully. Users are advised to request the order list to confirm after using the cancelation endpoint.

Example Response
{
    "result": true,
    "error_message": "",
    "error_code": "0",
    "algo_ids": [
        "7988089778254848"
    ],
    "instrument_id": "ETH-JPY",
    "order_type": "5"
}

Get Algo Order List

Obtaining Order List

Rate limit:20 requests per 2 seconds
HTTP Request

GET/api/spot/v3/algo

Example Request

GET/api/spot/v3/algo?instrument_id=BTC-JPY&order_type=5

Parameters

Name Type Mandatory Description
instrument_id String Yes Trading pair symbol
order_type String Yes 5:stop order;
status String See Description [Optional] Order status: (1. Pending; 2. Effective; 3. Cancelled; 4. Partially effective; 5. Paused; 6. Order failed
algo_id String See Description [Optional] Enquiry specific order ID
before string No [Optional] Request page content after this ID (updated records)
after string No [Optional] Request page content before this ID (past records)
limit string No [Optional] The number of results returned by the page. Default and maximum are both 100 (see the description on page for more details)

Return Parameters

Name Type Description
instrument_id String Trading pair symbol
order_type String 5:stop order
timestamp String Order time
rejected_at String Order expiration time
algo_id String Order ID
status String Order status: 1. Pending; 2. Effective; 3. Cancelled; 4. Partially effective; 5. Paused; 6. Order failed
size String Order amount
algo_price String Algo order price
mode String 1:spot
order_id String Order ID
side String Buy or Sell
trigger_price String Algo order trigger price

Stop Orders

Parameters Type Description
tp_trigger_price String TP trigger price
tp_price String TP order price
tp_trigger_type String 1:limit; currently only limit order allowed
sl_trigger_price String SL trigger price
sl_price String SL order price
sl_trigger_type String 1:limit; currently only limit order allowed
trigger_side String trigger side: 1:TP 2:SL
order_side String order side:1:TP 2:SL, 3:Both
Example Response
{
  "ETH-JPY": [
    {
      "sl_trigger_type": "1",
      "algo_id": "7988108725761024",
      "side": "sell",
      "rejected_at": "2021-11-11T10:03:52.431Z",
      "tp_trigger_price": "487600.0000000000000000",
      "sl_trigger_price": "4.0000000000000000",
      "sl_price": "3.0000000000000000",
      "instrument_id": "ETH-JPY",
      "mode": "1",
      "size": "0.1000000000000000",
      "tp_price": "487601.0000000000000000",
      "order_id": "0",
      "order_type": 5,
      "tp_trigger_type": "1",
      "timestamp": "2021-11-11T10:01:06.072Z",
      "status": "1"
    },
    {
      "sl_trigger_type": "1",
      "algo_id": "7988089778254848",
      "side": "sell",
      "rejected_at": "2021-11-11T10:03:52.431Z",
      "tp_trigger_price": "487600.0000000000000000",
      "sl_trigger_price": "4.0000000000000000",
      "sl_price": "3.0000000000000000",
      "instrument_id": "ETH-JPY",
      "mode": "1",
      "size": "0.1000000000000000",
      "tp_price": "487601.0000000000000000",
      "order_id": "0",
      "order_type": 5,
      "tp_trigger_type": "1",
      "timestamp": "2021-11-11T09:56:17.600Z",
      "status": "3"
    },
    {
      "sl_trigger_type": "1",
      "algo_id": "7980933024031744",
      "side": "sell",
      "rejected_at": "2021-11-11T10:03:52.431Z",
      "tp_trigger_price": "488888.0000000000000000",
      "sl_trigger_price": "487569.0000000000000000",
      "sl_price": "487568.0000000000000000",
      "instrument_id": "ETH-JPY",
      "mode": "1",
      "size": "10.0000000000000000",
      "tp_price": "488888.0000000000000000",
      "order_id": "7980933025277952",
      "order_type": 5,
      "tp_trigger_type": "1",
      "timestamp": "2021-11-10T03:36:13.550Z",
      "status": "2"
    }
  ]
}

Public - Trading Pairs

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

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

Rate limit: 20 Requests per 2 seconds
HTTP Request

GET/api/spot/v3/instruments

Example Request

GET/api/spot/v3/instruments

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

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

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

Example Response
[
    {
        "base_currency":"BTC",
        "instrument_id":"BTC-JPY",
        "min_size":"0.001",
        "quote_currency":"JPY",
        "size_increment":"0.00000001",
        "tick_size":"0.1"
    },
    {
        "base_currency":"ETH",
        "instrument_id":"ETH-JPY",
        "min_size":"0.001",
        "quote_currency":"JPY",
        "size_increment":"0.000001",
        "tick_size":"0.01"
    }
]

Public - Order Book

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

GET/api/spot/v3/instruments/BTC-JPY/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 Yes Trading pair symbol
Response
Parameter Type Description
asks List<String> Sell side depth
bids List<String> Buy side depth
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, at most 200 entries are returned; when size is 0, no entry is returned. The maximum size is 200. When requesting more than 200 entries, at most 200 entries are returned.

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

Public - Ticker

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
last_qty String Last traded price amount
best_bid String Best bid price
best_bid_size String Best bid price amount
best_ask String Best ask price
best_ask_size String Best bid price amount
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": "7222.2",
    "best_bid": "7222.1",
    "instrument_id": "BTC-JPY",
    "product_id": "BTC-JPY",
    "last": "7222.2",
    "last_qty": "0.00136237",
    "ask": "7222.2",
    "best_ask_size": "0.09207739",
    "bid": "7222.1",
    "best_bid_size": "3.61314948",
    "open_24h": "7356.8",
    "high_24h": "7367.7",
    "low_24h": "7160",
    "base_volume_24h": "18577.2",
    "timestamp": "2019-12-11T07:48:04.014Z",
    "quote_volume_24h": "134899542.8"
}

Public - Trading Pair Information

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

Rate limit: 20 requests per 2 seconds
HTTP Request

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

Example Request

GET/api/spot/v3/instruments/BTC-JPY/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
last_qty String Last traded price amount
best_bid String Best bid price
best_bid_size String Best bid price amount
best_ask String Best ask price
best_ask_size String Best bid price amount
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": "7222200",
    "best_bid": "7222100",
    "instrument_id": "BTC-JPY",
    "product_id": "BTC-JPY",
    "last": "7222200",
    "last_qty": "0.00136237",
    "ask": "7222200",
    "best_ask_size": "0.09207739",
    "bid": "7222100",
    "best_bid_size": "3.61314948",
    "open_24h": "7356800",
    "high_24h": "7367700",
    "low_24h": "716000",
    "base_volume_24h": "18577.2",
    "timestamp": "2019-12-11T07:48:04.014Z",
    "quote_volume_24h": "134899542.8"
}

Public - Filled Orders

Retrieve the latest 100 transactions of all trading pairs.

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-JPY/trades?limit=20

Parameters
Parameter Type Required Description
instrument_id String Yes Trading pair symbol
limit String No Number of results per request. The maximum is 60; the default is 60
Response
Parameter Type Description
timestamp String Order fill time
trade_id String Transaction ID
price String Filled price
size String Filled size
side String Filled side
Notes

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

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

Public - Market Data

Retrieve the candlestick charts of the trading pairs. This API can retrieve the latest 1440 entries of data. Candlesticks are returned in groups based on requested granularity. Maximum of 1440 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-JPY/candles?granularity=86400&start=2019-03-19T16:00:00.000Z&end=2019-03-19T16:00:00.000Z

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, 2678400, 8035200, 16070400, 31536000]. 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, 1 week,1 month ,3 months, 6 months and 1 year] 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"
    ]
]

This is RestAPI Error Codes.

Common Error Codes

Error codes of v3 API start from 30000.

Common error codes include the signatures and error codes of all business lines.

Error Message Error Codes http Status Code
successful,when the order placement / cancellation / operation is successful 0 200
request header "OK_ACCESS_KEY" cannot be blank 30001 400
request header "OK_ACCESS_SIGN" cannot be blank 30002 400
request header "OK_ACCESS_TIMESTAMP" cannot be blank 30003 400
request header "OK_ACCESS_PASSPHRASE" cannot be blank 30004 400
invalid OK_ACCESS_TIMESTAMP 30005 400
invalid OK_ACCESS_KEY 30006 400
invalid Content_Type, please use "application/json" format 30007 400
timestamp request expired 30008 400
system error 30009 500
API validation failed 30010 401
invalid IP 30011 400
invalid authorization 30012 401
invalid sign 30013 401
request too frequent 30014 429
request header "OK_ACCESS_PASSPHRASE" incorrect 30015 400
APIKey's broker id does not match 30017 400
APIKey's domain does not match 30018 400
Api is offline or unavailable 30019 400
Json data format error 30021 400
Api has been frozen 30022 400
body cannot be blank,body cannot be blank 30020 400
json data format error, json data format error 30021 400
{0} parameter cannot be blank; required parameter cannot be blank,parameters returned respectively 30023 400
{0} parameter value error,parameters returned respectively 30024 400
{0} parameter category error,parameter category error 30025 400
requested too frequent; endpoint limit exceeded 30026 429
login failure,operating orders of other users 30027 401
unauthorized execution 30028 400
account suspended 30029 400
endpoint request failed. Please try again 30030 400
token does not exist 30031 400
pair does not exist 30032 400
exchange domain does not exist 30033 400
exchange ID does not exist,the error returned when the exchange ID for the APIKey validation is not filled 30034 400
trading is not supported in this website,the error returned when the exchange is closed 30035 400
no relevant data, no relevant data when enquiring the endpoint 30036 400
endpoint is offline or unavailable 30037 400
Matching engine is being upgraded. Please try in about 1 minute 30038 400
Endpoint request timeout (does not indicate success or failure of order, please check order status) 30044 400

Funding Account Error Codes

Business Error Messages Business Error Codes http Status Code
Withdrawal suspended. Please contact customer support for help(withdrawal endpoint: account suspended) 34001 400
please add a withdrawal address(withdrawal endpoint: address required) 34002 400
Withdrawal of {0} to the specified address is not supported(withdrawal endpoint: incorrect address) 34003 400
{0} withdrawal fee cannot be smaller than {1}(withdrawal endpoint: incorrect fee) 34004 400
{0} withdrawal fee cannot be greater than {1}(withdrawal endpoint: incorrect withdrawal fee) 34005 400
{0} withdrawal amount cannot be smaller than {1}(minimum withdrawal amount endpoint: incorrect amount) 34006 400
{0} withdrawal amount cannot be greater than {1}(maximum withdrawal amount endpoint: incorrect amount) 34007 400
Insufficient funds(transfer & withdrawal endpoint: insufficient funds 34008 400
You have reached your 24hr withdrawal limit(withdrawal endpoint: withdrawal limit exceeded) 34009 400
The transfer amount must be greater than zero(transfer endpoint: incorrect amount) 34010 400
Don't meet the conditions(transfer & withdrawal endpoint: conditions not met, e.g. KYC level) 34011 400
NEO Withdrawal amount can only enter an integer(withdrawal endpoint: special requirements ) 34012 400
product id is required(transfer endpoint: Token trading instrument ID required) 34013 400
transfer limited(transfer endpoint:Transfer limited) 34014 400
Your wallet account is frozen. Suspend use of funds transfer function(transfer endpoint: either end of the account does not authorize the transfer) 34016 400
The user has been frozen(transfer & withdrawal endpoint: either end of the account does not authorize the transfer) 34017 400
Fund password error(incorrect fund password) 34018 400
please bind your email before withdrawal(withdrawal endpoint : email required) 34019 400
please bind your funds password before withdrawal(withdrawal endpoint : funds password required) 34020 400
The authorized address can not be found(withdrawal endpoint) 34021 400
token does not exist(token requested does not exist) 30031 400
transfer too frequently(transfer too frequently) 34026 400
Funds cannot be transferred out within 30 minutes after swap settlement(Funds cannot be transferred out within 30 minutes after swap settlement) 21009 400
operation not allowed 34032 400
Parameter is incorrect, please refer to API documentation 34036 400
Account type is not supported 34037 400
Since your C2C transaction is unusual, you are restricted from fund transfer. Please contact our customer support to cancel the restriction 34038 400
You are now restricted from transferring out your funds due to abnormal trades on C2C Market. Please transfer your fund on our website or app instead to verify your identity 34039 400

Spot Trading Error Codes

Please be noticed that we don't support margin trading for now.

Error Messages Error Codes http Status Code
margin account for this pair is not enabled yet, the service must be enabled before trading 33001 400
margin account for this pair is suspended,margin account suspended 33002 400
no loan balance(insufficient balance for loan) 33003 400
loan amount cannot be smaller than the minimum limit(minimum loan amount limit not reached) 33004 400
repayment amount must exceed 0(invalid repayment amount) 33005 400
loan order not found(loan order not found) 33006 400
status not found(status unchanged) 33007 400
Your borrowing amount has exceeded the available amount (If the margin allows, you can adjust the leverage to borrow more) 33008 400
UserID is blank(UserID not provided) 33009 400
you cannot cancel an order during session 2 of call auction(order cancellation not allowed during call auction) 33010 400
no new market data (no market data) 33011 400
order cancellation failed(order cancellation failed) 33012 400
order placement failed(order placement failed) 33013 400
order does not exist( order canceled already. Invalid order number) 33014 400
exceeded maximum limit(exceeded maximum limit during multiple-order placement) 33015 400
margin trading is not open for this token( insufficient balance for order placement) 33016 400
insufficient balance ( margin trading not supported for this pair ) 33017 400
this parameter must be smaller than 1 ( invalid parameter for getting market data) 33018 400
request not supported(margin trading not supported for some exchanges) 33020 400
token and the pair do not match(incorrect token for the token pair during repayment) 33021 400
pair and the order do not match (incorrect token for the order during repayment) 33022 400
you can only place market orders during call auction(you can only place market orders during call auction) 33023 400
trading amount too small(invalid trading amount) 33024 400
base token amount is blank(settings not completed during order placement) 33025 400
transaction completed( cancel limited when the transaction completed) 33026 400
cancelled order or order cancelling(cancel limited when the order is cancelling or cancelled) 33027 400
the decimal places of the trading price exceeded the limit(order endpoint: The decimal places of the trading price exceeded the limit) 33028 400
the decimal places of the trading size exceeded the limit(order endpoint::The decimal places of the trading size exceeded the limit) 33029 400
The current Loan request system is being processed, please try again later 33032 400
You can only place limit order after Call Auction has started 33034 400
This type of order cannot be canceled(This type of order cannot be canceled) 33035 400
Exceeding the limit of entrust order 33036 400
The buy order price should be lower than 130% of the trigger price 33037 400
The sell order price should be higher than 70% of the trigger price 33038 400
The limit of callback rate is 0 < x <= 5% 33039 400
The trigger price of a buy order should be lower than the latest transaction price 33040 400
The trigger price of a sell order should be higher than the latest transaction price 33041 400
The limit of price variance is 0 < x <= 1% 33042 400
The total amount must be larger than 0 33043 400
The average amount should be 1/1000 * total amount <= x <= total amount 33044 400
The price should not be 0, including trigger price, order price, and price limit 33045 400
Price variance should be 0 < x <= 1% 33046 400
Sweep ratio should be 0 < x <= 100% 33047 400
Per order limit: Total amount/1000 < x <= Total amount 33048 400
Total amount should be X > 0 33049 400
Time interval should be 5 <= x <= 120s 33050 400
cancel order number not higher limit: plan and track entrust no more than 10, ice and time entrust no more than 6 33051 400
client_oid or order_id is required 33059 400
Only fill in either parameter client_oid or order_id 33060 400
The leverage ratio is too high. The borrowed position has exceeded the maximum position of this leverage ratio. Please readjust the leverage ratio 33062 400
Leverage multiple is too low, there is insufficient margin in the account, please readjust the leverage ratio 33063 400
The setting of the leverage ratio cannot be less than 2, please readjust the leverage ratio 33064 400
Leverage ratio exceeds maximum leverage ratio, please readjust leverage ratio 33065 400

WebSocket API

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

General

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

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

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

Notes:

All the messages returning from WebSocket API are optimized by Deflate compression. Users are expected to decompress the messages by their own means(Compression and decompression through the inflate algorithm).

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

url:wss://connect.okcoin.jp:443/ws/v3

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

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

Example :

send:

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

response:

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

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

 {"table":"spot/ticker","data":[{"instrument_id":"ETH-JPY","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-JPY"}]}

Unsubscription

Users can cancel one or more channels.

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

send:

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

response:

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

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 APIKey

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

Channel List

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

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

Channels that don't require login

spot/ticker // ticker channel

spot/candle60s // 1mins candlestick

spot/trade // trade information

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

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

Channels that require login

spot/account //User's account information

spot/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
Example Response
{
    "table":"spot/account",
    "data":[
        {
            "balance":"2.215374581132125",
            "available":"1.632774581132125",
            "currency":"JPY",
            "id":"",
            "hold":"0.5826"
        }
    ]
}

User Orders

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

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

spot/order is channel nameLTC-JPY is instrument_id

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

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

Example Response
{
    "table":"spot/order",
    "data":[
        {
            "client_oid":"",
            "filled_notional":"0",
            "filled_size":"0",
            "instrument_id":"LTC-JPY",
            "last_fill_px":"0",
            "last_fill_qty":"0",
            "last_fill_time":"1970-01-01T00:00:00.000Z",
            "margin_trading":"1",
            "notional":"",
            "order_id":"3576398568830976",
            "order_type":"0",
            "price":"5.826",
            "side":"buy",
            "size":"0.1",
            "state":"0",
            "status":"open",
            "timestamp":"2019-09-24T06:45:11.394Z",
            "type":"limit",
            "created_at":"2019-09-24T06:45:11.394Z"
        }
    ]
}

User Algo Orders

Users must login to obtain trading data.

Send – example:

{"op": "subscribe", "args": ["spot/order_algo:LTC-JPY"]}

Of which "spot/order_algo" is the channel name and "LTC-JPY" is the instrument_id

Return Parameters

Parameter Type Description
algo_id String algo ID
order_type String 5:stop order
mode String 1:spot
size String Order size
instrument_id String Token
side String buy or sell
timestamp String Order time
status String Order status: 1. Pending; 2. Effective; 3. Cancelled; 4. Partially effective; 5. Paused; 6. Order failed
cancel_code String 0: Cancel the order overtime
1: The user cancels the order actively
2: The balance is insufficient to cancel the order

Stop Orders

Parameters Type Description
tp_trigger_price String TP trigger price
tp_price String TP order price
tp_trigger_type String 1:limit; currently only limit order allowed
sl_trigger_price String SL trigger price
sl_price String SL order price
sl_trigger_type String 1:limit; currently only limit order allowed
trigger_side String trigger side: 1:TP 2:SL
order_side String order side:1:TP 2:SL, 3:Both
Example Response
{
  "table": "spot/order_algo",
  "data": [
    {
      "algo_id": "7992531393232896",
      "cancel_code": "",
      "created_at": "2021-11-12T04:45:50.632Z",
      "instrument_id": "ETH-JPY",
      "mode": "1",
      "order_side": "3",
      "order_type": "5",
      "side": "sell",
      "size": "0.1",
      "sl_price": "3",
      "sl_trigger_price": "4",
      "sl_trigger_type": "1",
      "status": "1",
      "timestamp": "2021-11-12T04:45:50.632Z",
      "tp_price": "487601",
      "tp_trigger_price": "487600",
      "tp_trigger_type": "1",
      "trigger_side": ""
    }
  ]
}

Public-Ticker

Retrieve the latest price, best bid & offer and 24-hours trading volume of a single contract,data is pushed every 100ms.

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

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

Response
Parameter Type Description
instrument_id String Contract ID, e.g., BTC-JPY-170310
last String Last traded price
last_qty String Last traded price amount
best_bid String Best bid price
best_bid_size String Best bid price amount
best_ask String Best ask price
best_ask_size String Best bid price amount
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
Example Response
{
    "table":"spot/ticker",
    "data":[
        {
            "instrument_id":"ETH-JPY",
            "last":"146.24",
            "last_qty":"0.082483",
            "best_bid":"146.24",
            "best_bid_size":"0.006822",
            "best_ask":"146.25",
            "best_ask_size":"80.541709",
            "open_24h":"147.17",
            "high_24h":"147.48",
            "low_24h":"143.88",
            "base_volume_24h":"117387.58",
            "quote_volume_24h":"17159427.21",
            "timestamp":"2019-12-11T02:31:40.436Z"
        }
    ]
}

Public-Candlesticks

Retrieve the candlestick data,data is pushed every 500ms.

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

spot/candle60s is channel name,ETH-JPY 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
Example Response
{
    "table":"spot/candle60s",
    "data":[
        {
            "candle":[
                "2019-04-16T10:49:00.000Z",
                "162.03",
                "162.04",
                "161.96",
                "161.98",
                "336.452694"
            ],
            "instrument_id":"ETH-JPY"
        }
    ]
}

Public-Trade

Get the filled orders data,it will be pushed when there is transaction data.

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

spot/trade is the channel nameETH-JPY 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-JPY",
        "price": "162.12",
        "side": "buy",
        "size": "11.085",
        "timestamp": "2019-05-06T06:51:24.389Z",
        "trade_id": "1210447366"
    }]
}

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

spot/depth5 is channel nameETH-JPY is instrument_id

response parameters
Parameter Type Description
asks List<String> Sell side depth
bids List<String> Buy side depth
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.

Example Response

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

Public-Depth400

After subscription, 400 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-JPY"]}

spot/depth is channel nameETH-JPY is trading pair

Response
Parameter Types Description
asks List<String> Sell side depth
bids List<String> Buy side depth
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-JPY",
            "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-JPY",
            "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
        }
    ]
}

error code

error message format:

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

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

FAQ

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

There are no limitations.

2、How did Http status code 429 happen?

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

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

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

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

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

5、How many APIKeys can I apply for an account?

10.

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

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

7、What is the OKCoinJapan's API visit frequency limit based on?

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

8、Why did my API timeout?

Your network has timeout. Please check your network and use the Tokyo AWS server instead.

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

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

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

Yes, in order to make your account more secure, it’s mandatory to enter your IP address.

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

The order unit is 1, or multiples of 1.

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

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

Questions And Feedback

If you have any questions or suggestions regarding our API, you are more than welcome to give us feedback via this link: (please indicate API v3). We will respond as soon as possible.