Skip to content

Latest commit

 

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

Exchange-official-API-docs

Official Documentation for the Exchange APIs and Streams


Introduction

Welcome to the Exchange API documentation for developers. Here you can find a breakdown of the API endpoints and how to use them.


General Information

Endpoint

The root URL for API access: https://api.crypto.com

The root URL for WebSocket access wss://ws.crypto.com/kline-api/ws

All requests must be made via HTTPS protocol. For POST and DELETE requests, the Content-Type in the request must be application/x-www-form-urlencoded.

Generate the API Key

Before sending any requests, you'll need to generate a new API key. This can be done via the web interface in【User Center】-【API】. After generating the key, there are two things you need to record:

  • API Key
  • Secret Key

API Key and Secret are randomly generated by the system and can not be modified.

You can optionally specify a whitelist of IP addresses when generating the API Key. If specified, the API can only be used from the whitelisted IP addresses.

Request Signing

Some endpoints are only accessible by authenticated users. The authentication is based on a pair of API Key and SHA-256 of the HTTP request parameter along with the API Secret Key (and should never explicitly include the API Secret Key in your request).

The algorithm for generating the SHA-256 signature is as follows:

  1. Sort the HTTP request parameter names in ascending order.

  2. For each parameter name, if the corresponding parameter value is not null/empty, append namevalue (without any other separators) to the buffer.

  3. Use SHA-256 to hash the buffer string.

Example:

api_key = mZhlB7z8dDXXdL74uwoIoqAtPQSpY6Mk
time = 1573789761928
secret_key = qg7fPyVj43tvfWBX83pSB7s8ZajHD1ve

sign=sha256("api_key" + "mZhlB7z8dDXXdL74uwoIoqAtPQSpY6Mk" + "time" + "1573789761928" + "qg7fPyVj43tvfWBX83pSB7s8ZajHD1ve")

Response Status Code

HTTP Error Code

  • 400 Bad Request – Invalid request format

  • 401 Unauthorized – Invalid API Key

  • 403 Forbidden – You do not have access to the requested resource

  • 404 Not Found - Server could not find the API endpoint

  • 429 Too Many Requests - A rate limit has been exceeded. The following table shows rate limits:

    API Group Limits Group by
    Market APIs up to 10 requests per second IP
    User APIs up to 10 requests per second user_id
  • 499 Request rejected due to an input validation error

  • 500 Internal Server Error

  • 503 Server Busy - The server is temporarily too busy, please retry later

Unless otherwise specified, all responses are a JSON object with the following fields. The user can observe the code and msg fields for more detailed error information.

{
    code: 0, // zero means ok, non-zero means err
    msg: "suc", // "suc" means successful, if code is non-zero then this contains the error message
    data: ... // the response data, if any
}

Market Symbols

Many APIs requires a symbol field which is the name of a market (or the name of the Trading Pair). The following table has a few examples of symbols:

Currency Name xxx-cro xxx-btc xxx-usdt
cro - crobtc crousdt
btc btccro - btcusdt
eth ethcro ethbtc ethusdt
xrp xrpcro xrpbtc xrpusdt

API Reference

There are three groups of API endpoints:

API Group Request Signing Description
Market APIs Not needed Market public data such as ticker, order book, etc...
User APIs Required User account activities such as checking account balance, create order, cancel order, etc...
WebSocket API Not needed Market public data such as ticker, order book, etc...

Users are recommended to use WebSocket API instead of Market API because the former is faster and more efficient.

An overview of all the available API endpoints are listed as follows:

Group Path Method Allowed Parameters Action
Market /v1/symbols GET (null) List all available market symbols
Market /v1/tickers GET (null) Get tickers in all available markets
Market /v1/ticker GET symbol Get ticker for a particular market
Market /v1/klines GET symbol, period Get k-line data over a specified period
Market /v1/trades GET symbol Get last 200 trades in a specified market
Market /v1/ticker/price GET (null) Get latest execution price for all markets
Market /v1/depth GET symbol, type Get the order book for a particular market
User /v1/account POST +3 List all account balance of user
User /v1/order POST side, type, volume, price, fee_is_user_exchange_coin +3 Create an order
User /v1/showOrder POST order_id +3 Get order detail
User /v1/order DELETE order_id +3 Cancel an order
User /v1/cancelAllOrders POST symbol +3 Cancel all orders in a particular market
User /v1/openOrders POST symbol, pageSize, page +3 List all open orders in a particular market
User /v1/allOrders POST symbol, pageSize, page, startDate, endDate +3 List all orders in a particular market
User /v1/myTrades POST symbol, pageSize, page, startDate, endDate, sort +3 List all executed orders

Note: For User API calls, there are three more parameters in each requests -- api_key, time and sign.

Group Request or Subscribe Channel Description
WS req review Request current tickers in all available markets
WS sub market_${symbol}_ticker Subscribe new tickers for a particular market
WS req market_${symbol}_kline_1min
market_${symbol}_kline_5min
market_${symbol}_kline_15min
market_${symbol}_kline_30min
market_${symbol}_kline_60min
market_${symbol}_kline_1day
market_${symbol}_kline_1week
market_${symbol}_kline_1month
Request history k-line data over a specified period
WS sub market_${symbol}_kline_1min
market_${symbol}_kline_5min
market_${symbol}_kline_15min
market_${symbol}_kline_30min
market_${symbol}_kline_60min
market_${symbol}_kline_1day
market_${symbol}_kline_1week
market_${symbol}_kline_1month
Subscribe new k-line data over a specified period
WS req market_${symbol}_trade_ticker Request last 200 trades in a specified market
WS sub market_${symbol}_trade_ticker Subscribe: new trades in a specified market
WS sub market_${symbol}_depth_step[0-2] Subscribe: - order book for a particular market (Incremental update)
WS sub market_${symbol}_depth_step[0-2] Subscribe: - order book for a particular market (Full update)

Market API

List all available market symbols

  1. Endpoint URL: /v1/symbols
  2. Method: GET
  3. Description: queries all transaction pairs and precision supported by the system.
  4. This is a public interface, request signature is not needed
  5. Request Parameter: no parameter is allowed
  6. Response Content-Type: application/json
  7. Response JSON fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
    "code": "0",
    "msg": "suc",
    "data": [
        {
            "symbol": "ethbtc", // Transaction pairs
            "count_coin": "btc", // Money of Account
            "amount_precision": 3, // Quantitative precision digits (0 is a single digit)
            "base_coin": "eth", // Base currency
            "price_precision": 8 // Price Precision Number (0 is a single digit) 
        },
        {
            "symbol": "ltcbtc",
            "count_coin": "btc",
            "amount_precision": 2,
            "base_coin": "ltc",
            "price_precision": 8
        },
        {
            "symbol": "etcbtc",
            "count_coin": "btc",
            "amount_precision": 2,
            "base_coin": "etc",
            "price_precision": 8
        }
    ]
}

Get tickers in all available markets

  1. Endpoint URL: /v1/tickers
  2. Method: GET
  3. Description: gets all trading pairs quotes on the market.
  4. This is a public interface, request signature is not needed
  5. Request Parameter: no parameter is allowed
  6. Response Content-Type: application/json
  7. Response JSON fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
   "date": 1534335607859, // Server time 
   "ticker": [
     {
       "symbol": "btcusdt", // Transaction pairs 
       "high": "9744.47", // Highest price in the last 24 hours
       "vol": "0.0251263", // Trading volume in the last 24 hours
       "last": 9744.2500000000000000 , // Latest transaction price
       "low": "9744.25", // Lowest price in the last 24 hours
       "buy": 9744.25, // Current buy price
       "sell": 9744.47, // Current sell price
       "change": "-0.0000225769", // 
       "rose": "-0.0000225769" // ups or downs
     },
     {
       "symbol": "ethusdt",
       "high": 535.96,
       "vol": 6366.8591,
       "last": 20,
       "low": 279.57,
       "rose": -0.44564773
     },
     {
       "symbol": "ethbtc",
       "high": 1,
       "vol": 281261,
       "last": 0.1,
       "low": 0.044039,
       "buy": "0.044049",
       "sell": "0.044049",
       "rose": -0.00022701
     }
   ]
 }

Get ticker for a particular market

  1. Endpoint URL: /v1/ticker
  2. Method: GET
  3. Description: gets the current market quotes.
  4. This is a public interface, request signature is not needed
  5. Request Parameters: see below
Request Parameter Required Description
symbol Yes Market mark, btcusdt, See below for details
  1. Response Content-Type: application/json
  2. Response JSON fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
    "high": 1, //Maximum value
    "vol": 10232.26315789, //Trading volume
    "last": 173.60263169, //Latest Transaction Price
    "low": 0.01, //Minimum value
    "buy": "0.01000000", //Buy one price
    "sell": "1.12345680", //Selling price
    "rose": -0.44564773, //Ups and downs
    "time": 1514448473626
}

Get k-line data over a specified period

  1. Endpoint URL: /v1/klines
  2. Method: GET
  3. Description: gets K-line data.
  4. This is a public interface, request signature is not needed
  5. Request Parameter: no parameter is allowed
Get Parameter Required Description
symbol Yes Market mark, bchbtc, See below for details
period Yes Given in minutes. Possible values are [1, 5, 15, 30, 60, 1440, 10080, 43200]
which corresponds to 1min, 5min, 15min, 30min, 1hour, 1day, 1week, 1month.
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
[
        [
            1514445780,  //time stamp
            1.12,        //Opening price
            1.12,        //Highest
            1.12,        //minimum
            1.12,        //Closing price
            0            //volume

        ],
        [
            1514445840,
            1.12,
            1.12,
            1.12,
            1.12,
            0
        ],
        [
            1514445900,
            1.12,
            1.12,
            1.12,
            1.12,
            0
        ]
]

Get last 200 trades in a specified market

  1. Endpoint URL: /v1/trades
  2. Method: GET
  3. Description: obtains market transaction records.
  4. This is a public interface, request signature is not needed
  5. Request Parameter: see below
GET Parameter Required Description
symbol Yes Market mark, bchbtc, See below for details
  1. Response Content-Type: application/json
  2. Response JSON fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
    "code": "0",
    "msg": "suc",
    "data": [
        {
            "amount": 0.0010000000000000,
            "price": 9744.2500000000000000,
            "ctime": 1572404045000,
            "id": 6303,
            "type": "sell"
        },
        {
            "amount": 0.0000010200000000,
            "price": 9744.4700000000000000,
            "ctime": 1572404025000,
            "id": 6302,
            "type": "buy"
        },
        {
            "amount": 0.0010000000000000,
            "price": 9744.2500000000000000,
            "ctime": 1572403679000,
            "id": 6301,
            "type": "sell"
        },
        {
            "amount": 0.0010000000000000,
            "price": 9744.2500000000000000,
            "ctime": 1572403679000,
            "id": 6300,
            "type": "sell"
        }
    ]
}

Get latest execution price for all markets

  1. Endpoint URL: /v1/ticker/price
  2. Method: GET
  3. Description: gets the latest transaction price of each pair of currencies.
  4. This is a public interface, request signature is not needed
  5. Request Parameter: no parameter is allowed
  6. Response Content-Type: application/json
  7. Response JSON Fields: see below
Response JSON Field Example Description
code 0
msg "suc" Success or failure
data {"btcusdt":15000,"ethusdt":800}

Get the order book for a particular market

  1. Endpoint URL: /v1/depth
  2. Method: GET
  3. Description: gets the list of orders from buyers and sellers for the market
  4. This is a public interface, request signature is not needed
  5. Request Parameter: see below
Get Parameter Required Description
symbol Yes Market mark, ethbtc, See below for details
type Yes The depth type -- options: step0, step1, step2 (Merger depth0-2). step0time is the highest accuracy
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
        "tick": {
            "asks": [
                [
                    9745,
                    0.57373498
                ],
                [
                    9748,
                    0.25
                ],
            ],
            "bids": [
                [
                    9744,
                    102.45305246
                ],
                [
                    9654,
                    1.831
                ],
            ],
            "time": null
        }
}

User API

List all account balance of user

  1. Endpoint URL: /v1/account
  2. Method: POST
  3. Description: display the balance of user’s assets across all accounts
  4. Request Parameter: see below
POST Parameter Required Description
api_key Yes API key
time Yes Time stamp
sign Yes sha256 signature
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
  "total_asset": 432323.23, // user total assets (estimated in BTC)
  "coin_list": [
    {
      "normal": 32323.233, // usable balance
      "locked": 32323.233, // locked balance, e.g. locked in an active, non-executed order
      "btcValuatin": 112.33, // value equal to BTC
      "coin": "btc" // asset type
    },
    {
      "normal": 32323.233,
      "locked": 32323.233,
      "btcValuatin": 112.33,
      "coin": "ltc"
    },
    {
      "normal": 32323.233,
      "locked": 32323.233,
      "btcValuatin": 112.33,
      "coin": "bch"
    }
  ]
}

Create an order

  1. Endpoint URL: /v1/order
  2. Method: POST
  3. Description: creates a buy or sell order on exchange
  4. Request Parameter: see below
POST parameter Required Description
side Yes BUY, SELL
type Yes Type of list: 1 for limit order (user sets a price), 2 for market order (best available price)
volume Yes Purchase quantity (Polysemy, multiplexing fields)
type=1 represents the quantity of sales and purchases
type=2: buy means the total price, Selling represents the total number.
Trading restrictions user/me-User information.
price No Authorized unit price. If type=2 then no need for this parameter.
symbol Yes Market symbol "ethbtc"
fee_is_user_exchange_coin No (Redundant fields are ignored) this parameter indicates whether to use the platform currency to pay the handling fee, 0 means no, 1 means yes. 0 when the exchange has the platform currency.
api_key Yes API key
time Yes Time stamp
sign Yes sha256 signature
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
    "order_id": 34343 // the newly created order_id
}

Get order detail

  1. Endpoint URL: /v1/showOrder
  2. Method: POST
  3. Description: obtain order details.
  4. Request Parameter: see below
POST Parameter Required Description
order_id Yes Order ID
symbol Yes Market symbol "ethbtc", See below for details
api_key Yes API key
time Yes Time stamp
sign Yes sha256 signature
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
    "trade_list": [
        {
            "volume": "0.00100000",
            "feeCoin": "USDT",
            "price": "9744.25000000",
            "fee": "0.00000000",
            "ctime": 1571971998000,
            "deal_price": "9.74425000",
            "id": 6224,
            "type": "SELL"
        }
    ],
    "order_info": {
        "id": 8140,
        "side": "SELL",
        "total_price": "8.00000000",
        "fee": 0E-8,
        "created_at": 1571971998681,
        "deal_price": 9.7442500000000000,
        "avg_price": "9744.25000000",
        "countCoin": "USDT",
        "source": 3,
        "type": 1,
        "side_msg": "SELL",
        "volume": "0.00100000",
        "price": "8000.00000000",
        "source_msg": "API",
        "status_msg": "Completely Filled",
        "deal_volume": "0.00100000",
        "fee_coin": "USDT",
        "remain_volume": "0.00000000",
        "baseCoin": "BTC",
        "tradeList": [
            {
                "volume": "0.00100000",
                "feeCoin": "USDT",
                "price": "9744.25000000",
                "fee": "0.00000000",
                "ctime": 1571971998000,
                "deal_price": "9.74425000",
                "id": 6224,
                "type": "SELL"
            }
        ],
        "status": 2
    }
}

Cancel an order

  1. Endpoint URL: /v1/order
  2. Method: DELETE
  3. Description: cancellation of the order.
  4. Request Parameter: see below
DELETE body Parameter Required Description
order_id Yes OrderID
symbol Yes Market symbol "ethbtc". See below for details
api_key Yes API key
time Yes Time stamp
sign Yes sha256 signature
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data (null)

Cancel all orders in a particular market

  1. Endpoint URL: /v1/cancelAllOrders
  2. Method: POST
  3. Description: cancellation of all orders according to currency pair (Up to 2,000 cancellations).
  4. Request Parameter: see below
POST Parameter Required Description
symbol Yes Market symbol "ethbtc", See below for details
api_key Yes API key
time Yes Time stamp
sign Yes sha256 signature
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data (null)

List all open orders in a particular market

  1. Endpoint URL: /v1/openOrders
  2. Method: POST
  3. Description: get the current pending orders
  4. Request Parameter: see below
POST Parameter Required Description
symbol Yes Market symbol "btcusdt", See below for details
pageSize No Page size
page No Page number
api_key Yes API key
time Yes Time stamp
sign Yes sha256 signature
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
    "count":10,
    "resultList":[

        {
            "side": "BUY",
            "total_price": "9.00000000",
            "fee": 0E-8,
            "created_at": 1571971994609,
            "deal_price": 0E-16,
            "avg_price": "0.00000000",
            "countCoin": "USDT",
            "source": 3,
            "type": 1,
            "side_msg": "BUY",
            "volume": "0.00100000",
            "price": "9000.00000000",
            "source_msg": "API",
            "status_msg": "Unsettled",
            "deal_volume": "0.00000000",
            "fee_coin": "BTC",
            "id": 8139,
            "remain_volume": "0.00100000",
            "baseCoin": "BTC",
            // 0: INIT, "Initial order"
            // 1: NEW, "New order, Unfinished business enters the market"
            // 2: FILLED, "Full deal"
            // 3: PART_FILLED, "Partial transaction"
            // 4: CANCELED, "Order cancelled"
            // 5: PENDING_CANCEL, "Order will be cancelled"
            // 6. EXPIRED(, "Abnormal order"
            "status": 1
        },
        {
            "side": "BUY",
            "total_price": "9.00000000",
            "fee": 0E-8,
            "created_at": 1571880796540,
            "deal_price": 0E-16,
            "avg_price": "0.00000000",
            "countCoin": "USDT",
            "source": 3,
            "type": 1,
            "side_msg": "BUY",
            "volume": "0.00100000",
            "price": "9000.00000000",
            "source_msg": "API",
            "status_msg": "Unsettled",
            "deal_volume": "0.00000000",
            "fee_coin": "BTC",
            "id": 8081,
            "remain_volume": "0.00100000",
            "baseCoin": "BTC",
            "status": 1
        }
    ]
}

List all orders in a particular market

  1. Endpoint URL: /v1/allOrders

  2. Method: POST

  3. Description: acquire full list of orders (including executed, pending, cancelled orders)

  4. Request Parameter: see below

POST Parameter Required Description
symbol Yes Market symbol "btcusdt", See below for details
startDate No (Added) Start time, accurate to seconds "yyyy-MM-dd mm:hh:ss"
endDate No (Added) End time, accurate to seconds "yyyy-MM-dd mm:hh:ss"
pageSize No Page size
page No Page number
api_key Yes API key
time Yes Time stamp
sign Yes sha256 signature
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
    "count":10,
    "orderList":[
        {
            "side": "BUY",
            "total_price": "9.74447000",
            "fee": 0E-8,
            "created_at": 1572235997622,
            "deal_price": 9.7444700000000000,
            "avg_price": "9744.47000000",
            "countCoin": "USDT",
            "source": 1,
            "type": 1,
            "side_msg": "BUY",
            "volume": "0.00100000",
            "price": "9744.47000000",
            "source_msg": "WEB",
            "status_msg": "Completely Filled",
            "deal_volume": "0.00100000",
            "fee_coin": "BTC",
            "id": 8145,
            "remain_volume": "0.00000000",
            "baseCoin": "BTC",
            "status": 2
        },
        {
            "side": "SELL",
            "total_price": "8.00000000",
            "fee": 0E-8,
            "created_at": 1571971998681,
            "deal_price": 9.7442500000000000,
            "avg_price": "9744.25000000",
            "countCoin": "USDT",
            "source": 3,
            "type": 1,
            "side_msg": "SELL",
            "volume": "0.00100000",
            "price": "8000.00000000",
            "source_msg": "API",
            "status_msg": "Completely Filled",
            "deal_volume": "0.00100000",
            "fee_coin": "USDT",
            "id": 8140,
            "remain_volume": "0.00000000",
            "baseCoin": "BTC",
            "status": 2
        },
    ]
}

List all executed orders

  1. Endpoint URL: /v1/myTrades
  2. Method: POST
  3. Description: get all records of executed orders
  4. Request Parameter: see below
POST Parameter Required Description
symbol Yes Market symbol "btcusdt", See below for details
startDate No (Added) Start time, accurate to seconds "yyyy-MM-dd HH:mm:ss"
endDate No (Added) End time, accurate to seconds "yyyy-MM-dd HH:mm:ss"
pageSize No Page size
page No Page number
api_key Yes API key
time Yes Time stamp
sort No 1 gives reverse order
sign Yes sha256 signature
  1. Response Content-Type: application/json
  2. Response JSON Fields: see below
Response JSON Field Example Description
code 0 Return code, 0 for success, non-zero for failure
msg "suc" Success or the error message
data shown below
{
    "count":100,
    "resultList":[
        {
            "volume": "0.00100000",
            "side": "BUY",
            "feeCoin": "BTC",
            "price": "9744.47000000",
            "fee": "0.00000000",
            "ctime": 1572235997000,
            "deal_price": "9.74",
            "id": 6227,
            "type": "BUY",
            "bid_id": 8145,
            "bid_user_id": 10106
        },
        {
            "volume": "0.001",
            "side": "SELL",
            "feeCoin": "USDT",
            "ask_user_id": 10106,
            "price": "9744.25000000",
            "fee": "0.00000000",
            "ctime": 1571971998000,
            "deal_price": "9.74",
            "id": 6224,
            "type": "SELL",
            "ask_id": 8140
        }
    ]
}

WebSocket API

Request current tickers in all available markets

  • Request mode:
{"event":"req","params":{"channel":"review"}}
  • Example response:
{
   event_rep: "rep",
   channel: "review",
   data: {
          bchbtc:  {amount: "115.968833484"close: "0.07956"high: "0.086323"low: "0.079251"open: "0.086323"rose: "-0.07834528"vol: "1393.247"}
          bchusdt: {amount: "416316.164145661", close: "513.56", high: "556.42", low: "510.85", open: "555.71", ...}
          btcusdt: {amount: "999341.34124", close: "6450.18", high: "6486.39", low: "6359.63", open: "6435.79", ...}
   }
}

Subscribe to new tickers for a particular market

  • Sample request:
{"event":"sub","params":{"channel":"market_${symbol}_ticker","cb_id":"custom"}}
  • Return subscription status once:
{
    "event_rep":"subed",
    "channel":"market_${symbol}_ticker",
    "cb_id":"Please Return by the Way You Came",
    "ts":1506584998239,
    "status":"ok",
    "lower_frame":"0" // lower_frame: 0 No coin pair off the shelf,  1 Coin pair
}
  • Continue to return subscription messages:
{
    "channel":"market_${symbol}_ticker", //Subscription transactions versus market${symbol}Express btckrw etc.
    "ts":1506584998239, //d time
    "tick":{
        "id":1506584998, //Redundancy, no practical significance, timestamp
        "amount":123.1221, //A turnover
        "vol":1212.12211, //Trading volume
        "open":2233.22, //Opening price
        "close":1221.11, //Closing price
        "high":22322.22, //Highest price
        "low":2321.22, //Minimum price
        "rose":-0.2922, //Gain
        "ts":1506584998239, //Data generation time
        "lower_frame":"0"
    }
}

Request k-line data history over a specified period

  • Increase request parameters endIdx and pageSize (Up to 300, default 300 data). If endIdx is empty then the last 300 entries are returned.

  • Sample request:

{
    "event":"req",
    "params":{
        "channel":"market_${symbol}_kline_[1min/5min/15min/30min/60min/1day/1week/1month]",
        "cb_id":"custom",
        "since":"1506602880"
    }
}
  • Return data:
{
    "event_rep":"rep","channel":"market_${symbol}_kline_[1min/5min/15min/30min/60min/1day/1week/1month]","cb_id":"Please Return by the Way You Came",
    "since":"1506602880",
    "ts":1506584998239, //Request time
    "data":[ //300 article
        {
            "id":1506602880, //Time scale starting value
            "amount":123.1221, //A turnover
            "vol":1212.12211, //Trading volume
            "open":2233.22, //Opening price
            "close":1221.11, //Closing price
            "high":22322.22, //Highest price
            "low":2321.22 //Minimum price
        },
        {
            "id":1506602880, //Time scale starting value
            "amount":123.1221, //A turnover
            "vol":1212.12211, //Trading volume
            "open":2233.22, //Opening price
            "close":1221.11, //Closing price
            "high":22322.22, //Highest price
            "low":2321.22 //Minimum price
        }
    ]
}

Subscribe to new k-line data over a specified period

  • Sample request:
{
    "event":"sub",
    "params":{
        "channel":"market_${symbol}_kline_[1min/5min/15min/30min/60min/1day/1week/1month]",
        "cb_id":"custom"
    }
}
  • Return subscription status once:
{
    "event_rep":"subed",
    "channel":"market_${symbol}_kline_[1min/5min/15min/30min/60min/1day/1week/1month]",
    "cb_id":"Please Return by the Way You Came","ts":1506584998239,"status":"ok"
}
  • Continue to return subscription messages:
{
    "channel":"market_${symbol}_kline_[1min/5min/15min/30min/60min/1day/1week/1month]", //Subscription transactions versus market${symbol}Expressbtckrwetc.

    "ts":1506584998239, //Request time
    "tick":{
        "id":1506602880, //Time scale starting value
        "amount":123.1221, //A turnover
        "vol":1212.12211, //Trading volume
        "open":2233.22, //Opening price
        "close":1221.11, //Closing price
        "high":22322.22, //Highest price
        "low":2321.22 //Minimum price
    }
}

Request last 200 trades in a specified market

  • Sample request:
{
    "event":"req",
    "params":{
        "channel":"market_${symbol}_trade_ticker","cb_id":"custom",
        "top":200
    }
}
  • Direct response of transaction information:
{
    "event_rep":"rep",
    "channel":"market_${symbol}_trade_ticker",
    "cb_id":"Please Return by the Way You Came","ts":1506584998239,
    "status":"ok",
    "top":200, //Maximum support 200
    "data":[
        {
            "id":12121, //Transaction ID
            "side":"buy", //Direction of businessbuy,sell
            "price":32.233, //Unit Price
            "vol":232, //Number
            "amount":323, //Total
            "ts":1506584998239 //Data generation time
        },
        {
            "id":12120, //Transaction ID
            "side":"buy", //Direction of business buy,sell
            "price":32.233, //Unit Price
            "vol":232, //Number
            "amount":323, //Total
            "ts":1506584998239, //Data generation time
            "ds":'2017-09-10 23:12:21'
        }
    ]
}

Subscribe to new trades in a specified market

  • Sample request:
{
    "event":"sub",
    "params":{
        "channel":"market_${symbol}_trade_ticker","cb_id":"custom"
    }
}
  • Return subscription status once:
{
    "event_rep":"subed",
    "channel":"market_${symbol}_trade_ticker",
    "cb_id":"Please Return by the Way You Came",
    "ts":1506584998239,
    "status":"ok"
}
  • Continue to return subscription messages:
{
    "channel":"market_${symbol}_trade_ticker", //Subscription transactions versus market${symbol}Expressbtckrwetc.
    "ts":1506584998239, //Request time
    "tick":{
        "id":12121, //dataThe biggest deal ID
        "ts":1506584998239, //dataThe biggest deal
        "data":[
            {
                "id":12121, //transaction ID
                "side":"buy", //Direction of business buy,sell
                "price":32.233, //Unit Price
                "vol":232, //Number
                "amount":323, //Total
                "ts":1506584998239, //Data generation time
                "ds":'2017-09-10 23:12:21'
            },
            {
                "id":12120, //Transaction ID
                "side":"buy", //Direction of business buy,sell
                "price":32.233, //Unit Price
                "vol":232, //Number
                "amount":323, //Total
                "ts":1506584998239, //Data generation time
                "ds":'2017-09-10 23:12:21'
            }
        ]
    }
}

Subscribe to order book for a particular market (Incremental update)

  • Sample request:
{
    "event":"sub",
    "params":{
        "channel":"market_${symbol}_depth_step[0-2]","cb_id":"custom",
        "asks":150,
        "bids":150
    }
}
  • Return to subscription status once:
{
    "event_rep":"subed",
    "channel":"market_${symbol}_depth_step[0-2]",
    "cb_id":"Please Return by the Way You Came",
    "asks":150,
    "bids":150,
    "ts":1506584998239,"
    status":"ok"
}
  • Note: The first successful subscription will immediately return the full amount of data and the server will regularly push the full amount of data to the front-end to avoid problems.

  • Full quantity: the front end directly replaces the original disk outlet

{
    "channel":"market_${symbol}_depth_step[0-2]", //${symbol}Expressbtckrwetc.,Depth has three dimensions, 0, 1, 2
    "ts":1506584998239, //Request time
    "tick":{
        "asks":[ //Selling
            [22112.22,0.9332],
            [22112.21,0.2],
        ],
        "buys":[ //Bid
            [22111.22,0.9332],
            [22111.21,0.2],
        ]
    }
}
  • Note: The front end for incremental inventory information only needs to replace the quantity corresponding to the price.

  • Direct addition of new price

{
    "channel":"market_${symbol}_depth_step[0-2]", // ${symbol}Expressbtckrwetc.,Depth has 3 dimensions, 0, 1, 2
    "ts":1506584998239, //Request time
    "tick":{
        "side": "asks", //Trading Direction  asks: Selling buys: Bid
        "price" : 133.55, //A price segment corresponding to the opening
        "volume" : 44.22 //Quantity corresponding to price segment
    }
}

Subscribe to order book for a particular market (Full update)

  • Sample request:
{
    "event":"sub",
    "params":{
        "channel":"market_${symbol}_depth_step[0-2]",
        "cb_id":"custom",
        "asks":150,
        "bids":150
    }
}
  • Return subscription status once:
{
    "event_rep":"subed",
    "channel":"market_${symbol}_depth_step[0-2]",
    "cb_id":"Please Return by the Way You Came",
    "asks":150,
    "bids":150,
    "ts":1506584998239,
    "status":"ok"
}
  • Continue to return subscription messages:
{
    "channel":"market_${symbol}_depth_step[0-2]", //${symbol}Represents btckrw, etc.,Depth has 3 dimensions, 0, 1, 2
    "ts":1506584998239, //Request time
    "tick":{
        "asks":[ //Selling
            [22112.22,0.9332],
            [22112.21,0.2]
        ],
        "buys":[ //Bid
            [22111.22,0.9332],
            [22111.21,0.2]
        ]
    }
}

ws-api Demo (java)

package test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.java_websocket.client.DefaultSSLWebSocketClientFactory;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;

/**
 * @author Squid DateTime:November 22, 2018, 9:25:20 PM 
 * Suggested use websocket client Edition 
 * <dependency> 
 * <groupId>org.java-websocket</groupId> 
 * <artifactId>Java-WebSocket</artifactId> 
 * <version>1.3.0</version> 
 * </dependency> 
 *
 */
public class WsTest {

    public static void main(String[] args) {
        try {
            //wsurl 
            String url = "wss://ws.crypto.com/kline-api/ws";
            //Historical data request parameters 
            String reqParam = "{"event":"req","params":{"channel":"market_btcusdt_trade_ticker","cb_id":"btcusdt","top":150}}";
            //Subscription parameters 
            String subParam = "{"event":"sub","params":{"channel":"market_btcusdt_trade_ticker","cb_id":"btcusdt","top":150}}";

            //Initialization request history data 
            WebSocketUtils wsc = WebSocketUtils.executeWebSocket(url, reqParam);

            //Subscribe to real-time data 
            wsc.send(subParam);

            //Thread does not end, waiting for new messages, www.crypto.com Generally, a new deal will return in about a minute
            while (true) {
                Thread.sleep(1000);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class WebSocketUtils extends WebSocketClient {
        private static WebSocketUtils wsclient = null;
        private String msg = "";

        public WebSocketUtils(URI serverURI) {
            super(serverURI);
        }

        public WebSocketUtils(URI serverUri, Draft draft) {
            super(serverUri, draft);
        }

        public WebSocketUtils(URI serverUri, Map<String, String> headers, int connecttimeout) {
            super(serverUri, new Draft_17(), headers, connecttimeout);
        }

        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            System.out.println("Links have been established");

        }

        @Override
        public void onMessage(String s) {
            System.out.println("Receive a string message");
        }

        @Override
        public void onClose(int i, String s, boolean b) {
            System.out.println("Link closed");
        }

        @Override
        public void onError(Exception e) {
            System.out.println("Wrong report");
        }

        @Override
        public void onMessage(ByteBuffer socketBuffer) {
            try {
                String marketStr = byteBufferToString(socketBuffer);
                String market = uncompress(marketStr).toLowerCase();
                if (market.contains("ping")) {
                    System.out.println("Receive messageping: "+market);
                    String tmp = market.replace("ping", "pong");
                    wsclient.send(market.replace("ping", "pong"));
                } else {
                    msg = market;
                    System.out.println("Receive message: "+msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public static Map<String, String> getWebSocketHeaders() throws IOException {
            Map<String, String> headers = new HashMap<String, String>();
            return headers;
        }

        private static void trustAllHosts(WebSocketUtils appClient) {
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[] {};
                }

                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
            } };

            try {
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                appClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sc));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static WebSocketUtils executeWebSocket(String url,String sendMsg) throws Exception {
            wsclient = new WebSocketUtils(new URI(url), getWebSocketHeaders(), 1000);
            trustAllHosts(wsclient);
            wsclient.connectBlocking();
            wsclient.send(sendMsg);
            return wsclient;
        }

        // buffer turn String 
        public String byteBufferToString(ByteBuffer buffer) {
            CharBuffer charBuffer = null;
            try {
                Charset charset = Charset.forName("ISO-8859-1");
                CharsetDecoder decoder = charset.newDecoder();
                charBuffer = decoder.decode(buffer);
                buffer.flip();
                return charBuffer.toString();
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }

        // decompression 
        public String uncompress(String str) throws IOException {
            if (str == null || str.length() == 0) {
                return str;
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString();
        }

    }
}

About

Offical Crypto.com Exchange API Document

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors