Introduction
GMO Coin provides a Public API that does not require authentication and a Private API that requires authentication using an API key.
- All requests from the client to the API are HTTPS communication.
- Only Spot and Margin trading are supported.
//Request examples are tested with Node.js v21.0.0.
#Request examples are tested with Python 3.12.0.
//Request examples are tested with Go 1.21.3.
#Request examples are tested with Ruby 3.2.2.
//Request examples are tested with Kotlin 1.9.10.
<?php
//Request examples are tested with PHP 8.2.11.
//Request examples are tested with rustc 1.73.0.
--Request examples are tested with ghc 9.8.1.
//Request examples are tested with .NET Framework 8.0.1.
//Request examples are tested with Swift 5.8.1.
Endpoint
- Public API:
https://api.coin.z.com/public - Public WebSocket API:
wss://api.coin.z.com/ws/public - Private API:
https://api.coin.z.com/private - Private WebSocket API:
wss://api.coin.z.com/ws/private
Version
Current version: v1
API Limiting
API usage Limits are below:
Public WebSocket API Limiting
- 1 request (subscribe/unsubscribe) per second from each IP address for Public WebSocket API.
Private API Limiting
- Current week's private API limits are based on the trading volume from the previous week.
- Private API's limits are subject to change without prior notice.
- If you enable the IP restriction feature on the membership site, it will deny any API calling that comes from a non-registered IP.
- Only features that are specified on the membership site when API key was issued can be called.
- Permissions for the CryptoCurrency withdrawal APIs are separated for each API. These APIs can be called only with an API key that has the permission. See Create API key for details.
| Level | Volume | API limits | Description |
|---|---|---|---|
| Tier 1 | Last week trading volume < 1,000,000,000yen | 20req/s | Maximum 20 GET requests per second. Maximum 20 POST requests per second. |
| Tier 2 | 1,000,000,000yen <= Last week trading volume < 2,000,000,000yen | 30req/s | Maximum 30 GET requests per second. Maximum 30 POST requests per second. |
| Tier 3 | Last week trading volume >= 2,000,000,000yen | 50req/s | Maximum 50 GET requests per second. Maximum 50 POST requests per second. |
*Trading volume targets spot trading and margin trading of exchange.
*Trading volume data will be collected between past Sunday 6:00 and current Sunday 5:59 JST.
*Tier will be updated every Sunday between 6:00 - 6:30 JST.
Private WebSocket API Limiting
- Private WebSocket API is limited to maximum 1 request (subscribe/unsubscribe) per second for each IP address.
- If you enable the IP restriction feature on the membership site, it will deny any API calling that comes from a non-registered IP.
- Only features specified at the time of issuing the API key can be subscribed.
Other
We may restrict API usage due to any of the following reasons.
- To automatically limit the flow rate when our entire system experiences overload.
- We have determined the user's API usage may be causing an overload on our system.
- We have determined that users are repeatedly placing orders to intentionally overload our system.
Opening New Accounts
If you don't have an account Sign up for free
Creating API Keys
After opening an account, you can create API keys from the membership site.
When you create an API key, you can set a permission for each functionality.
The following CryptoCurrency withdrawal APIs have a separate permission for each API. Give the API key the permission for each API you call. An API key without the permission cannot call that API.
- CryptoCurrency withdrawal
- Cancel CryptoCurrency withdrawal
- CryptoCurrency withdrawal status
- Registered withdrawal addresses
- Countries and regions
- States and provinces
- Withdrawal purposes
* Two-factor authentication is required to create, edit, or enable any API key, regardless of its permissions. Customers aged 18 or 19 cannot create or edit an API key with permissions for the CryptoCurrency withdrawal APIs.
* If an API key with permissions for the CryptoCurrency withdrawal APIs and its API secret are exposed to a third party, your cryptocurrency may be withdrawn to a registered address without any action on your part. Withdrawals via the API do not require two-factor authentication for each request.
Give withdrawal permissions only when needed, and disable the API key while you are not using the API. Enabling the IP restriction feature blocks API calls from unregistered IP addresses even if the API key is exposed (see API Limiting). You are responsible for keeping your API key and API secret strictly confidential.
Authentication
Private API
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://END_POINT_URL';
const path = '/v1/PATH';
const reqBody = JSON.stringify({});
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://END_POINT_URL'
path = '/v1/PATH'
reqBody = {}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (res.json())
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://END_POINT_URL"
path := "/v1/PATH"
reqBody := (`{}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://END_POINT_URL'
path = '/v1/PATH'
reqBody = {}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://END_POINT_URL"
var path = "/v1/PATH"
var reqBody = """{}"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://END_POINT_URL';
$path = '/v1/PATH';
$reqBody = '{}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
order().unwrap();
}
fn order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://END_POINT_URL";
let path = "/v1/PATH";
let parameters = json!({});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://END_POINT_URL"
path :: S.String
path = "/v1/PATH"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {}
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Sample();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Sample()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://END_POINT_URL";
const string path = "/v1/PATH";
var reqBody = "{}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/PATH"
let reqBodyStr = """
{}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
HTTP header requires to include information with using API key and API secret below:
- API-KEY: Access key that is issued on the membership site
- API-TIMESTAMP: The request's Unix Timestamp
- API-SIGN: Signature generated for each request with the following method
Signature Generation
You can generate the signature by signing a concatenated string of the request's Unix Timestamp (milliseconds), the HTTP method, the request path, and the request body with your API secret key using the HMAC-SHA256 algorithm. Please pay special attention to the following:
- For GET requests, the request body must be an empty string.
- The request path must start with
/v1and must not start with/private.
Private WebSocket API
Using a Private API to get an access token. The way of authentication for the Private API is the same as the other Private API.
Public API
Service Status
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/status';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/status'
response = requests.get(endPoint + path)
print(response.json())
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/status"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/status'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/status"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/status';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/status")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
response <- httpJSON "https://api.coin.z.com/public/v1/status"
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Status();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Status()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/status";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/status"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"status": "OPEN"
},
"responsetime": "2019-03-19T02:15:06.001Z"
}
Gets the service status of GMO Coin.
Request
GET /public/v1/status
Parameters
None
Response
| Property Name | Value | Description |
|---|---|---|
| status | string | Service status: MAINTENANCE PREOPEN OPEN |
Ticker
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/ticker?symbol=BTC';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/ticker?symbol=BTC'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/ticker?symbol=BTC"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/ticker?symbol=BTC'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/ticker?symbol=BTC"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/ticker?symbol=BTC';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/ticker?symbol=BTC")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/ticker"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "BTC")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Ticker();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Ticker()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/ticker?symbol=BTC";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/ticker?symbol=BTC"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"ask": "750760",
"bid": "750600",
"high": "762302",
"last": "756662",
"low": "704874",
"symbol": "BTC",
"timestamp": "2018-03-30T12:34:56.789Z",
"volume": "194785.8484"
}
],
"responsetime": "2019-03-19T02:15:06.014Z"
}
Gets the latest rates of the specified symbol.
If you want to get all symbols' rates, we recommend calling out it without a symbol.
Request
GET /public/v1/ticker
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Optional | If a symbol is not specified, returns all symbols' rates.The handling symbols are here |
Response
| Property Name | Value | Description |
|---|---|---|
| list.volume | string | Volume of trade in 24 hours. |
Order Books
Request example:
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/orderbooks?symbol=BTC';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/orderbooks?symbol=BTC'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/orderbooks?symbol=BTC"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/orderbooks?symbol=BTC'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/orderbooks?symbol=BTC"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/orderbooks?symbol=BTC';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/orderbooks?symbol=BTC")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/orderbooks"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "BTC")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Orderbooks();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Orderbooks()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/orderbooks?symbol=BTC";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/orderbooks?symbol=BTC"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"asks": [
{
"price": "455659",
"size": "0.1"
}
],
"bids": [
{
"price": "455659",
"size": "0.1"
}
],
"symbol": "BTC"
},
"responsetime": "2019-03-19T02:15:06.026Z"
}
Gets an order book (snapshot) of the specified symbol.
Request
GET /public/v1/orderbooks
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here |
Response
| Property Name | Value | Description |
|---|---|---|
| asks | array | Information of sell orders in ascending order of price. |
| bids | array | Information of buy orders in descending order of price. |
Trade History
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/trades?symbol=BTC&page=1&count=10';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/trades?symbol=BTC&page=1&count=10'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/trades?symbol=BTC&page=1&count=10"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/trades?symbol=BTC&page=1&count=10'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/trades?symbol=BTC&page=1&count=10"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/trades?symbol=BTC&page=1&count=10';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/trades?symbol=BTC&page=1&count=10")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/trades"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "BTC"), ("page", Just "1"), ("count", Just "10")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Trades();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Trades()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/trades?symbol=BTC&page=1&count=10";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/trades?symbol=BTC&page=1&count=10"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"currentPage": 1,
"count": 30
},
"list": [
{
"price": "750760",
"side": "BUY",
"size": "0.1",
"timestamp": "2018-03-30T12:34:56.789Z"
}
]
},
"responsetime": "2019-03-28T09:28:07.980Z"
}
Gets the trade history in descending order of timestamp for a specified symbol.
Request
GET /public/v1/trades
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here |
| page | number | Optional | Target page: If a page is not specified, it will run assuming 1 is set. |
| count | number | Optional | Number of items that you want to get in 1 page: If a count is not specified, it will run assuming 100 (maximum value) is set. |
Response
| Property Name | Value | Description |
|---|---|---|
| price | string | Executed price |
| side | string | Side: BUY SELL |
| size | string | Executed quantity |
| timestamp | string | Executed timestamp |
KLine Data
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/klines?symbol=BTC&interval=1min&date=20210417';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/klines?symbol=BTC&interval=1min&date=20210417'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/klines?symbol=BTC&interval=1min&date=20210417"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/klines?symbol=BTC&interval=1min&date=20210417'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/klines?symbol=BTC&interval=1min&date=20210417"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/klines?symbol=BTC&interval=1min&date=20210417';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/klines?symbol=BTC&interval=1min&date=20210417")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/klines"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "BTC"), ("interval", Just "1min"), ("date", Just "20210417")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Klines();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Klines()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/klines?symbol=BTC&interval=1min&date=20210417";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/klines?symbol=BTC&interval=1min&date=20210417"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"openTime":"1618588800000",
"open":"6418255",
"high":"6518250",
"low":"6318250",
"close":"6418253",
"volume":"0.0001"
},
{
"openTime":"1618588860000",
"open":"6418251",
"high":"6418252",
"low":"6415250",
"close":"6418245",
"volume":"0.0001"
}
],
"responsetime": "2019-03-28T09:28:07.980Z"
}
Gets a market's OHLCV candlestick data (sorted by start time in ascending order) of the specified symbol.
Request
GET /public/v1/klines
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here |
| interval | string | Required |
1min 5min 10min 15min 30min 1hour 4hour 8hour 12hour 1day 1week 1month |
| date | string | Required |
Acceptable data formats: YYYYMMDD YYYYIf YYYYMMDD , the following interval values are supported: 1min 5min 10min 15min 30min 1hour *The date should be equal to or after 20210415. Date will be renewed at JST 6:00.If YYYY , the following interval values are supported: 4hour 8hour 12hour 1day 1week 1month *The date should be equal to or after the release date of each symbol. The release date is here. |
Response
| Property Name | Value | Description |
|---|---|---|
| openTime | string | Start unix timestamp(milliseconds) |
| open | string | Open price |
| high | string | High price |
| low | string | Low price |
| close | string | Close price |
| volume | string | Volume of trade |
Trade rules
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/symbols';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/symbols'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/symbols"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/symbols'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/symbols"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/symbols';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/symbols")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/symbols"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Orderbooks();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Orderbooks()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/symbols";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/symbols"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"symbol": "BTC",
"minOrderSize": "0.0001",
"maxOrderSize": "5",
"sizeStep": "0.0001",
"tickSize": "1",
"takerFee": "0.0005",
"makerFee": "-0.0001"
},
{
"symbol": "BTC_JPY",
"minOrderSize": "0.01",
"maxOrderSize": "5",
"sizeStep": "0.01",
"tickSize": "1",
"takerFee": "0",
"makerFee": "0"
}
],
"responsetime": "2022-12-15T19:22:23.792Z"
}
Gets trade rules.
Request
GET /public/v1/symbols
Parameters
None
Response
| Property Name | Value | Description |
|---|---|---|
| symbol | string | The handling symbols are here |
| minOrderSize | string | Minimum order amount |
| maxOrderSize | string | Maximum order amount |
| sizeStep | string | Minimum order value |
| tickSize | string | Tick size |
| takerFee | string | Taker Fee |
| makerFee | string | Maker Fee |
Public WebSocket API
- A ping will be sent from the server to a client once per minute. If there's no response (pong) from a client 3 consecutive times, then the WebSocket will be disconnected automatically.
Ticker
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/public/v1");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/public/v1')
def on_open(self):
message = {
"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/public/v1"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/public/v1")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "ticker",
:symbol => 'BTC'
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/public/v1"
var sendMsg = """
{"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// Required installing ratchet/pawl with a command below before running the code.
// composer require ratchet/pawl
require __DIR__ . '/vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop);
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$connector("wss://api.coin.z.com/ws/public/v1")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "ticker", "symbol": "BTC" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/public/v1" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = Ticker();
task.Wait();
}
static async Task Ticker()
{
const string endpoint = "wss://api.coin.z.com/ws/public/v1";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/public/v1");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/public/v1")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel":"ticker",
"ask": "750760",
"bid": "750600",
"high": "762302",
"last": "756662",
"low": "704874",
"symbol": "BTC",
"timestamp": "2018-03-30T12:34:56.789Z",
"volume": "194785.8484"
}
Gets the latest rates of the specified symbol.
After subscribe, tickers start to be sent.
Parameters
- Parameter type: JSON
| Property Name | Type | Required | Available Values |
|---|---|---|---|
| command | string | Required |
subscribe unsubscribe |
| channel | string | Required |
ticker |
| symbol | string | Required |
The handling symbols are here |
Response
| Property Name | Value | Description |
|---|---|---|
| channel | string | ticker |
| ask | string | The best indicative price in the current selling orders. |
| bid | string | The best indicative price in the current buying orders. |
| high | string | The highest trading price of the day. |
| last | string | The latest trading price. |
| low | string | The lowest trading price of the day. |
| symbol | string | The handling symbols are here |
| timestamp | string | Executed timestamp. |
| volume | string | Volume of trade in 24 hours. |
- There is no Response when
unsubscribeis requested.
Order Books
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/public/v1");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/public/v1')
def on_open(self):
message = {
"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/public/v1"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/public/v1")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "orderbooks",
:symbol => 'BTC'
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/public/v1"
var sendMsg = """
{"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// Required installing ratchet/pawl with a command below before running the code.
// composer require ratchet/pawl
require __DIR__ . '/vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop);
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$connector("wss://api.coin.z.com/ws/public/v1")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "orderbooks", "symbol": "BTC" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/public/v1" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = Orderbooks();
task.Wait();
}
static async Task Orderbooks()
{
const string endpoint = "wss://api.coin.z.com/ws/public/v1";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/public/v1");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/public/v1")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel":"orderbooks",
"asks": [
{"price": "455659","size": "0.1"},
{"price": "455658","size": "0.2"}
],
"bids": [
{"price": "455665","size": "0.1"},
{"price": "455655","size": "0.3"}
],
"symbol": "BTC",
"timestamp": "2018-03-30T12:34:56.789Z"
}
Gets an order book (snapshot) of the specified symbol.
After subscribe, order books start to be sent.
Parameters
- Parameter type: JSON
| Property Name | Type | Required | Available Values |
|---|---|---|---|
| command | string | Required |
subscribe unsubscribe |
| channel | string | Required |
orderbooks |
| symbol | string | Required |
The handling symbols are here |
Response
| Property Name | Value | Description |
|---|---|---|
| channel | string | orderbooks |
| asks | array | Information of sell orders in ascending order of price. |
| bids | array | Information of buy orders in descending order of price. |
| symbol | string | The handling symbols are here |
| timestamp | string | Timestamp of the orderbook. |
- There is no Response when
unsubscribeis requested.
Trades
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/public/v1");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "trades",
"symbol": "BTC"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/public/v1')
def on_open(self):
message = {
"command": "subscribe",
"channel": "trades",
"symbol": "BTC"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/public/v1"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "trades",
"symbol": "BTC"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/public/v1")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "trades",
:symbol => 'BTC'
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/public/v1"
var sendMsg = """
{"command": "subscribe",
"channel": "trades",
"symbol": "BTC"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// Required installing ratchet/pawl with a command below before running the code.
// composer require ratchet/pawl
require __DIR__ . '/vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop);
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$connector("wss://api.coin.z.com/ws/public/v1")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "trades", "symbol": "BTC" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/public/v1" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = Trades();
task.Wait();
}
static async Task Trades()
{
const string endpoint = "wss://api.coin.z.com/ws/public/v1";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/public/v1");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/public/v1")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "trades",
"symbol": "BTC"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel":"trades",
"price": "750760",
"side": "BUY",
"size": "0.1",
"timestamp": "2018-03-30T12:34:56.789Z",
"symbol": "BTC"
}
Gets trade histories of the specified symbol.
After subscribe, trade histories start to be sent.
Parameters
- Parameter type: JSON
| Property Name | Type | Required | Available Values |
|---|---|---|---|
| command | string | Required |
subscribe unsubscribe |
| channel | string | Required |
trades |
| symbol | string | Required |
The handling symbols are here |
| option | string | Optional | TAKER_ONLY*If option is specified, it will send taker data only. *If you request multiple trade subscriptions with the same symbol, only the latest request will be valid. |
Response
| Property Name | Value | Description |
|---|---|---|
| channel | string | trades |
| price | string | Executed price |
| side | string | Side: BUY SELL |
| size | string | Executed quantity |
| timestamp | string | Executed timestamp |
| symbol | string | The handling symbols are here |
- There is no Response when
unsubscribeis requested.
Private API
Margin
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/margin';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/margin'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/margin"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/margin'
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
import org.json.JSONObject
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/margin"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/margin';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
margin().unwrap();
}
fn margin() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/margin";
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/margin"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Margin();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Margin()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/margin";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/margin"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"actualProfitLoss": "68286188",
"availableAmount": "57262506",
"availableAmountForSpot": "57262506",
"cryptoShortfallStatus": "NORMAL",
"margin": "1021682",
"marginCallStatus": "NORMAL",
"marginRatio": "6683.6",
"profitLoss": "0",
"transferableAmount": "57262506"
},
"responsetime": "2019-03-19T02:15:06.051Z"
}
Gets information of trading capacity.
Request
GET /private/v1/account/margin
Parameters
None
Response
| Property Name | Value | Description |
|---|---|---|
| actualProfitLoss | string | The summary of the current evaluated amount |
| availableAmount | string | Available amount (including the collateral crypto-asset value, for leverage trading) |
| availableAmountForSpot | string | Available amount for spot trading (excluding the collateral crypto-asset value) |
| cryptoShortfallStatus | string | Crypto collateral shortfall status: NORMAL SHORTFALL LIQUIDATION |
| margin | string | Used margin |
| marginCallStatus | string | Marin call status: NORMAL MARGIN_CALL LOSSCUT |
| marginRatio | string | Maintenance margin ratio |
| profitLoss | string | Appraisal profit or loss |
| transferableAmount | string | Transferable amount |
Assets
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/assets';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/assets'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/assets"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/assets'
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/assets"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/assets';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/assets";
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/assets"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/assets";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/assets"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"amount": "993982448",
"available": "993982448",
"conversionRate": "1",
"symbol": "JPY"
},
{
"amount": "4.0002",
"available": "4.0002",
"conversionRate": "859614",
"symbol": "BTC"
}
],
"responsetime": "2019-03-19T02:15:06.055Z"
}
Retrieves asset data.
Request
GET /private/v1/account/assets
Parameters
None
Response
| Property Name | Value | Description |
|---|---|---|
| amount | string | Amount |
| available | string | Available amount (Amount - Scheduled withdrawal amount) |
| conversionRate | string | JPY conversion rate (It is the selling price in the OTC Spot Market. *If the symbol is not listed in the OTC Spot Market, the final execution price in the Spot Trading will be used as the JPY conversion rate.) |
| symbol | string | Asset Ticker Symbol: The handling symbols are here *Only symbols available on the exchange (Spot Trading) can be ordered by API.The handling symbols are here |
Trading Volume
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/tradingVolume';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/tradingVolume'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/tradingVolume"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/tradingVolume'
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/tradingVolume"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/tradingVolume';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/tradingVolume";
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/tradingVolume"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/tradingVolume";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/tradingVolume"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"jpyVolume": "9988888",
"tierLevel": 1,
"limit": [
{
"symbol": "BTC/JPY",
"todayLimitOpenSize": "10000",
"takerFee": "0",
"makerFee": "0"
},
{
"symbol": "BTC",
"todayLimitBuySize": "98",
"todayLimitSellSize": "102",
"takerFee": "0.0015",
"makerFee": "-0.0007"
}
]
},
"responsetime": "2019-03-19T02:15:06.055Z"
}
Returns trading volume data.
Request
GET /private/v1/account/tradingVolume
Parameters
None
Response
| Property Name | Value | Description |
|---|---|---|
| jpyVolume | string | Current week's trading volume (Japanese Yen) |
| tierLevel | number | Current trading level: 1 2 3 |
| limit.symbol | string | The handling symbols are here |
| limit.todayLimitOpenSize | string | Remaining size of maximum daily trading volume (Open) *Margin symbols only |
| limit.todayLimitBuySize | string | Remaining size of maximum daily trading volume (Buy) *Spot symbols only |
| limit.todayLimitSellSize | string | Remaining size of maximum daily trading volume (Sell) *Spot symbols only |
| limit.takerFee | string | Taker Fee |
| limit.makerFee | string | Maker Fee |
Fiat deposit history
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/fiatDeposit/history';
const parameters = '?fromTimestamp=2024-03-01T00:00:00.000Z';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/fiatDeposit/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "fromTimestamp": "2024-03-01T00:00:00.000Z" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/fiatDeposit/history"
parameters := "?fromTimestamp=2024-03-01T00:00:00.000Z"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/fiatDeposit/history'
parameters = {
:fromTimestamp => '2024-03-01T00:00:00.000Z'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/fiatDeposit/history"
var parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/fiatDeposit/history';
$parameters = '?fromTimestamp=2024-03-01T00:00:00.000Z';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/fiatDeposit/history";
let mut parameters = HashMap::new();
parameters.insert("fromTimestamp", "2024-03-01T00:00:00.000Z");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/fiatDeposit/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("fromTimestamp", Just "2024-03-01T00:00:00.000Z")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/fiatDeposit/history";
const string parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/fiatDeposit/history"
let parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"amount": "50000",
"fee": "0",
"status": "EXECUTED",
"symbol": "JPY",
"timestamp": "2021-01-01T13:47:12.791Z"
}
],
"responsetime": "2024-02-28T11:48:57.996Z"
}
Returns JPY deposit history data.
Request
GET /private/v1/account/fiatDeposit/history
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| fromTimestamp | string | Required |
Start search (UTC):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:00:00.000Z)* When only fromTimestamp is specified, toTimestamp will be 'fromTimestamp + 30 minutes'. |
| toTimestamp | string | Optional | End search (UTC):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:30:00.000Z)* The maximum difference between fromTimestamp and toTimestamp is 30 minutes. |
Response
| Property Name | Value | Description |
|---|---|---|
| amount | string | amount |
| fee | string | fee |
| status | string | status: EXECUTED |
| symbol | string | symbol: JPY |
| timestamp | string | executed timestamp(UTC) |
Fiat withdrawal history
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/fiatWithdrawal/history';
const parameters = '?fromTimestamp=2024-03-01T00:00:00.000Z';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/fiatWithdrawal/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "fromTimestamp": "2024-03-01T00:00:00.000Z" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/fiatWithdrawal/history"
parameters := "?fromTimestamp=2024-03-01T00:00:00.000Z"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/fiatWithdrawal/history'
parameters = {
:fromTimestamp => '2024-03-01T00:00:00.000Z'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/fiatWithdrawal/history"
var parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/fiatWithdrawal/history';
$parameters = '?fromTimestamp=2024-03-01T00:00:00.000Z';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/fiatWithdrawal/history";
let mut parameters = HashMap::new();
parameters.insert("fromTimestamp", "2024-03-01T00:00:00.000Z");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/fiatWithdrawal/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("fromTimestamp", Just "2024-03-01T00:00:00.000Z")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/fiatWithdrawal/history";
const string parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/fiatWithdrawal/history"
let parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"amount": "50000",
"fee": "0",
"status": "EXECUTED",
"symbol": "JPY",
"timestamp": "2021-01-01T13:47:12.791Z"
}
],
"responsetime": "2024-02-28T11:48:57.996Z"
}
Returns JPY withdrawal history data。
Request
GET /private/v1/account/fiatWithdrawal/history
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| fromTimestamp | string | Required |
Start search (UTC):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:00:00.000Z)* When only fromTimestamp is specified, toTimestamp will be 'fromTimestamp + 30 minutes'. |
| toTimestamp | string | Optional | End search (UTC):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:30:00.000Z)* The maximum difference between fromTimestamp and toTimestamp is 30 minutes. |
Response
| Property Name | Value | Description |
|---|---|---|
| amount | string | amount |
| fee | string | fee |
| status | string | status: EXECUTED |
| symbol | string | The handling symbols are here: JPY |
| timestamp | string | executed timestamp(UTC) |
CryptoCurrency deposit history
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/deposit/history';
const parameters = '?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/deposit/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "symbol": "BTC", "fromTimestamp": "2024-03-01T00:00:00.000Z" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/deposit/history"
parameters := "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/deposit/history'
parameters = {
:symbol => 'BTC',
:fromTimestamp => '2024-03-01T00:00:00.000Z'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/deposit/history"
var parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/deposit/history';
$parameters = '?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/deposit/history";
let parameters = json!({
"symbol": "BTC",
"fromTimestamp": "2024-03-01T00:00:00.000Z"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/deposit/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC"), ("fromTimestamp", Just "2024-03-01T00:00:00.000Z")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/deposit/history";
const string parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/deposit/history"
let parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"address": "xxx",
"amount": "0.9503",
"status": "EXECUTED",
"symbol": "BTC",
"timestamp": "2021-10-05T06:04:46.241Z",
"txHash": "yyy"
}
],
"responsetime": "2024-02-28T12:20:07.103Z"
}
Returns CryptoCurrency deposit history data.
Request
GET /private/v1/account/deposit/history
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here |
| fromTimestamp | string | Required |
Start search (UTC):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:00:00.000Z)* When only fromTimestamp is specified, toTimestamp will be 'fromTimestamp + 30 minutes'. |
| toTimestamp | string | Optional | End search (UTC):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:30:00.000Z)* The maximum difference between fromTimestamp and toTimestamp is 30 minutes. |
Response
| Property Name | Value | Description |
|---|---|---|
| address | string | address |
| amount | string | amount |
| fee | string | fee |
| status | string | status: EXECUTED |
| symbol | string | The handling symbols are here |
| timestamp | string | executed timestamp(UTC) |
| txHash | string | transaction hash |
CryptoCurrency withdrawal history
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/history';
const parameters = '?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "symbol": "BTC", "fromTimestamp": "2024-03-01T00:00:00.000Z" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/history"
parameters := "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/history'
parameters = {
:symbol => 'BTC',
:fromTimestamp => '2024-03-01T00:00:00.000Z'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/history"
var parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/history';
$parameters = '?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/history";
let parameters = json!({
"symbol": "BTC",
"fromTimestamp": "2024-03-01T00:00:00.000Z"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC"), ("fromTimestamp", Just "2024-03-01T00:00:00.000Z")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/history";
const string parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/history"
let parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"address": "xxx",
"amount": "0.9503",
"status": "EXECUTED",
"symbol": "BTC",
"timestamp": "2021-10-05T06:04:46.241Z",
"txHash": "yyy"
}
],
"responsetime": "2024-02-28T12:20:07.103Z"
}
Returns CryptoCurrency withdrawal history data.
Request
GET /private/v1/account/withdrawal/history
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here |
| fromTimestamp | string | Required |
Start search (UTC):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:00:00.000Z)* When only fromTimestamp is specified, toTimestamp will be 'fromTimestamp + 30 minutes'. |
| toTimestamp | string | Optional | End search (UTC):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:30:00.000Z)* The maximum difference between fromTimestamp and toTimestamp is 30 minutes. |
Response
| Property Name | Value | Description |
|---|---|---|
| address | string | address |
| amount | string | amount |
| fee | string | fee |
| status | string | status: EXECUTED |
| symbol | string | The handling symbols are here |
| timestamp | string | executed timestamp(UTC) |
| txHash | string | transaction hash |
Registered withdrawal addresses
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/crypto/addresses';
const parameters = '?symbol=ETH';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/addresses'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "symbol": "ETH" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/crypto/addresses"
parameters := "?symbol=ETH"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/addresses'
parameters = {
:symbol => 'ETH'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/crypto/addresses"
var parameters = "?symbol=ETH"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/crypto/addresses';
$parameters = '?symbol=ETH';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
withdrawal_crypto_addresses().unwrap();
}
fn withdrawal_crypto_addresses() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/crypto/addresses";
let parameters = json!({
"symbol": "ETH"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/crypto/addresses"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "ETH")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WithdrawalCryptoAddresses();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WithdrawalCryptoAddresses()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/crypto/addresses";
const string parameters = "?symbol=ETH";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/crypto/addresses"
let parameters = "?symbol=ETH"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"addressId": 858872,
"symbol": "ETH",
"name": "メタマスクETH",
"address": "0x0785Ee6A44543aDAC0607A656AEa2e2c96c266f7",
"chainType": 0,
"vaspType": "PRIVATE",
"vaspName": null,
"receiverType": "SELF",
"sendable": true,
"sendableFrom": null
}
]
},
"responsetime": "2026-11-14T02:00:00.456Z"
}
Returns the registered addresses that can be used for CryptoCurrency withdrawal.
Addresses that have been registered and have passed the review on the membership site are returned. Both external addresses and GMO Coin accounts are included. Addresses that are under review, rejected, or invalid are not included. Addresses for which the membership site asks you to enter additional recipient information are not included either (including addresses of crypto-asset service providers not connected to Sygna whose country of location has not been entered). Once the additional information has been entered and reviewed on the membership site, the address is included in the list.
* Addresses can be registered, changed, or deleted only on the membership site, not via the API.
* An address cannot be used for withdrawal for 24 hours after we send you the email notifying you that the review of the address is complete. An address whose sendable is false can be used on or after the date and time in sendableFrom.
* If you specify the addressId of an address that is not included in the list in CryptoCurrency withdrawal, ERR-5138 is returned.
Request
GET /private/v1/account/withdrawal/crypto/addresses
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here* Specify one symbol per request. |
Response
| Property Name | Value | Description |
|---|---|---|
| list[].addressId | number | Address ID. Specify this value as addressId in CryptoCurrency withdrawal. |
| list[].symbol | string | The handling symbols are here |
| list[].name | string | Name of the address registered on the membership site |
| list[].address | string | Destination address. For a GMO Coin account, this is the deposit address of the destination account. |
| list[].chainType | number | chain type: 0 1 |
| list[].vaspType | string | address type: PRIVATE INTERNAL OTHER_VASP SYGNA_VASP |
| list[].vaspName | string | Name of the destination crypto-asset service provider. Set only when the address type is SYGNA_VASP or OTHER_VASP; otherwise null. |
| list[].receiverType | string | receiver type: SELF THIRD_PARTY null for addresses that are neither yourself nor a third party. |
| list[].sendable | bool | Whether the address can be used for withdrawal now. false within 24 hours after we send you the email notifying you that the review of the address is complete. |
| list[].sendableFrom | string | Date and time (UTC) when the address becomes available for withdrawal, set only when sendable is false; otherwise null. |
Withdrawal purposes
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/crypto/purposes';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/purposes'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/crypto/purposes"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/purposes'
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/crypto/purposes"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/crypto/purposes';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
withdrawal_crypto_purposes().unwrap();
}
fn withdrawal_crypto_purposes() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/crypto/purposes";
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/crypto/purposes"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WithdrawalCryptoPurposes();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WithdrawalCryptoPurposes()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/crypto/purposes";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/crypto/purposes"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"purposeCode": 2,
"name": "暗号資産の保管",
"nameEn": "Storage of crypto assets",
"requiresText": false,
"requiresTradeDetails": false,
"manualReview": false
},
{
"purposeCode": 13,
"name": "輸入品代金の支払い",
"nameEn": "Payment for imported goods",
"requiresText": false,
"requiresTradeDetails": true,
"manualReview": true
}
]
},
"responsetime": "2026-11-14T02:00:00.456Z"
}
Returns the list of withdrawal purposes that can be specified in CryptoCurrency withdrawal.
* When you specify a purpose whose requiresText is true, purposeText is required. When you specify a purpose whose requiresTradeDetails is true (trade-related), tradeDetails is required.
* Purposes whose manualReview is true are subject to a manual review by GMO Coin, and the review takes time to complete.
* Only the purposes that can be specified for your account type are returned. For general corporation accounts, 1, 2, 26, and 99 are returned. For special corporation accounts, the same purposes as individual accounts are returned. Specifying a purpose code that is not in the list returns ERR-5153 when the request is received.
Request
GET /private/v1/account/withdrawal/crypto/purposes
Parameters
None
Response
| Property Name | Value | Description |
|---|---|---|
| list[].purposeCode | number | Purpose code. Specify this value as purposeCode in CryptoCurrency withdrawal. |
| list[].name | string | Name of the purpose (in Japanese) |
| list[].nameEn | string | Name of the purpose (in English) |
| list[].requiresText | bool | If true, purposeText is required. |
| list[].requiresTradeDetails | bool | If true, tradeDetails is required. |
| list[].manualReview | bool | If true, the purpose is subject to a manual review (the review takes time). |
Countries and regions
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/crypto/nations';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/nations'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/crypto/nations"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/nations'
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/crypto/nations"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/crypto/nations';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
withdrawal_crypto_nations().unwrap();
}
fn withdrawal_crypto_nations() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/crypto/nations";
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/crypto/nations"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WithdrawalCryptoNations();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WithdrawalCryptoNations()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/crypto/nations";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/crypto/nations"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"countryCode": "JPN",
"name": "日本",
"hasProvinces": true
},
{
"countryCode": "CAN",
"name": "カナダ",
"hasProvinces": false
}
]
},
"responsetime": "2026-11-14T02:00:00.456Z"
}
Returns the list of countries and regions to be specified as locations in tradeDetails of CryptoCurrency withdrawal when the purpose is trade-related.
* The list also includes countries and regions to which we do not allow withdrawals. A request that specifies such a country or region as a location is rejected (REJECTED) in the review of the withdrawal purpose after acceptance.
Request
GET /private/v1/account/withdrawal/crypto/nations
Parameters
None
Response
| Property Name | Value | Description |
|---|---|---|
| list[].countryCode | string | Country or region code (ISO 3166-1 alpha-3) |
| list[].name | string | Name of the country or region (in Japanese) |
| list[].hasProvinces | bool | For countries and regions where this is true (Japan, the United States, and China), specify regionCode in the location. Otherwise, specify cityName. |
States and provinces
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/crypto/provinces';
const parameters = '?countryCode=JPN';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/provinces'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "countryCode": "JPN" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/crypto/provinces"
parameters := "?countryCode=JPN"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/provinces'
parameters = {
:countryCode => 'JPN'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/crypto/provinces"
var parameters = "?countryCode=JPN"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/crypto/provinces';
$parameters = '?countryCode=JPN';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
withdrawal_crypto_provinces().unwrap();
}
fn withdrawal_crypto_provinces() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/crypto/provinces";
let parameters = json!({
"countryCode": "JPN"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/crypto/provinces"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("countryCode", Just "JPN")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WithdrawalCryptoProvinces();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WithdrawalCryptoProvinces()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/crypto/provinces";
const string parameters = "?countryCode=JPN";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/crypto/provinces"
let parameters = "?countryCode=JPN"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"regionCode": "010",
"name": "北海道"
},
{
"regionCode": "020",
"name": "青森県"
}
]
},
"responsetime": "2026-11-14T02:00:00.456Z"
}
Returns the list of states and provinces to be specified as locations in tradeDetails of CryptoCurrency withdrawal when the purpose is trade-related.
* regionCode is assigned per country or region, so the same value may appear in different countries. Always use it together with countryCode.
* If you specify a country or region that has no states or provinces, or a country code that does not exist, no error occurs and list is returned as an empty array. If countryCode is not three uppercase letters, ERR-5106 is returned.
Request
GET /private/v1/account/withdrawal/crypto/provinces
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| countryCode | string | Required |
Country or region code (ISO 3166-1 alpha-3). Specify a country or region whose hasProvinces is true in Countries and regions. |
Response
| Property Name | Value | Description |
|---|---|---|
| list[].regionCode | string | State or province code (3-digit string, e.g. 010) |
| list[].name | string | Name of the state or province (in Japanese) |
CryptoCurrency withdrawal
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/crypto';
const reqBody = JSON.stringify({
clientOrderId: "withdrawal001",
symbol: "ETH",
addressId: 858872,
sendAmount: "0.1",
purposeCode: 2
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto'
reqBody = {
"clientOrderId": "withdrawal001",
"symbol": "ETH",
"addressId": 858872,
"sendAmount": "0.1",
"purposeCode": 2
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/crypto"
reqBody := (`{
"clientOrderId": "withdrawal001",
"symbol": "ETH",
"addressId": 858872,
"sendAmount": "0.1",
"purposeCode": 2
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto'
reqBody = {
:clientOrderId => 'withdrawal001',
:symbol => 'ETH',
:addressId => 858872,
:sendAmount => '0.1',
:purposeCode => 2
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/crypto"
var reqBody = """
{"clientOrderId": "withdrawal001", "symbol": "ETH", "addressId": 858872, "sendAmount": "0.1", "purposeCode": 2}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/crypto';
$reqBody = '{
"clientOrderId": "withdrawal001",
"symbol": "ETH",
"addressId": 858872,
"sendAmount": "0.1",
"purposeCode": 2
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
withdrawal_crypto().unwrap();
}
fn withdrawal_crypto() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/crypto";
let parameters = json!({
"clientOrderId": "withdrawal001",
"symbol": "ETH",
"addressId": 858872,
"sendAmount": "0.1",
"purposeCode": 2
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/crypto"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"clientOrderId": "withdrawal001",
"symbol": "ETH",
"addressId": 858872,
"sendAmount": "0.1",
"purposeCode": 2
}
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WithdrawalCrypto();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WithdrawalCrypto()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/crypto";
var reqBody = "{ \"clientOrderId\": \"withdrawal001\", \"symbol\": \"ETH\", \"addressId\": 858872, \"sendAmount\": \"0.1\", \"purposeCode\": 2 }";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/crypto"
let reqBodyStr = """
{
"clientOrderId": "withdrawal001",
"symbol": "ETH",
"addressId": 858872,
"sendAmount": "0.1",
"purposeCode": 2
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"orderId": 26145170,
"clientOrderId": "withdrawal001",
"symbol": "ETH",
"addressId": 858872,
"sendAmount": "0.1",
"fee": "0.0004",
"apiFee": "0.0004",
"apiFeeJpy": "220",
"rate": "550000",
"status": "UNDER_REVIEW",
"acceptedAt": "2026-11-14T02:00:00.000Z"
},
"responsetime": "2026-11-14T02:00:00.456Z"
}
tradeDetails example:
{
"clientOrderId": "withdrawal002",
"symbol": "BTC",
"addressId": 850509,
"sendAmount": "0.05",
"purposeCode": 13,
"tradeDetails": {
"receiverLocation": { "countryCode": "JPN", "regionCode": "010", "cityName": null },
"itemName": "食料品",
"originLocation": { "countryCode": "CHN", "regionCode": "004", "cityName": null },
"shipmentLocation": { "countryCode": "CAN", "regionCode": null, "cityName": "Vancouver" }
}
}
Requests a CryptoCurrency withdrawal to a registered address.
Specify the destination with addressId, which can be obtained from Registered withdrawal addresses. The network of the address can be checked with chainType returned by that API.
An API withdrawal fee is charged for each withdrawal request. For the fee amount, see Fees. The fee is converted into the amount of CryptoCurrency at our buying price (BID) at the time of the request, rounded up to the number of decimal places defined for each symbol, and collected from your balance of that CryptoCurrency separately from the withdrawal amount. The same applies when the destination is a GMO Coin account.
* Because the fee is converted at the rate at the time of the request, it varies for each request. You can check the collected fee in fee and apiFee in the response.
* Because the fee is collected from your balance of that CryptoCurrency separately from the withdrawal amount, specifying your entire holding results in insufficient balance (ERR-208). For DOT, ERR-5155 is returned instead if the amount is below the minimum withdrawal amount. Withdraw any holding below the minimum withdrawal amount from the membership site.
Withdrawal requests subject to review are sent after a review by GMO Coin. Withdrawals to a GMO Coin account are not subject to review, and their status is PROCESSING at acceptance. Check the status after acceptance with CryptoCurrency withdrawal status.
* ERR-5004, a system error such as ERR-5000, an HTTP 5xx status, or a timeout does not mean that the withdrawal request failed. The request may have been accepted, so check the result by calling CryptoCurrency withdrawal status with clientOrderId. Requesting again with the same clientOrderId returns ERR-915, so the withdrawal is not made twice.
* If you request again with a new clientOrderId and the earlier request had been accepted, the withdrawal is made twice. Request again only after CryptoCurrency withdrawal status returns ERR-5158 (not accepted). Immediately after a request, processing may not have finished and the request may not be found yet, so check again after a while.
* If a location falls under a country or region to which we do not allow withdrawals, the request is not rejected at acceptance; after acceptance, it is rejected (REJECTED) in the review of the withdrawal purpose.
* Withdrawals within one month of account opening that exceed the limit based on your declared financial assets category are not accepted via the API (ERR-5141).
* A withdrawal request can be canceled only when the address type is SYGNA_VASP and it is waiting for the review. For details, see Cancel CryptoCurrency withdrawal.
* For an example of tradeDetails for a trade-related purpose, see the tradeDetails example below the Response example.
* A withdrawal request for the same symbol can be made only once per second per account. Exceeding this returns ERR-5003. A request rejected by the validation at acceptance (such as an input error) is not counted toward this limit. A request rejected after acceptance by the balance or limit checks (such as ERR-208 for insufficient balance or ERR-5157 for exceeding the daily withdrawal limit) is counted. Withdrawal requests for a different symbol are not subject to this limit.
Request
POST /private/v1/account/withdrawal/crypto
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| clientOrderId | string | Required |
An order identifier assigned by the client. *Only combinations of up to 36 single-byte alphanumeric characters can be used. *Case-sensitive. *It must be unique within the account, and a clientOrderId that has been used before cannot be reused. However, the clientOrderId of a request rejected with an error on acceptance can be reused. The clientOrderId of a request rejected in the review cannot be reused. *ERR-915 is returned if a clientOrderId that has already been used is specified, regardless of the content of the request. Use a new value for each request. When ERR-915 is returned, you can check the result of the original request by calling CryptoCurrency withdrawal status with the same clientOrderId. *If you use a UUID, specify it as 32 hexadecimal characters with the hyphens removed. |
| symbol | string | Required |
The handling symbols are hereSpecify the same symbol as the address of addressId. |
| addressId | number | Required |
Address ID obtained from Registered withdrawal addresses |
| sendAmount | string | Required |
Withdrawal amount. Specify a positive number with no more decimal places than the symbol allows. The specified amount is sent as is, and the fee is collected from your balance separately. For withdrawal conditions such as the minimum withdrawal amount and the daily withdrawal limit, see here. |
| purposeCode | number | *Required unless the address type is INTERNAL (a GMO Coin account) |
Purpose code. Obtain the available values from Withdrawal purposes. Cannot be specified when the address type is INTERNAL (a GMO Coin account) (ERR-5153). |
| purposeText | string | *Required when requiresText of the purpose is true |
Description of the purpose (free text, up to 400 characters). Cannot be specified when requiresText of the purpose is false. |
| tradeDetails | object | *Required when requiresTradeDetails of the purpose is true |
Trade-related information. It cannot be specified for purposes whose requiresTradeDetails is not true (other than trade-related purposes). |
| tradeDetails.receiverLocation | object | Required |
Location of the cargo receiver (Location) |
| tradeDetails.itemName | string | Required |
Name of the imported goods (up to 256 characters) |
| tradeDetails.originLocation | object | Required |
Place of origin (Location) |
| tradeDetails.shipmentLocation | object | Required |
Place of shipment (where the cargo is loaded) (Location) |
- For Location (receiverLocation, originLocation, and shipmentLocation), specify an object with the following properties.
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| countryCode | string | Required |
Country or region code (ISO 3166-1 alpha-3). countryCode from Countries and regions |
| regionCode | string | *Required for countries and regions whose hasProvinces is true |
State or province code. regionCode from States and provinces. It cannot be specified for countries and regions whose hasProvinces is false. |
| cityName | string | *Required for countries and regions whose hasProvinces is false |
City name (up to 256 characters). It cannot be specified for countries and regions whose hasProvinces is true. |
* Specify exactly one of regionCode and cityName. Set the other to null or omit it.
Response
| Property Name | Value | Description |
|---|---|---|
| orderId | number | Order ID. Specify this value in CryptoCurrency withdrawal status and Cancel CryptoCurrency withdrawal. |
| clientOrderId | string | clientOrderId specified in the withdrawal request |
| symbol | string | The handling symbols are here |
| addressId | number | Address ID |
| sendAmount | string | Withdrawal amount |
| fee | string | Total withdrawal fee (amount of CryptoCurrency). The same value as the fee shown in the transaction history on the membership site. |
| apiFee | string | Amount of the API withdrawal fee included in fee |
| apiFeeJpy | string | API withdrawal fee (JPY) |
| rate | string | Rate used to convert the fee (our buying price (BID), JPY) |
| status | string | withdrawal status: UNDER_REVIEW PROCESSING EXECUTED CANCELED REJECTED ERROR |
| acceptedAt | string | Accepted timestamp (UTC). Precise to the second (milliseconds are always 000). For withdrawals subject to the review, this is the same value as the accepted timestamp returned by CryptoCurrency withdrawal status. |
CryptoCurrency withdrawal status
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/crypto/status';
const parameters = '?orderId=26145170';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/status'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "orderId": "26145170" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/crypto/status"
parameters := "?orderId=26145170"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/status'
parameters = {
:orderId => '26145170'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/crypto/status"
var parameters = "?orderId=26145170"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/crypto/status';
$parameters = '?orderId=26145170';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
withdrawal_crypto_status().unwrap();
}
fn withdrawal_crypto_status() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/crypto/status";
let parameters = json!({
"orderId": "26145170"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/crypto/status"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("orderId", Just "26145170")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WithdrawalCryptoStatus();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WithdrawalCryptoStatus()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/crypto/status";
const string parameters = "?orderId=26145170";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/crypto/status"
let parameters = "?orderId=26145170"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"orderId": 26145170,
"clientOrderId": "withdrawal001",
"symbol": "ETH",
"addressId": 858872,
"sendAmount": "0.1",
"fee": "0.0004",
"apiFee": "0.0004",
"status": "EXECUTED",
"cancelable": false,
"txHash": [
"0x40320c23e98939b724eda46e4eadac82e112309fdba82273b179988cf210569a"
],
"acceptedAt": "2026-11-14T02:00:00.000Z",
"updatedAt": "2026-11-14T02:06:14.000Z"
},
"responsetime": "2026-11-14T02:10:00.456Z"
}
Returns the status of the specified CryptoCurrency withdrawal request.
Specify either orderId or clientOrderId.
* ERR-5158 is returned if no matching withdrawal request is found (an order ID that does not exist, an order of another account, or an order other than a withdrawal).
* While a withdrawal is waiting to be sent after the review, its status is PROCESSING. A withdrawal request in PROCESSING cannot be canceled. If PROCESSING continues for a long time, please contact us.
Completed (EXECUTED) withdrawals can also be obtained from CryptoCurrency withdrawal history.
* ERR-5212 is returned if both orderId and clientOrderId are specified, and ERR-5106 is returned if neither is specified or the format is invalid.
Request
GET /private/v1/account/withdrawal/crypto/status
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| orderId | number | * |
Order ID of the withdrawal request |
| clientOrderId | string | * |
clientOrderId specified in the withdrawal request |
Response
| Property Name | Value | Description |
|---|---|---|
| orderId | number | Order id |
| clientOrderId | string | clientOrderId specified in the withdrawal request. null if not set. |
| symbol | string | The handling symbols are here |
| addressId | number | Address ID. null if it cannot be obtained. |
| sendAmount | string | Withdrawal amount |
| fee | string | Total withdrawal fee (amount of CryptoCurrency). The same value as the fee shown in the transaction history on the membership site. |
| apiFee | string | Amount of the API withdrawal fee included in fee. null if no API withdrawal fee is recorded. |
| status | string | withdrawal status: UNDER_REVIEW PROCESSING EXECUTED CANCELED REJECTED ERROR |
| cancelable | bool | Whether a cancellation request can be accepted. true only when the address type is SYGNA_VASP and the request is waiting for the review. false when a cancellation has already been requested or when the status is other than UNDER_REVIEW (such as CANCELED or ERROR). |
| txHash | array | Array of transaction hashes. An empty array before the withdrawal is sent. Contains multiple values if the withdrawal was sent in multiple transactions. If the destination is a GMO Coin account, it remains an empty array even after completion. |
| acceptedAt | string | Accepted timestamp (UTC). Precise to the second (milliseconds are always 000). null for withdrawals that are not subject to the review, such as some withdrawals to GMO Coin accounts. |
| updatedAt | string | Last updated timestamp (UTC). null if it cannot be obtained. |
Cancel CryptoCurrency withdrawal
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/crypto/cancel';
const reqBody = JSON.stringify({
orderId: 26145188
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/cancel'
reqBody = {
"orderId": 26145188
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/crypto/cancel"
reqBody := (`{
"orderId": 26145188
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/crypto/cancel'
reqBody = {
:orderId => 26145188
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/crypto/cancel"
var reqBody = """
{"orderId": 26145188}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/crypto/cancel';
$reqBody = '{
"orderId": 26145188
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
cancel_withdrawal_crypto().unwrap();
}
fn cancel_withdrawal_crypto() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/crypto/cancel";
let parameters = json!({
"orderId": 26145188
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/crypto/cancel"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"orderId": 26145188
}
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CancelWithdrawalCrypto();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CancelWithdrawalCrypto()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/crypto/cancel";
var reqBody = "{ \"orderId\": 26145188 }";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/crypto/cancel"
let reqBodyStr = """
{
"orderId": 26145188
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"orderId": 26145188,
"status": "UNDER_REVIEW",
"cancelRequested": true
},
"responsetime": "2026-11-14T02:00:00.456Z"
}
Requests cancellation of a CryptoCurrency withdrawal request.
Cancellation is possible only for withdrawal requests whose address type is SYGNA_VASP (a crypto-asset service provider connected to Sygna) and only while waiting for the review (the same condition as on the membership site). Withdrawal requests with other address types cannot be canceled.
You can check whether a request can be canceled with cancelable in CryptoCurrency withdrawal status.
* A successful response indicates that the cancellation request has been accepted, not that the cancellation has been completed. Check the completion of the cancellation (CANCELED) with CryptoCurrency withdrawal status.
* You can also cancel on the membership site under the same condition.
Request
POST /private/v1/account/withdrawal/crypto/cancel
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| orderId | number | Required |
Order ID of the withdrawal request to cancel |
Response
| Property Name | Value | Description |
|---|---|---|
| orderId | number | Order id |
| status | string | Withdrawal status at the time the cancellation request was accepted (remains UNDER_REVIEW until the cancellation is completed) |
| cancelRequested | bool | Whether the cancellation request has been accepted |
Exchange Fee History
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/exchangeFee/history';
const parameters = '?fromDate=20260601&toDate=20260607';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/exchangeFee/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "fromDate": "20260601", "toDate": "20260607" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/exchangeFee/history"
parameters := "?fromDate=20260601&toDate=20260607"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/exchangeFee/history'
parameters = {
:fromDate => '20260601',
:toDate => '20260607'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/exchangeFee/history"
var parameters = "?fromDate=20260601&toDate=20260607"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/exchangeFee/history';
$parameters = '?fromDate=20260601&toDate=20260607';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/exchangeFee/history";
let mut parameters = HashMap::new();
parameters.insert("fromDate", "20260601");
parameters.insert("toDate", "20260607");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/exchangeFee/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("fromDate", Just "20260601"), ("toDate", Just "20260607")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/exchangeFee/history";
const string parameters = "?fromDate=20260601&toDate=20260607";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/exchangeFee/history"
let parameters = "?fromDate=20260601&toDate=20260607"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"cursor": "AbzejT4z9R01mjvOj_APz3Y34AQmWAQenEVr07RfrVCbAmJZi9vgFexNTqKFYU9uW7rArTHokipb0gXMElEvu2v90QAey3haCOB9"
},
"list": [
{
"symbol": "BTC_JPY",
"feeType": "LEVERAGE_FEE",
"deliveryDate": "20260615",
"deliveryDatetime": "2026-06-15T21:01:23.456Z",
"deliveryAmount": "-120"
},
{
"symbol": "BTC",
"feeType": "SPOT_FEE_REFUND",
"deliveryDate": "20260615",
"deliveryDatetime": "2026-06-15T21:01:21.229Z",
"deliveryAmount": "4"
}
],
"lastFinalizedDate": "20260615"
},
"responsetime": "2026-07-03T11:48:57.996Z"
}
Returns exchange fee refund (fractional refund of spot and margin trading fees) and exchange margin fee collection history data.
Each record represents one business day per symbol and fee type.
Records are returned newest first (descending by business day; within the same business day, most recently recorded first).
* Leverage trading (Crypto FX) fees are not included.
Records are created by a daily batch process after each business day closes (a business day runs 6:00 to 5:59 JST the next day).
If the business day you want to query is on or before lastFinalizedDate, records for that business day are complete (an empty result can be treated as a confirmed absence of fees/refunds for that day). For business days after lastFinalizedDate, the daily batch is still processing; retry after a while.
lastFinalizedDate reflects the value at response time. It may advance while you are paging through continued results. Records added after it advances cannot be retrieved with the cursor in use. Restart without a cursor when a complete result set is required.
* No record is created for exchange margin fee on a day with no open position or a 0% interest rate. Fee refunds are also not created when the total is 0 yen.
* If the history query times out, ERR-5016 is returned. Retry the same request first; if the error persists, narrow the fromDate/toDate range.
Request
GET /private/v1/account/exchangeFee/history
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| fromDate | string | Required |
Start business day:YYYYMMDD format string (e.g. 20260601)* Must be on or before toDate. Future business days cannot be specified. |
| toDate | string | Optional | End business day:YYYYMMDD format string (e.g. 20260607)* When not specified, toDate will be the same business day as fromDate (single-day search).* The maximum difference between fromDate and toDate is 7 days. |
| count | number | Optional | Maximum number of items per page* The allowed range is 1 to 100. The default value is 100. |
| cursor | string | Optional | Specify the pagination.cursor of the previous response to get the next page.* When cursor is specified, fromDate/toDate must be the same as the previous request.* The next page contains older records (list is returned newest first). |
Response
| Property Name | Value | Description |
|---|---|---|
| pagination.cursor | string | continuation token, set only when the next page exists |
| list[].symbol | string | symbol of the trade the fee was incurred on (Spot: BTC etc. / Margin: BTC_JPY etc.) |
| list[].feeType | string | fee type: LEVERAGE_FEE SPOT_FEE_REFUND LEVERAGE_FEE_REFUND |
| list[].deliveryDate | string | target business day (YYYYMMDD) |
| list[].deliveryDatetime | string | recorded timestamp(UTC) |
| list[].deliveryAmount | string | amount (JPY). Positive for refunds, negative for collections. |
| lastFinalizedDate | string | the latest business day (YYYYMMDD) for which the daily batch process (posting fees / reflecting refunds) has completed. Records up to and including this date are finalized. Not returned for an account whose daily batch process has never completed. |
Orders
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/orders';
const parameters = '?orderId=123456789,223456789';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/orders'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "orderId": "123456789,223456789" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/orders"
parameters := "?orderId=123456789,223456789"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/orders'
parameters = {
:orderId => '123456789,223456789'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/orders"
var parameters = "?orderId=123456789,223456789"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/orders';
$parameters = '?orderId=123456789,223456789';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
orders().unwrap();
}
fn orders() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/orders";
let mut parameters = HashMap::new();
parameters.insert("orderId", "123456789,223456789");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/orders"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("orderId", Just "123456789,223456789")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Orders();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Orders()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/orders";
const string parameters = "?orderId=123456789,223456789";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/orders"
let parameters = "?orderId=123456789,223456789"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"orderId": 223456789,
"clientOrderId": "abc123",
"rootOrderId": 223456789,
"symbol": "BTC_JPY",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "0.02",
"executedSize": "0.02",
"price": "1430001",
"losscutPrice": "0",
"status": "EXECUTED",
"timeInForce": "FAS",
"timestamp": "2020-10-14T20:18:59.343Z"
},
{
"rootOrderId": 123456789,
"orderId": 123456789,
"symbol": "BTC",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "1",
"executedSize": "0",
"price": "900000",
"losscutPrice": "0",
"status": "CANCELED",
"cancelType": "USER",
"timeInForce": "FAS",
"timestamp": "2019-03-19T02:15:06.059Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.059Z"
}
Gets the order information of the specified order id or client order id.
Target: Spot and Margin trading
- Either
orderIdorclientOrderIdis required. Only one of them can be set at a time.
Request
GET /private/v1/orders
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| orderId | string | * |
Either orderId or clientOrderId is required.A comma-separated list of order ids. The maximum number of order ids is 10. |
| clientOrderId | string | * |
Either orderId or clientOrderId is required.*Only combinations of up to 36 single-byte alphanumeric characters can be used. *A comma-separated list of clientOrderIds. The maximum number of clientOrderIds is 10. The length limit applies to each clientOrderId. |
Response
| Property Name | Value | Description |
|---|---|---|
| rootOrderId | number | Root order id |
| orderId | number | Order id |
| clientOrderId | string | Client order id *Returned only when set |
| symbol | string | The handling symbols are here |
| side | string | Side: BUY SELL |
| orderType | string | Order Type: NORMAL LOSSCUT |
| executionType | string | Execution Type: MARKET LIMIT STOP |
| settleType | string | Settlement Type: OPEN CLOSE |
| size | string | Quantity of the order |
| executedSize | string | Executed quantity |
| price | string | Price of the order (This property is not included if the order is MARKET.) |
| losscutPrice | string | Margin Liquidation (It should be "0" if the order is Spot trading or losscutPrice is not set.) |
| status | string | Order Status: WAITING ORDERED MODIFYING CANCELLING CANCELED EXECUTED EXPIRED * WAITING is valid for stop limit orders. |
| cancelType | string | Cancel Type: USER POSITION_LOSSCUT INSUFFICIENT_BALANCE INSUFFICIENT_MARGIN ACCOUNT_LOSSCUT MARGIN_CALL MARGIN_CALL_LOSSCUT EXPIRED_FAK EXPIRED_FOK EXPIRED_SOK EXPIRED_SELFTRADE COLLATERAL_LIQUIDATION*It is returned if status is CANCELLING, CANCELED, or EXPIRED. |
| timeInForce | string | Time in force: FAK FAS FOK (SOK is Post-only order) |
| timestamp | string | Ordered timestamp |
Active Orders
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/activeOrders';
const parameters = '?symbol=BTC&page=1&count=10';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/activeOrders'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"symbol": "BTC",
"page": 1,
"count": 10
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/activeOrders"
parameters := "?symbol=BTC&page=1&count=10"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/activeOrders'
parameters = {
:symbol => 'BTC',
:page => 1,
:count => 10
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/activeOrders"
var parameters = "?symbol=BTC&page=1&count=10"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/activeOrders';
$parameters = '?symbol=BTC&page=1&count=10';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
active_orders().unwrap();
}
fn active_orders() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/activeOrders";
let parameters = json!({
"symbol": "BTC",
"page": 1,
"count": 10
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/activeOrders"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC"), ("page", Just "1"), ("count", Just "10")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = ActiveOrders();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> ActiveOrders()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/activeOrders";
const string parameters = "?symbol=BTC&page=1&count=10";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/activeOrders"
let parameters = "?symbol=BTC&page=1&count=10"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"currentPage": 1,
"count": 30
},
"list": [
{
"rootOrderId": 123456789,
"orderId": 123456789,
"clientOrderId": "abc123",
"symbol": "BTC",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "1",
"executedSize": "0",
"price": "840000",
"losscutPrice": "0",
"status": "ORDERED",
"timeInForce": "FAS",
"timestamp": "2019-03-19T01:07:24.217Z"
}
]
},
"responsetime": "2019-03-19T01:07:24.217Z"
}
Gets active orders list of the specified symbol.
Target: Spot and Margin trading
Request
GET /private/v1/activeOrders
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here |
| page | number | Optional | Target page: If a page is not specified, it will run assuming 1 is set. |
| count | number | Optional | Number of items that you want to get in 1 page: If a count is not specified, it will run assuming 100 (maximum value) is set. |
Response
| Property Name | Value | Description |
|---|---|---|
| rootOrderId | number | Root order id |
| orderId | number | Order id |
| clientOrderId | string | Client order id *Returned only when set |
| symbol | string | The handling symbols are here |
| side | string | Side: BUY SELL |
| orderType | string | Order Type: NORMAL LOSSCUT |
| executionType | string | Execution Type: MARKET LIMIT STOP |
| settleType | string | Settlement Type: OPEN CLOSE |
| size | string | Quantity of the order |
| executedSize | string | Executed quantity |
| price | string | Price of the order (This property is not included if the order is MARKET.) |
| losscutPrice | string | Margin Liquidation (It should be "0" if the order is Spot trading or losscutPrice is not set.) |
| status | string | Order Status: WAITING ORDERED MODIFYING CANCELLING * WAITING is valid for stop limit orders. |
| timeInForce | string | Time in force: FAK FAS FOK (SOK is Post-only order) |
| timestamp | string | Ordered timestamp |
Executions
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/executions';
const parameters = '?executionId=72123911,92123912';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/executions'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"executionId": "72123911,92123912"
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/executions"
parameters := "?executionId=72123911,92123912"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/executions'
parameters = {
:executionId => '72123911,92123912'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/executions"
var parameters = "?executionId=72123911,92123912"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/executions';
$parameters = '?executionId=72123911,92123912';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
executions().unwrap();
}
fn executions() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/executions";
let mut parameters = HashMap::new();
parameters.insert("executionId", "72123911,92123912");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/executions"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("executionId", Just "72123911,92123912")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Executions();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Executions()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/executions";
const string parameters = "?executionId=72123911,92123912";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/executions"
let parameters = "?executionId=72123911,92123912"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"executionId": 92123912,
"orderId": 223456789,
"clientOrderId": "abc123",
"positionId": 1234567,
"symbol": "BTC_JPY",
"side": "BUY",
"settleType": "OPEN",
"size": "0.02",
"price": "1900000",
"lossGain": "0",
"fee": "223",
"timestamp": "2020-11-24T21:27:04.764Z"
},
{
"executionId": 72123911,
"orderId": 123456789,
"positionId": 1234567,
"symbol": "BTC",
"side": "BUY",
"settleType": "OPEN",
"size": "0.7361",
"price": "877404",
"lossGain": "0",
"fee": "323",
"timestamp": "2019-03-19T02:15:06.081Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.081Z"
}
Gets executed order information of the specified order id, execution id or client order id.
Target: Spot and Margin trading
- Either
orderIdorexecutionIdorclientOrderIdis required. Only one of them can be set at a time.
Request
GET /private/v1/executions
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| orderId | number | * |
Either orderId or executionId or clientOrderId is required. |
| executionId | string | * |
Either orderId or executionId or clientOrderId is required. A comma-separated list of execution ids. The maximum number of execution ids is 10. |
| clientOrderId | string | * |
Either orderId or executionId or clientOrderId is required.*Only combinations of up to 36 single-byte alphanumeric characters can be used. *Only one clientOrderId can be specified. A comma-separated list cannot be used. |
Response
| Property Name | Value | Description |
|---|---|---|
| executionId | number | Execution id |
| orderId | number | Order id |
| clientOrderId | string | Client order id *Returned only when set |
| positionId | number | Position id *Margin trading only |
| symbol | string | The handling symbols are here |
| side | string | Side: BUY SELL |
| settleType | string | Settlement Type: OPEN CLOSE |
| size | string | Executed quantity |
| price | string | Executed price |
| lossGain | string | Settlement profit/loss |
| fee | string | Trade fee*It returns a positive value if Taker, a negative value if Maker. |
| timestamp | string | Executed timestamp |
Latest Executions
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/latestExecutions';
const parameters = '?symbol=BTC&page=1&count=100';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/latestExecutions'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"symbol": "BTC",
"page": 1,
"count": 100
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/latestExecutions"
parameters := "?symbol=BTC&page=1&count=100"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/latestExecutions'
parameters = {
:symbol => 'BTC',
:page => 1,
:count => 100
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/latestExecutions"
var parameters = "?symbol=BTC&page=1&count=100"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/latestExecutions';
$parameters = '?symbol=BTC&page=1&count=100';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
latest_executions().unwrap();
}
fn latest_executions() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/latestExecutions";
let parameters = json!({
"symbol": "BTC",
"page": 1,
"count": 100,
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/latestExecutions"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC"), ("page", Just "1"), ("count", Just "100")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = LatestExecutions();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> LatestExecutions()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/latestExecutions";
const string parameters = "?symbol=BTC&page=1&count=100";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/latestExecutions"
let parameters = "?symbol=BTC&page=1&count=100"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"currentPage": 1,
"count": 30
},
"list": [
{
"executionId": 72123911,
"orderId": 123456789,
"clientOrderId": "abc123",
"positionId": 1234567,
"symbol": "BTC",
"side": "BUY",
"settleType": "OPEN",
"size": "0.7361",
"price": "877404",
"lossGain": "0",
"fee": "323",
"timestamp": "2019-03-19T02:15:06.086Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.086Z"
}
Gets the latest executed order information.
Target: Spot and Margin trading
- This returns the last day of executed order information.
Request
GET /private/v1/latestExecutions
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here |
| page | number | Optional | Target page: If a page is not specified, it will run assuming 1 is set. |
| count | number | Optional | Number of items that you want to get in 1 page: If a count is not specified, it will run assuming 100 (maximum value) is set. |
Response
| Property Name | Value | Description |
|---|---|---|
| executionId | number | Execution id |
| orderId | number | Order id |
| clientOrderId | string | Client order id *Returned only when set |
| positionId | number | Position id *Margin trading only |
| symbol | string | The handling symbols are here |
| side | string | Side: BUY SELL |
| settleType | string | Settlement Type: OPEN CLOSE |
| size | string | Executed quantity |
| price | string | Executed price |
| lossGain | string | Settlement profit/loss |
| fee | string | Trade fee*It returns a positive value if Taker, a negative value if Maker. |
| timestamp | string | Executed timestamp |
Open Positions
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/openPositions';
const parameters = '?symbol=BTC_JPY&page=1&count=100';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/openPositions'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"symbol": "BTC_JPY",
"page": 1,
"count": 100
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/openPositions"
parameters := "?symbol=BTC_JPY&page=1&count=100"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/openPositions'
parameters = {
:symbol => 'BTC_JPY',
:page => 1,
:count => 100
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/openPositions"
var parameters = "?symbol=BTC_JPY&page=1&count=100"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/openPositions';
$parameters = '?symbol=BTC_JPY&page=1&count=100';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
open_positions().unwrap();
}
fn open_positions() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/openPositions";
let parameters = json!({
"symbol": "BTC_JPY",
"page": 1,
"count": 100,
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/openPositions"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC_JPY"), ("page", Just "1"), ("count", Just "100")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = OpenPositions();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> OpenPositions()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/openPositions";
const string parameters = "?symbol=BTC_JPY&page=1&count=100";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/openPositions"
let parameters = "?symbol=BTC_JPY&page=1&count=100"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"currentPage": 1,
"count": 30
},
"list": [
{
"positionId": 1234567,
"symbol": "BTC_JPY",
"side": "BUY",
"size": "0.22",
"orderdSize": "0",
"price": "876045",
"lossGain": "14",
"leverage": "4",
"losscutPrice": "766540",
"timestamp": "2019-03-19T02:15:06.094Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.095Z"
}
Gets a list of opened postions.
Target: Margin trading
Request
GET /private/v1/openPositions
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling margin symbols are here |
| page | number | Optional | Target page: If a page is not specified, it will run assuming 1 is set. |
| count | number | Optional | Number of items that you want to get in 1 page: If a count is not specified, it will run assuming 100 (maximum value) is set. |
Response
| Property Name | Value | Description |
|---|---|---|
| positionId | number | Position id |
| symbol | string | The handling margin symbols are here |
| side | string | Side: BUY SELL |
| size | string | Quantity of the position |
| orderdSize | string | Quantity of the order |
| price | string | Price of the position |
| lossGain | string | Settlement profit/loss |
| leverage | string | Leverage |
| losscutPrice | string | Margin Liquidation |
| timestamp | string | Executed timestamp |
Position Summary
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/positionSummary';
const parameters = '?symbol=BTC_JPY';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/positionSummary'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"symbol": "BTC_JPY"
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/positionSummary"
parameters := "?symbol=BTC_JPY"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/positionSummary'
parameters = {
:symbol => 'BTC_JPY'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/positionSummary"
var parameters = "?symbol=BTC_JPY"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/positionSummary';
$parameters = '?symbol=BTC_JPY';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
position_summary().unwrap();
}
fn position_summary() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/positionSummary";
let mut parameters = HashMap::new();
parameters.insert("symbol", "BTC_JPY");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/positionSummary"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC_JPY")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = PositionSummary();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> PositionSummary()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/positionSummary";
const string parameters = "?symbol=BTC_JPY";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/positionSummary"
let parameters = "?symbol=BTC_JPY"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"averagePositionRate": "715656",
"positionLossGain": "250675",
"side": "BUY",
"sumOrderQuantity": "2",
"sumPositionQuantity": "11.6999",
"symbol": "BTC_JPY"
}
]
},
"responsetime": "2019-03-19T02:15:06.102Z"
}
Gets a list of the position summary.
Target: Margin trading
- It is possible to get the position summary by symbol and side (BUY/SELL). If you want to get the position summary of all symbols, we recommend calling out it without a symbol.
Request
GET /private/v1/positionSummary
Parameters
- Parameter type: query
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Optional | If a symbol is not specified, it will return the position summary of all symbols. The handling margin symbols are here |
Response
| Property Name | Value | Description |
|---|---|---|
| averagePositionRate | string | Average price of the position |
| positionLossGain | string | Settlement profit/loss |
| side | string | Side: BUY SELL |
| sumOrderQuantity | string | Quantity of the order |
| sumPositionQuantity | string | Quantity of the position |
| symbol | string | The handling margin symbols are here |
Transfer
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/transfer';
const reqBody = JSON.stringify({
amount: "100000",
transferType: "WITHDRAWAL"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/transfer'
reqBody = {
"amount": "100000",
"transferType": "WITHDRAWAL"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/transfer"
reqBody := (`{
"amount": "100000",
"transferType": "WITHDRAWAL"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/transfer'
reqBody = {
:amount => '100000',
:transferType => 'WITHDRAWAL'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/transfer"
var reqBody = """
{"amount": "100000",
"transferType": "WITHDRAWAL"
}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/transfer';
$reqBody = '{
"amount": "100000",
"transferType": "WITHDRAWAL"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
transfer().unwrap();
}
fn transfer() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/transfer";
let parameters = json!({
"amount": "100000",
"transferType": "WITHDRAWAL"
});
let text = format!("{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/transfer"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"amount": "100000",
"transferType": "WITHDRAWAL"
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = transfer();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> transfer()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/transfer";
var reqBody = "{ \"amount\": \"100000\", " +
"\"transferType\": \"WITHDRAWAL\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/transfer"
let reqBodyStr = """
{
"amount": "100000",
"transferType": "WITHDRAWAL"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"transferredAmount": "100000"
}
],
"responsetime": "2019-03-19T02:15:06.055Z"
}
Transfer to crypto account or to forex account.
Maximum 1 transfer requests per 3 minute.
Request
POST /private/v1/account/transfer
Parameters
- Parameter content type:
application/json
| Property Name | Value | Description |
|---|---|---|
| amount | string | Transfer in Japanese yen |
| transferType | string | Account transfer type: WITHDRAWAL DEPOSIT |
Response
| Property Name | Value | Description |
|---|---|---|
| transferredAmount | string | Account transfer amount. |
Order
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/order';
const reqBody = JSON.stringify({
symbol: "BTC_JPY",
side: "BUY",
executionType: "LIMIT",
timeInForce: "FAS",
price: "430001",
losscutPrice: "30012",
size: "0.02"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/order'
reqBody = {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/order"
reqBody := (`{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/order'
reqBody = {
:symbol => 'BTC_JPY',
:side => 'BUY',
:executionType => 'LIMIT',
:timeInForce => 'FAS',
:price => '430001',
:losscutPrice => '30012',
:size => '0.02'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/order"
var reqBody = """
{"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/order';
$reqBody = '{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
order().unwrap();
}
fn order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/order";
let parameters = json!({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/order"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02" }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Order();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Order()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/order";
var reqBody = "{ \"symbol\": \"BTC_JPY\", " +
"\"side\": \"BUY\", " +
"\"executionType\": \"LIMIT\", " +
"\"timeInForce\": \"FAS\", " +
"\"price\": \"430001\", " +
"\"losscutPrice\": \"30012\", " +
"\"size\": \"0.02\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/order"
let reqBodyStr = """
{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": "637000",
"responsetime": "2019-03-19T02:15:06.108Z"
}
Creates a new order
Target: Spot and Margin trading
- Spot trade: BUY/SELL order
- Margin trade: Open new BUY/SELL order
Request
POST /private/v1/order
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling symbols are here |
| side | string | Required |
BUY SELL |
| executionType | string | Required |
MARKET LIMIT STOP |
| timeInForce | string | Optional | FAK FAS FOK ((SOK is Post-only order) LIMIT can only be specified )*If timeInForce is not specified, FAK for MARKET and STOP, FAS for LIMIT.Please refer to here for symbols for which SOK can be specified. |
| price | string | *Depending on executionType |
Required if LIMIT STOP. Not required if MARKET. |
| losscutPrice | string | Optional | Available only when order is margin trading and executionType is LIMIT or STOP. |
| size | string | Required |
|
| clientOrderId | string | Optional | An order identifier assigned by the client. *Only combinations of up to 36 single-byte alphanumeric characters can be used. *Case-sensitive. *It must be unique within the account, and a clientOrderId that has been used before cannot be reused. The clientOrderId of an order rejected with an error can be reused. *ERR-915 is returned if a clientOrderId that has already been used is specified. When ERR-915 is returned, you can check the result of the original request by calling Orders with the same clientOrderId. *If you use a UUID, specify it as 32 hexadecimal characters with the hyphens removed. |
| cancelBefore | bool | Optional | true Cancellation of active orders and creating new orders will occur at the same time based on the below rule:If order size > available balance:Existing orders will be cancelled from the oldest, and a new order will execute based on available balance. If order size ≦ available balance:Old orders will not be cancelled and a new order will be created. If cancelBefore is not specified, it will run assuming false is set. *You can only specify cancelBefore as true for orders which are spot trading, executionType: MARKET, timeInforce: FAK and side: SELL. |
Response
| Property Name | Value | Description |
|---|---|---|
| data | string | The new order's orderId |
Change Order
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/changeOrder';
const reqBody = JSON.stringify({
orderId: 2,
price: "1201",
losscutPrice: "1000"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/changeOrder'
reqBody = {
"orderId": 2,
"price": "1201",
"losscutPrice": "1000"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/changeOrder"
reqBody := (`{
"orderId": 2,
"price": "1201",
"losscutPrice": "1000"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/changeOrder'
reqBody = {
:orderId => 2,
:price => '1201',
:losscutPrice => '1000'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/changeOrder"
var reqBody = """
{"orderId": 2, "price": "1201", "losscutPrice": "1000"}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/changeOrder';
$reqBody = '{
orderId: 2,
price: "1201",
losscutPrice: "1000"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
change_order().unwrap();
}
fn change_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/changeOrder";
let parameters = json!({
"orderId": 2,
"price": "1201",
"losscutPrice": "1000",
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/changeOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"orderId": 2,
"price": "1201",
"losscutPrice": "1000" }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = ChangeOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> ChangeOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/changeOrder";
var reqBody = "{ \"orderId\": 2, " +
"\"price\": \"1201\", " +
"\"losscutPrice\": \"1000\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/changeOrder"
let reqBodyStr = """
{
"orderId": 2,
"price": "1201",
"losscutPrice": "1000"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T01:07:24.557Z"
}
Changes an order.
Target: Spot and Margin trading
Request
POST /private/v1/changeOrder
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| orderId | number | Required |
|
| price | string | Required |
|
| losscutPrice | string | Optional |
Cancel Order
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/cancelOrder';
const reqBody = JSON.stringify({
orderId: 2
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelOrder'
reqBody = {
"orderId": 2
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/cancelOrder"
reqBody := (`{
"orderId": 2
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelOrder'
reqBody = {
:orderId => 2
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/cancelOrder"
var reqBody = """
{"orderId": 2}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/cancelOrder';
$reqBody = '{
"orderId": 2
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
cancel_order().unwrap();
}
fn cancel_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/cancelOrder";
let parameters = json!({
"orderId": 2
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/cancelOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"orderId": 2 }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CancelOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CancelOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/cancelOrder";
var reqBody = "{ \"orderId\": 2 }";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/cancelOrder"
let reqBodyStr = """
{
"orderId": 2
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T01:07:24.557Z"
}
Cancels an order
Target: Spot and Margin trading
Request
POST /private/v1/cancelOrder
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| orderId | number | Required |
Cancel Orders
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/cancelOrders';
const reqBody = JSON.stringify({
orderIds: [1,2,3,4]
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelOrders'
reqBody = {
"orderIds": [1,2,3,4]
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/cancelOrders"
reqBody := (`{
"orderIds": [1,2,3,4]
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelOrders'
reqBody = {
:orderIds => [1,2,3,4]
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/cancelOrders"
var reqBody = """
{"orderIds": [1,2,3,4]}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/cancelOrders';
$reqBody = '{
"orderIds": [1,2,3,4]
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
cancel_orders().unwrap();
}
fn cancel_orders() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/cancelOrders";
let parameters = json!({
"orderIds": [1,2,3,4]
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/cancelOrders"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"orderIds": [1,2,3,4] }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CancelOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CancelOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/cancelOrders";
var reqBody = "{ \"orderIds\": [1,2,3,4] }";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/cancelOrders"
let reqBodyStr = """
{
"orderIds": [1,2,3,4]
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"failed": [
{
"message_code": "ERR-5122",
"message_string": "The request is invalid due to the status of the specified order.",
"orderId": 1
},
{
"message_code": "ERR-5122",
"message_string": "The request is invalid due to the status of the specified order.",
"orderId": 2
}
],
"success": [3,4]
},
"responsetime": "2019-03-19T01:07:24.557Z"
}
Cancels orders
Target: Spot and Margin trading
- It is possible to cancel max 10 orders
Request
POST /private/v1/cancelOrders
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| orderIds | array | Required |
Response
| Property Name | Value | Description |
|---|---|---|
| success | array | Order id that succeeded to accept cancellation |
| failed | array | Order id that failed to accept cancellation and failure information |
Cancel Bulk Order
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/cancelBulkOrder';
const reqBody = JSON.stringify({
symbols: ["BTC","BTC_JPY"],
side: "BUY",
settleType: "OPEN",
desc: true
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelBulkOrder'
reqBody = {
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": True
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/cancelBulkOrder"
reqBody := (`{
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelBulkOrder'
reqBody = {
:symbols => ['BTC','BTC_JPY'],
:side => 'BUY',
:settleType => 'OPEN',
:desc => true
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/cancelBulkOrder"
var reqBody = """
{"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/cancelBulkOrder';
$reqBody = '{
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
cancel_bulk_order().unwrap();
}
fn cancel_bulk_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/cancelBulkOrder";
let parameters = json!({
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/cancelBulkOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CancelOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CancelOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/cancelBulkOrder";
var reqBody = "{ \"symbols\": [\"BTC\",\"BTC_JPY\"], " +
"\"side\": \"BUY\", " +
"\"settleType\": \"OPEN\", " +
"\"desc\": true}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/cancelBulkOrder"
let reqBodyStr = """
{
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [637000,637002],
"responsetime": "2019-03-19T01:07:24.557Z"
}
Cancel bulk orders
Target: Spot and Margin trading
- After searching for cancellation target,Its cancel max 10 orders
Request
POST /private/v1/cancelBulkOrder
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbols | array | Required |
The handling symbols are here |
| side | string | Optional | BUY SELLWhen the parameter is specified, the order of the specified side targets cancellation |
| settleType | string | Optional | OPEN CLOSEWhen the parameter is specified, the spot order and the margin order of the specified settleType targets cancellation |
| desc | bool | Optional | true The order are cancelled in order from newest by order timefalse The order are cancelled in order from oldest by order timeIf the desc is not specified, Its value is false |
Response
| Property Name | Value | Description |
|---|---|---|
| data | array | Order id that succeeded to accept cancellation |
Close Order
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/closeOrder';
const reqBody = JSON.stringify({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/closeOrder'
reqBody = {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/closeOrder"
reqBody := (`{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/closeOrder'
reqBody = {
:symbol => 'BTC_JPY',
:side => 'BUY',
:executionType => 'LIMIT',
:timeInForce => 'FAS',
:price => '85201',
:settlePosition => [
{
:positionId => 1000342,
:size => '3.44'
}
]
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/closeOrder"
var reqBody = """
{"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/closeOrder';
$reqBody = '{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
close_order().unwrap();
}
fn close_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/closeOrder";
let parameters = json!({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/closeOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]}
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CloseOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CloseOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/closeOrder";
var reqBody = "{ \"symbol\": \"BTC_JPY\", " +
"\"side\": \"BUY\", " +
"\"executionType\": \"LIMIT\", " +
"\"timeInForce\": \"FAS\", " +
"\"price\": \"85201\", " +
"\"settlePosition\": [ { \"positionId\": 1000342, \"size\": \"3.44\" } ] }";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/closeOrder"
let reqBodyStr = """
{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": "637000",
"responsetime": "2019-03-19T01:07:24.557Z"
}
Closes a position
Target: Margin trading
Request
POST /private/v1/closeOrder
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling margin symbols are here |
| side | string | Required |
BUY SELL |
| executionType | string | Required |
MARKET LIMIT STOP |
| timeInForce | string | Optional | FAK FAS FOK ((SOK is Post-only order) LIMIT can only be specified )*If timeInForce is not specified, FAK for MARKET and STOP, FAS for LIMIT.Please refer to here for symbols for which SOK can be specified. |
| price | string | *Depending on executionType |
Required if LIMIT STOP. Not required if MARKET. |
| settlePosition.positionId | number | Required |
Allowed to set one position. |
| settlePosition.size | string | Required |
Allowed to set one position. |
| clientOrderId | string | Optional | An order identifier assigned by the client. *Only combinations of up to 36 single-byte alphanumeric characters can be used. *Case-sensitive. *It must be unique within the account, and a clientOrderId that has been used before cannot be reused. The clientOrderId of an order rejected with an error can be reused. *ERR-915 is returned if a clientOrderId that has already been used is specified. When ERR-915 is returned, you can check the result of the original request by calling Orders with the same clientOrderId. *If you use a UUID, specify it as 32 hexadecimal characters with the hyphens removed. |
| cancelBefore | bool | Optional | true Cancellation of active orders and creating new orders will occur at the same time based on the below rule:If order size > available balance:Existing orders will be cancelled from the oldest, and a new order will execute based on available balance. If order size ≦ available balance:Old orders will not be cancelled and a new order will be created. If cancelBefore is not specified, it will run assuming false is set. *You can only specify cancelBefore as true for orders which are executionType: MARKET, timeInforce: FAK and side: SELL.*cancelBefore cannot be set for active orders associated with multiple positions |
Response
| Property Name | Value | Description |
|---|---|---|
| data | string | The new closing order's orderId |
Close Bulk Order
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/closeBulkOrder';
const reqBody = JSON.stringify({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/closeBulkOrder'
reqBody = {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/closeBulkOrder"
reqBody := (`{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/closeBulkOrder'
reqBody = {
:symbol => 'BTC_JPY',
:side => 'BUY',
:executionType => 'LIMIT',
:timeInForce => 'FAS',
:price => '85201',
:size => '3.44'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/closeBulkOrder"
var reqBody = """
{"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/closeBulkOrder';
$reqBody = '{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
close_bulk_order().unwrap();
}
fn close_bulk_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/closeBulkOrder";
let parameters = json!({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/closeBulkOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44" }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CloseBulkOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CloseBulkOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/closeBulkOrder";
var reqBody = "{ \"symbol\": \"BTC_JPY\", " +
"\"side\": \"BUY\", " +
"\"executionType\": \"LIMIT\", " +
"\"timeInForce\": \"FAS\", " +
"\"price\": \"85201\", " +
"\"size\": \"3.44\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/closeBulkOrder"
let reqBodyStr = """
{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": "637000",
"responsetime": "2019-03-19T01:07:24.557Z"
}
Closes bulk orders.
Target: Margin trading
Request
POST /private/v1/closeBulkOrder
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| symbol | string | Required |
The handling margin symbols are here |
| side | string | Required |
BUY SELL |
| executionType | string | Required |
MARKET LIMIT STOP |
| timeInForce | string | Optional | FAK FAS FOK ((SOK is Post-only order) LIMIT can only be specified )*If timeInForce is not specified, FAK for MARKET and STOP, FAS for LIMIT.Please refer to here for symbols for which SOK can be specified. |
| price | string | *Depending on executionType |
Required if LIMIT STOP. Not required if MARKET. |
| size | string | Required |
|
| clientOrderId | string | Optional | An order identifier assigned by the client. *Only combinations of up to 36 single-byte alphanumeric characters can be used. *Case-sensitive. *It must be unique within the account, and a clientOrderId that has been used before cannot be reused. The clientOrderId of an order rejected with an error can be reused. *ERR-915 is returned if a clientOrderId that has already been used is specified. When ERR-915 is returned, you can check the result of the original request by calling Orders with the same clientOrderId. *If you use a UUID, specify it as 32 hexadecimal characters with the hyphens removed. |
Response
| Property Name | Value | Description |
|---|---|---|
| data | string | The new closing bulk order's orderId |
Change Margin Liquidation
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/changeLosscutPrice';
const reqBody = JSON.stringify({
"positionId": 305885,
"losscutPrice": "750000"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/changeLosscutPrice'
reqBody = {
"positionId": 305885,
"losscutPrice": "750000"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/changeLosscutPrice"
reqBody := (`{
"positionId": 305885,
"losscutPrice": "750000"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/changeLosscutPrice'
reqBody = {
:positionId => 305885,
:losscutPrice => '750000'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/changeLosscutPrice"
var reqBody = """
{"positionId": 305885, "losscutPrice": "750000"}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/changeLosscutPrice';
$reqBody = '{
"positionId": 305885,
"losscutPrice": "750000"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
change_losscut_price().unwrap();
}
fn change_losscut_price() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/changeLosscutPrice";
let parameters = json!({
"positionId": 305885,
"losscutPrice": "750000"
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/changeLosscutPrice"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"positionId": 305885,
"losscutPrice": "750000" }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = ChangeLosscutPrice();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> ChangeLosscutPrice()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/changeLosscutPrice";
var reqBody = "{ \"positionId\": 305885, " +
"\"losscutPrice\": \"750000\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/changeLosscutPrice"
let reqBodyStr = """
{
"positionId": 305885,
"losscutPrice": "750000"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T01:07:24.557Z"
}
Changes the margin liquidation of the specified position.
Target: Margin trading
Request
POST /private/v1/changeLosscutPrice
Parameters
- Parameter content type:
application/json
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| positionId | number | Required |
|
| losscutPrice | string | Required |
Private WebSocket API
- A ping will be sent from the server to a client once per minute. If there's no response (pong) from a client 3 consecutive times, then the WebSocket will be disconnected automatically.
- Using a Private API for authentication in order to obtain, extend and remove the access token.
- A Private WebSocket API's URL will be
Endpoint of Private WebSocket API + Access token
e.g.wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx
Create Access Token
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/ws-auth';
const reqBody = JSON.stringify({})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/ws-auth"
reqBody := (`{}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/ws-auth"
var reqBody = """{}"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/ws-auth';
$reqBody = '{}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
ws_auth_post().unwrap();
}
fn ws_auth_post() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/ws-auth";
let parameters = json!({});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/ws-auth"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {}
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WsAuthPost();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WsAuthPost()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/ws-auth";
var reqBody = "{}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/ws-auth"
let reqBodyStr = """
{}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": "xxxxxxxxxxxxxxxxxxxx",
"responsetime": "2019-03-19T02:15:06.102Z"
}
Gets an access token to call Private WebSocket API.
- The expiration time of access token is 60 minutes.
- The maximum number of access tokens is 5.
- If the number of issued tokens exceeds the maximum number of tokens, the tokens will be deleted in order of expiration time.
- To use the API with the existing API keys, open your membership site > API > 編集 (Edit) > APIキーの編集 (API key setting) screen and click "約定情報通知(WebSocket)" (Execution Notifications), "注文情報通知(WebSocket)" (Order Notifications), "ポジション情報通知(WebSocket)" (Position Notifications) or "ポジションサマリー情報通知(WebSocket)" (Position Summary Notifications) to call the Create Access Token API.
*Please set the API key permission before obtaining the access token.
Request
POST /private/v1/ws-auth
Parameters
None
Response
| Property Name | Value | Description |
|---|---|---|
| data | string | Access token |
Extend Access Token
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'PUT';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/ws-auth';
const reqBody = JSON.stringify({
"token": "xxxxxxxxxxxxxxxxxxxx"
})
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.put(endPoint + path, reqBody, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'PUT'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {
"token": "xxxxxxxxxxxxxxxxxxxx"
}
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.put(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "PUT"
endPoint := "https://api.coin.z.com/private"
path := "/v1/ws-auth"
reqBody := (`{
"token": "xxxxxxxxxxxxxxxxxxxx"
}`)
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'PUT'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {
:token => 'xxxxxxxxxxxxxxxxxxxx'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Put.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "PUT"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/ws-auth"
var reqBody = """
{"token": "xxxxxxxxxxxxxxxxxxxx"}
"""
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'PUT';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/ws-auth';
$reqBody = '{
"token": "xxxxxxxxxxxxxxxxxxxx"
}';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
ws_auth_put().unwrap();
}
fn ws_auth_put() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "PUT";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/ws-auth";
let parameters = json!({
"token": "xxxxxxxxxxxxxxxxxxxx"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.put(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "PUT"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/ws-auth"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"token": "xxxxxxxxxxxxxxxxxxxx" }
|]
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "PUT"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WsAuthPut();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WsAuthPut()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "PUT";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/ws-auth";
var reqBody = "{ \"token\": \"xxxxxxxxxxxxxxxxxxxx\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "PUT"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/ws-auth"
let reqBodyStr = """
{
"token": "xxxxxxxxxxxxxxxxxxxx"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T02:15:06.102Z"
}
Extends the expiration time of an access token.
- The new expiration time is 60 minutes.
Request
PUT /private/v1/ws-auth
Parameters
- Parameter type: JSON
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| token | string | Required |
Access token |
Delete Access Token
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'DELETE';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/ws-auth';
const reqBody = JSON.stringify({
"token": "xxxxxxxxxxxxxxxxxxxx"
})
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
},
"data": reqBody,
};
axios.delete(endPoint + path, options)
.then(function (response) {
console.log(JSON.stringify(response.data, null, 2));
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'DELETE'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {
"token": "xxxxxxxxxxxxxxxxxxxx"
}
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.delete(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "DELETE"
endPoint := "https://api.coin.z.com/private"
path := "/v1/ws-auth"
reqBody := (`{
"token": "xxxxxxxxxxxxxxxxxxxx"
}`)
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'DELETE'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {
:token => 'xxxxxxxxxxxxxxxxxxxx'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Delete.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "DELETE"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/ws-auth"
var reqBody = """
{"token": "xxxxxxxxxxxxxxxxxxxx"}
"""
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'DELETE';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/ws-auth';
$reqBody = '{
"token": "xxxxxxxxxxxxxxxxxxxx"
}';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
ws_auth_delete().unwrap();
}
fn ws_auth_delete() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "DELETE";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/ws-auth";
let parameters = json!({
"token": "xxxxxxxxxxxxxxxxxxxx"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.delete(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "DELETE"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/ws-auth"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"token": "xxxxxxxxxxxxxxxxxxxx" }
|]
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "DELETE"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WsAuthDelete();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WsAuthDelete()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "DELETE";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/ws-auth";
var reqBody = "{ \"token\": \"xxxxxxxxxxxxxxxxxxxx\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "DELETE"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/ws-auth"
let reqBodyStr = """
{
"token": "xxxxxxxxxxxxxxxxxxxx"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T02:15:06.102Z"
}
Deletes an access token.
Request
DELETE /private/v1/ws-auth
Parameters
- Parameter type: JSON
| Parameter | Type | Required | Available Values |
|---|---|---|---|
| token | string | Required |
Access token |
Execution Notifications
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "executionEvents"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "executionEvents"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "executionEvents"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "executionEvents"
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "executionEvents"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// Required installing ratchet/pawl with a command below before running the code.
// composer require ratchet/pawl
require __DIR__ . '/vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop);
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$connector("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "executionEvents" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/private/v1/xxxxxxxxxxxxxxxxxxxx" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = ExecutionEvents();
task.Wait();
}
static async Task ExecutionEvents()
{
const string endpoint = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "executionEvents"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel": "executionEvents",
"orderId": 123456789,
"clientOrderId": "abc123",
"executionId": 72123911,
"symbol": "BTC_JPY",
"settleType": "OPEN",
"executionType": "LIMIT",
"side": "BUY",
"executionPrice": "877404",
"executionSize": "0.5",
"positionId": 123456789,
"orderTimestamp": "2019-03-19T02:15:06.081Z",
"executionTimestamp": "2019-03-19T02:15:06.081Z",
"lossGain": "0",
"fee": "323",
"orderPrice": "877200",
"orderSize": "0.8",
"orderExecutedSize": "0.7",
"timeInForce": "FAS",
"msgType": "ER"
}
Receives latest execution events notifications.
After subscribe, latest execution events notification will be sent.
Parameters
- Parameter type: JSON
| Property Name | Type | Required | Available Values |
|---|---|---|---|
| command | string | Required |
subscribe unsubscribe |
| channel | string | Required |
executionEvents |
Response
| Property Name | Value | Description |
|---|---|---|
| channel | string | executionEvents |
| orderId | number | Order id |
| clientOrderId | string | Client order id *Returned only when set |
| executionId | number | Execution id |
| symbol | string | The handling symbols are here |
| settleType | string | Settlement Type: OPEN CLOSE |
| executionType | string | Execution Type: MARKET LIMIT STOP |
| side | string | Side: BUY SELL |
| executionPrice | string | Executed price |
| executionSize | string | Executed quantity |
| positionId | number | Position id *Margin trading only |
| orderTimestamp | string | Ordered timestamp |
| executionTimestamp | string | Executed timestamp |
| lossGain | string | Settlement profit/loss |
| fee | string | Trade fee*It returns a positive value if Taker, a negative value if Maker. |
| orderPrice | string | Price of the order (This property is not included if the order is MARKET.) |
| orderSize | string | Ordered size |
| orderExecutedSize | string | Excecuted size of the order |
| timeInForce | string | Time in force: FAK FAS FOK (SOK is Post-only order) |
| msgType | string | Message Type: ER |
- There is no Response when
unsubscribeis requested.
Order Notifications
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "orderEvents"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "orderEvents"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "orderEvents"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "orderEvents"
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "orderEvents"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// Required installing ratchet/pawl with a command below before running the code.
// composer require ratchet/pawl
require __DIR__ . '/vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop);
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$connector("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "orderEvents" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/private/v1/xxxxxxxxxxxxxxxxxxxx" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = OrderEvents();
task.Wait();
}
static async Task OrderEvents()
{
const string endpoint = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "orderEvents"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel": "orderEvents",
"orderId": 123456789,
"clientOrderId": "abc123",
"symbol": "BTC_JPY",
"settleType": "OPEN",
"executionType": "LIMIT",
"side": "BUY",
"orderStatus": "CANCELED",
"cancelType": "USER",
"orderTimestamp": "2019-03-19T02:15:06.081Z",
"orderPrice": "876045",
"orderSize": "0.8",
"orderExecutedSize": "0",
"losscutPrice": "0",
"timeInForce": "FAS",
"msgType": "NOR"
}
Receives latest order events notifications.
After subscribe, latest order events notification will be sent.
Parameters
- Parameter type: JSON
| Property Name | Type | Required | Available Values |
|---|---|---|---|
| command | string | Required |
subscribe unsubscribe |
| channel | string | Required |
orderEvents |
Response
| Property Name | Value | Description |
|---|---|---|
| channel | string | orderEvents |
| orderId | number | Order id |
| clientOrderId | string | Client order id *Returned only when set |
| symbol | string | The handling symbols are here |
| settleType | string | Settlement Type: OPEN CLOSE LOSS_CUT |
| executionType | string | Execution Type: MARKET LIMIT STOP |
| side | string | Side: BUY SELL |
| orderStatus | string | Order Status: WAITING ORDERED CANCELED EXPIRED * WAITING is valid for stop limit orders. |
| cancelType | string | Cancel Type: USER POSITION_LOSSCUT INSUFFICIENT_BALANCE INSUFFICIENT_MARGIN ACCOUNT_LOSSCUT MARGIN_CALL MARGIN_CALL_LOSSCUT EXPIRED_FAK EXPIRED_FOK EXPIRED_SOK EXPIRED_SELFTRADE COLLATERAL_LIQUIDATION CLOSED_ORDER *It is returned if orderStatus is CANCELED or EXPIRED.Cancel Type: SOK_TAKER PRICE_LIMIT *It is returned if orderStatus is ORDERED. |
| orderTimestamp | string | Ordered timestamp |
| orderPrice | string | Price of the order (This property is not included if the order is MARKET.) |
| orderSize | string | Ordered size |
| orderExecutedSize | string | Excecuted size of the order |
| losscutPrice | string | Margin Liquidation (It should be "0" if the order is Spot trading or losscutPrice is not set.) |
| timeInForce | string | Time in force: FAK FAS FOK (SOK is Post-only order) |
| msgType | string | Message Type: NOR ROR COR ER |
- There is no Response when
unsubscribeis requested.
Position Notifications
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "positionEvents"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "positionEvents"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "positionEvents"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "positionEvents"
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "positionEvents"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// Required installing ratchet/pawl with a command below before running the code.
// composer require ratchet/pawl
require __DIR__ . '/vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop);
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$connector("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "positionEvents" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/private/v1/xxxxxxxxxxxxxxxxxxxx" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = PositionEvents();
task.Wait();
}
static async Task PositionEvents()
{
const string endpoint = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "positionEvents"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel": "positionEvents",
"positionId": 1234567,
"symbol": "BTC_JPY",
"side": "BUY",
"size": "0.22",
"orderdSize": "0",
"price": "876045",
"lossGain": "14",
"leverage": "4",
"losscutPrice": "766540",
"timestamp": "2019-03-19T02:15:06.094Z",
"msgType": "OPR"
}
Receives latest position events notifications.
After subscribe, latest position events notification will be sent.
Parameters
- Parameter type: JSON
| Property Name | Type | Required | Available Values |
|---|---|---|---|
| command | string | Required |
subscribe unsubscribe |
| channel | string | Required |
positionEvents |
Response
| Property Name | Value | Description |
|---|---|---|
| channel | string | positionEvents |
| positionId | number | Position id |
| symbol | string | The handling margin symbols are here |
| side | string | Side: BUY SELL |
| size | string | Quantity of the position |
| orderdSize | string | Quantity of the order |
| price | string | Price of the position |
| lossGain | string | Settlement profit/loss |
| leverage | string | Leverage |
| losscutPrice | string | Margin Liquidation |
| timestamp | string | Executed timestamp |
| msgType | string | Message Type: OPR UPR ULR CPR |
- There is no Response when
unsubscribeis requested.
Position Summary Notifications
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "positionSummaryEvents"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "positionSummaryEvents"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "positionSummaryEvents"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "positionSummaryEvents"
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "positionSummaryEvents"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// Required installing ratchet/pawl with a command below before running the code.
// composer require ratchet/pawl
require __DIR__ . '/vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop);
$connector = new \Ratchet\Client\Connector($loop, $reactConnector);
$connector("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "positionSummaryEvents" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/private/v1/xxxxxxxxxxxxxxxxxxxx" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = PositionSummaryEvents();
task.Wait();
}
static async Task PositionSummaryEvents()
{
const string endpoint = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "positionSummaryEvents"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel":"positionSummaryEvents",
"symbol":"BTC_JPY",
"side":"BUY",
"averagePositionRate":"1014484",
"positionLossGain":"18",
"sumOrderQuantity":"0.01",
"sumPositionQuantity":"0.03",
"timestamp":"2020-06-24T09:53:19.702Z",
"msgType":"UPDATE"
}
Receives latest position summary events notifications.
After subscribe, latest position summary events notification will be sent.
Parameters
- Parameter type: JSON
| Property Name | Type | Required | Available Values |
|---|---|---|---|
| command | string | Required |
subscribe unsubscribe |
| channel | string | Required |
positionSummaryEvents |
| option | string | Optional | PERIODIC*If option is specified, it will send data every 5 seconds. *If you request multiple subscriptions, only the latest request will be valid. |
Response
| Property Name | Value | Description |
|---|---|---|
| channel | string | positionSummaryEvents |
| symbol | string | The handling margin symbols are here |
| side | string | Side: BUY SELL |
| averagePositionRate | string | Average price of the position |
| positionLossGain | string | Settlement profit/loss |
| sumOrderQuantity | string | Quantity of the order |
| sumPositionQuantity | string | Quantity of the position |
| timestamp | string | Timestamp of the notifications |
| msgType | string | Message Type: INIT UPDATE PERIODIC |
- There is no Response when
unsubscribeis requested.
Historical Data
You can download the historical data (.CSV file) here.
References
This section explains about codes, which are API parameters and response values.
Parameters
This section explains about parameters and their details.
symbol: Trading symbol
| Value | Description | Release date |
|---|---|---|
| BTC | Bitcoin (Spot trading) | 2018/09/05 |
| ETH | Ethereum (Spot trading) | 2019/01/30 |
| BCH | BitcoinCash (Spot trading) | 2019/01/30 |
| LTC | Litecoin (Spot trading) | 2019/01/30 |
| XRP | Ripple (Spot trading) | 2019/01/30 |
| XLM | Stellar (Spot trading) | 2021/08/18 |
| DOT | Polkadot (Spot trading) | 2022/06/08 |
| ATOM | Cosmos (Spot trading) | 2022/06/08 |
| FCR | FCR Coin (Spot trading) | 2022/05/18 |
| ADA | Cardano (Spot trading) | 2022/07/13 |
| LINK | Chainlink (Spot trading) | 2022/07/13 |
| DOGE | Dogecoin (Spot trading) | 2023/08/05 |
| SOL | Solana (Spot trading) | 2023/08/05 |
| ASTR | Astar (Spot trading) | 2023/03/22 |
| NAC | NOT A HOTEL COIN (Spot trading) | 2024/12/13 |
| SUI | Sui (Spot trading) | 2026/01/17 |
| WILD | Wilder World (Spot trading) | 2026/03/21 |
| MNT | Mantle (Spot trading) | 2026/10/31 |
| BNB | Build and Build (Spot trading) | 2026/10/31 |
| Value | Description | Release date |
|---|---|---|
| BTC_JPY | Bitcoin-Japanese Yen (Margin trading) | 2018/09/05 |
| ETH_JPY | Ethereum-Japanese Yen (Margin trading) | 2019/01/30 |
| BCH_JPY | BitcoinCash-Japanese Yen (Margin trading) | 2019/01/30 |
| LTC_JPY | Litecoin-Japanese Yen (Margin trading) | 2019/01/30 |
| XRP_JPY | Ripple-Japanese Yen (Margin trading) | 2019/01/30 |
| DOT_JPY | Polkadot-Japanese Yen (Margin trading) | 2024/04/13 |
| ATOM_JPY | Cosmos-Japanese Yen (Margin trading) | 2024/04/13 |
| ADA_JPY | Cardano-Japanese Yen (Margin trading) | 2024/04/13 |
| LINK_JPY | Chainlink-Japanese Yen (Margin trading) | 2024/04/13 |
| DOGE_JPY | Dogecoin-Japanese Yen (Margin trading) | 2024/04/13 |
| SOL_JPY | Solana-Japanese Yen (Margin trading) | 2024/04/13 |
| SUI_JPY | Sui-Japanese Yen (Margin trading) | 2026/01/17 |
| MNT_JPY | Mantle-Japanese Yen (Margin trading) | 2026/10/31 |
| BNB_JPY | Build and Build-Japanese Yen (Margin trading) | 2026/10/31 |
symbol: Asset Ticker Symbol
| Value | Description |
|---|---|
| JPY | Japanese Yen |
| BTC | Bitcoin (OTC Spot) |
| ETH | Ethereum (OTC Spot) |
| BCH | BitcoinCash (OTC Spot) |
| LTC | Litecoin (OTC Spot) |
| XRP | Ripple (OTC Spot) |
| XLM | Stellar Lumens (OTC Spot) |
| OMG | OMG |
| DOT | Polkadot (OTC Spot) |
| ATOM | Cosmos (OTC Spot) |
| FCR | FCR Coin (Exchange) |
| ADA | Cardano (OTC Spot) |
| LINK | Chainlink (OTC Spot) |
| DOGE | Dogecoin (OTC Spot) |
| SOL | Solana (OTC Spot) |
| ASTR | Astar (Exchange) |
| NAC | NOT A HOTEL COIN (Exchange) |
| AVAX | AVAX (OTC Spot) |
| WILD | Wilder World (Exchange) |
| SUI | Sui (OTC Spot) |
| ZPG | ZPG (OTC Spot) |
| ZPGAG | ZPGAG (OTC Spot) |
| ZPGPT | ZPGPT (OTC Spot) |
| MNT | Mantle (OTC Spot) |
| BNB | Build and Build (OTC Spot) |
side: Side
| Value | Description |
|---|---|
| BUY | Buy |
| SELL | Sell |
executionType: Execution Type
| Value | Description |
|---|---|
| MARKET | Market order |
| LIMIT | Limit order |
| STOP | Stop limit order |
timeInForce: Time in force
| Value | Description |
|---|---|
| FAK | Fill and kill. When an order can only be partially executed and its remaining part expires. |
| FAS | Fill and store. When an order can only be partially executed and its remaining part is still valid. |
| FOK | Fill or kill. If an order is not executed immediately, the order will expire. |
| SOK | Store or kill. If a limit order is not maker, the order will expire. (Post-only order) |
Symbols for which SOK(Post-Only) can be specified in the timeInForce parameter
| Service | Description |
|---|---|
| Spot Trading | All symbols can be specified |
| Margin Trading | All symbols can be specified |
HTTP Status Codes
Status Codes
| Status Code | Description |
|---|---|
| 0 | A response for successful API processing. |
Error Codes
| Error Code | Description |
|---|---|
| ERR-70 | It will be returned when the BUY/SELL side of the specified position is incorrect in the settlement order. |
| ERR-189 | The quantity of your close order exceeds your open position. |
| ERR-200 | There are existing active orders and your order exceeds the maximum quantity that can be ordered. Please change the quantity to order or cancel an active order in order to create a new close order. |
| ERR-201 | Insufficient funds. |
| ERR-208 | The quantity of your order exceeds your available balance. Please check your balance or active orders. Also returned by CryptoCurrency withdrawal when the sendAmount plus the fee exceeds your balance of the symbol. |
| ERR-254 | The specified position does not exist. |
| ERR-422 | It will be returned when the specified position does not exist in the close bulk order. Please make sure that the symbol or side (BUY/SELL) is correct. |
| ERR-423 | It will be returned when the order quantity exceeds the total quantity of the positions that can be closed in the close bulk order. |
| ERR-430 | Invalid parameter (orderId/executionId) in executions. |
| ERR-554 | The server is unavailable. |
| ERR-626 | The server is busy. Please retry later. |
| ERR-635 | The number of active orders has exceeded the limit. Please cancel an active order to create a new order. |
| ERR-682 | A margin call has occurred. The operation cannot be executed. |
| ERR-683 | Margin call processing is in progress. The operation cannot be executed. |
| ERR-754 | Not enough transferable amount to transfer. |
| ERR-846 | The difference between fromTimestamp and toTimestamp is greater than the maximum of 30 minutes. |
| ERR-913 | Sell the entire collateral quantity, or sell so that the remaining collateral quantity after the sale is at least the minimum collateral quantity. |
| ERR-915 | Invalid clientOrderId in order (already used). |
| ERR-5003 | The API usage limits are exceeded. |
| ERR-5004 | An unexpected response was received from backend server. Execution status unknown. The request may have been accepted, so check the result by calling CryptoCurrency withdrawal status with clientOrderId (or with orderId for a cancellation request). Check the result in the same way when the response times out. |
| ERR-5007 | The API-TIMESTAMP is not set in the request header, or the value of API-TIMESTAMP is not a numeric value. Please ensure that the API-TIMESTAMP is set in the request header, and that the value is a numeric representation of a UNIX timestamp in milliseconds. |
| ERR-5008 | The API-TIMESTAMP set in the request header is later than the system time of the API. Please try updating the system time. |
| ERR-5009 | The API-TIMESTAMP set in the request header is earlier than the system time of the API. Please try updating the system time. |
| ERR-5010 | The API-SIGN (Signature) is invalid. Please check Authentication. |
| ERR-5011 | The API-KEY is empty. Please check Authentication. |
| ERR-5012 | The API authentication is invalid. |
| ERR-5014 | The membership agreement has not been completed. |
| ERR-5016 | The history query timed out. Please retry, or narrow the date range. |
| ERR-5106 | The request parameter is invalid. |
| ERR-5111 | Invalid timeInForce values. Please see the possible timeInForce values in Order, Close Order and Close Bulk Order. |
| ERR-5114 | The number of decimals exceeds the maximum precision. Please check the minimum order value here. |
| ERR-5118 | Returned when LosscutPrice cannot be specified in the request body. |
| ERR-5121 | Impossible to order due to order price is too low. |
| ERR-5122 | The specified order can not be changed or canceled (already MODIFYING, CANCELLING, CANCELED, EXECUTED or EXPIRED). Orders can be changed or canceled only in ORDERED (WAITING for stop limit orders) status. |
| ERR-5123 | The specified order doesn't exist. |
| ERR-5125 | Returned when there is API restriction. |
| ERR-5126 | The amount exceeds the maximum order amount or is less than the minimum order amount. Please check the trading rules here. |
| ERR-5127 | Your API connection is restricted. |
| ERR-5129 | Stop limit orders cannot be specified a price that will be executed immediately. |
| ERR-5130 | The orderID(s) exceeds the number that can be specified. |
| ERR-5132 | The executionID(s) exceeds the number that can be specified. |
| ERR-5133 | Account transfers are not possible due to transfer restrictions. |
| ERR-5135 | FxAccount not opened. Please try again ofter opening FxAccount. |
| ERR-5138 | The withdrawal address is invalid. |
| ERR-5139 | The withdrawal address is not yet available. |
| ERR-5140 | The deposit address has not been issued. |
| ERR-5141 | Withdrawal is restricted within one month of account opening. |
| ERR-5142 | Failed to get the rate. |
| ERR-5144 | The withdrawal cannot be canceled. |
| ERR-5145 | The clientOrderID(s) exceeds the number that can be specified. |
| ERR-5146 | Withdrawal of this symbol is suspended. |
| ERR-5147 | Customer information is not registered. |
| ERR-5148 | This operation is restricted because the identification document has expired. |
| ERR-5149 | This account cannot use the withdrawal service. |
| ERR-5150 | Withdrawal is limited by a recent Pay-easy deposit. |
| ERR-5151 | This account is currently under trade restrictions. |
| ERR-5152 | The destination account is closed. |
| ERR-5153 | The purpose of the withdrawal is invalid. |
| ERR-5154 | The location in tradeDetails (a nonexistent country or region code, an invalid combination of regionCode and cityName, or a missing location) or itemName is invalid. A country or region to which we do not allow withdrawals does not return ERR-5154; after acceptance, the request is rejected (REJECTED) in the review of the withdrawal purpose. |
| ERR-5155 | Returned when sendAmount in a CryptoCurrency withdrawal request to an external address is below the minimum withdrawal amount. The minimum withdrawal amount does not apply to withdrawals to a GMO Coin account (internal withdrawal). ERR-5155 is not returned when you specify your entire holding for a symbol other than DOT; ERR-208 is returned instead because the balance does not cover the fee. |
| ERR-5156 | This internal withdrawal requires a review and cannot be accepted. |
| ERR-5157 | Exceeds the daily withdrawal limit. |
| ERR-5158 | The specified withdrawal was not found. |
| ERR-5201 | A response code that when Public/Private API is called while the service is in a regular maintenance. CryptoCurrency withdrawal APIs are accepted while the Service Status is MAINTENANCE; they are not accepted, and this error is returned, only during the regular maintenance of the whole service. |
| ERR-5202 | A response code that when Public/Private API is called while the service is in a emergency maintenance. |
| ERR-5203 | A response code that when order or change order is called while the service is pre-open. * CryptoCurrency withdrawal APIs (CryptoCurrency withdrawal, Cancel CryptoCurrency withdrawal, CryptoCurrency withdrawal status, Registered withdrawal addresses, Withdrawal purposes, Countries and regions, and States and provinces) are accepted and this error is not returned while the Service Status is PREOPEN or MAINTENANCE (during the regular maintenance of the whole service they are not accepted and ERR-5201 is returned). |
| ERR-5204 | The request API PATH is invalid. |
| ERR-5206 | The limits of changing order for each order are exceeded. If you would like further changes for the order, please cancel the order and create a brand new order. |
| ERR-5207 | Invalid symbol, interval or date values. |
| ERR-5208 | OrderId(s) and executionId(s) cannot be used at the same time. |
| ERR-5212 | OrderId and ClientOrderId cannot be used at the same time. |
| ERR-5230 | ExecutionId and ClientOrderId cannot be used at the same time. |
Feedback
We'd like to hear some feedback about our API. Your feedback will be carefully reviewed by our development team, to be developed and released sequentially.
Please click here to contact us about any requests you may have about the API.
*Please click here to contact us about API inquiries. We may take some time to respond depending on the inquiry. Thank you for your understanding.
Changelog
2026
2026-11-14 New
- Added that each CryptoCurrency withdrawal API can be called only with an API key that has the permission for that API.
- Added the permissions for the CryptoCurrency withdrawal APIs and notes on API keys with those permissions.
- Added new error codes: ERR-5004, ERR-5138 to ERR-5142, ERR-5144 and ERR-5146 to ERR-5158
- ERR-208 and ERR-915 are now also returned by CryptoCurrency withdrawal, ERR-5003 is now also returned when CryptoCurrency withdrawal requests for the same symbol exceed once per second, and ERR-5212 is now also returned by CryptoCurrency withdrawal status.
- ERR-5201 and ERR-5203 now note that the CryptoCurrency withdrawal APIs are accepted while the Service Status is PREOPEN or MAINTENANCE.
2026-11-07
2026-10-31
2026-10-10
- Added a new request parameter: clientOrderId
- Added a new request parameter: clientOrderId
- Added a new request parameter: clientOrderId
- Added a new request parameter and response property: clientOrderId
- Added a new request parameter and response property: clientOrderId
- Added a new response property: clientOrderId
- Added a new response property: clientOrderId
- Added a new response property: clientOrderId
- Added a new response property: clientOrderId
- Added new error codes: ERR-915, ERR-5130, ERR-5132, ERR-5145, ERR-5212 and ERR-5230
2026-10-03
- Changed: Private API limits
- Tier 3 (last week trading volume of 2 billion or more, 50 GET and 50 POST requests per second) has been added, and the trading volume requirements for Tier 2 have been changed to 1 billion or more and under 2 billion.
2026-08-29
2026-07-25
- Added a new cancelType:
COLLATERAL_LIQUIDATIONto the Response section.
- Added a new cancelType:
COLLATERAL_LIQUIDATIONto the Response section.
- Clarified that availableAmount is the trading capacity for leverage trading, including the collateral crypto-asset value.
- Added a new response property: availableAmountForSpot
- Added a new response property: cryptoShortfallStatus
- Added a new error code: ERR-913
2026-07-18
2026-06-27
2026-06-06
2026-04-18
2026-03-21
2026-01-17
2025
2025-10-25
2025-10-04
2025-08-02
2025-06-28
2024
2024-12-13
2024-11-02
2024-06-01
2024-04-13
- Added a new symbol:
DOT_JPYATOM_JPYADA_JPYLINK_JPYDOGE_JPYSOL_JPYto the Parameter and Response section.
2024-03-02
- Changed: Private API limits
- Trading volume requirements for Tier 2 has been increased from from 100 million to over 1 billion.
- Tier2: Maximum 30 POST GET API requests per second for the same account.
2023
2023-12-16
2023-12-09
- Changed: Private API limits
- Tier1: Maximum 20 POST GET API requests per second for the same account.
2023-10-28
- Added a new : transferableAmount to the Response section.
2023-10-21
- Changed: Private API limits
- Trading volume requirements for Tier 2 has been reduced from 1 billion to over 100 million.
- Tier1: Maximum 10 POST GET API requests per second for the same account.
- Tier2: Maximum 20 POST GET API requests per second for the same account.
2023-09-16
- Added a new cancelType:
EXPIRED_SELFTRADEto the Response section.
- Added a new cancelType:
EXPIRED_SELFTRADEto the Response section.
2023-08-05
2023-07-29
2023-07-08
2023-05-13
- Added new TradingVolume properties: TakerFee and MakerFee.
2023-03-22
2023-01-18
2022
2022-12-21
2022-10-12
2022-07-13
2022-07-06
2022-06-08
2022-05-18
2022-04-08
- Changed: Private API limits
- Trading volume requirements for Tier 2 has been reduced from 2 billion to over 1 billion.
2022-03-30
2022-03-02
2022-02-16
2022-01-27
- Changed: Private API limits
- Current week's private API limits are based on the trading volume from the previous week.
2022-01-26
2021
2021-12-01
2021-10-20
2021-09-22
- Added a new Executions property: positionId to Response
- Added a new LatestExecutions property: positionId to Response
2021-09-08
- Added a new timeInForce:
FAKinto the Limit order.
- Added a new timeInForce:
FAKinto the Limit order.
- Added a new timeInForce:
FAKinto the Limit order.
2021-08-18
2021-08-04
- Changed a symbol parameter to Optional.
2021-07-14
2021-06-23
2021-05-26
- Changed: Private API limits
- Maximum 6 GET API requests per second for the same account.
- Maximum 6 GET API requests per second for the same account.
2021-05-19
2021-04-21
- Added a new response property: marginCallStatus
- Added a new cancelType:
MARGIN_CALLMARGIN_CALL_LOSSCUTto the Response section.
- Added a new cancelType:
MARGIN_CALLMARGIN_CALL_LOSSCUTto the Response section.
2021-04-15
2021-03-10
- Added a new response property: marginRatio
2020
2020-12-16
- Now you can request multiple executions at once by using a comma-separated list of execution ids.
- Changed the type of parameter: executionId from number to string.
- The maximum number of execution ids is 10.
2020-12-09
- Added a new Order parameter: cancelBefore
- Added a new Order parameter: cancelBefore
2020-11-04
- Now you can request multiple orders at once by using a comma-separated list of order ids.
- Changed the type of parameter: orderId from number to string.
- The maximum number of order ids is 10.
2020-09-09
- Changed the maximum number of tokens of Private WebSocket API from 1 to 5.
- If the number of issued tokens exceeds the maximum number of tokens, the tokens will be deleted in order of expiration time.
2020-09-02
- Added a new Order parameter: timeInForce
- Added a new Order parameter: timeInForce
- Added a new Order parameter: timeInForce
Added a new cancelType:
EXPIRED_FAKEXPIRED_FOKEXPIRED_SOKto the Response section.Added a new timeInForce:
FOKSOKto the Response section.
- Added a new timeInForce:
FOKSOKto the Response section.
- Added a new timeInForce:
FOKSOKto the Response section.
Added a new cancelType:
EXPIRED_FAKEXPIRED_FOKEXPIRED_SOKCLOSED_ORDERPRICE_LIMITSOK_TAKERto the Response section.Added a new timeInForce:
FOKSOKto the Response section.
2020-08-12
- Added a new Position Summary Notifications parameter: option
- Added a new response property: msgType
2020-08-05
- Added a new cancelType:
INSUFFICIENT_BALANCEINSUFFICIENT_MARGINACCOUNT_LOSSCUTto the Response section.
- Added a new cancelType:
INSUFFICIENT_BALANCEINSUFFICIENT_MARGINACCOUNT_LOSSCUTto the Response section.
2020-07-28
- You can download the historical data (.CSV file).
2020-07-15
- Added a new Order parameter: losscutPrice
2020-07-08
- To use the API with the existing API keys, open your membership site > API > 編集 (Edit) > APIキーの編集 (API key setting) screen and click "約定情報通知(WebSocket)" (Execution Notifications), "注文情報通知(WebSocket)" (Order Notifications), "ポジション情報通知(WebSocket)" (Position Notifications) or "ポジション情報通知(WebSocket)" (Position Summary Notifications) to call the Create Access Token API.
2020-06-24
- Added a new response property: cancelType
- Added a new response property: cancelType
2020-05-27
- Added a new Change Order parameter: losscutPrice
- Added a new response property: losscutPrice
- Added a new response property: losscutPrice
- Added a new response property: losscutPrice
2020-04-28
- To use the API with the existing API keys, open your membership site > API > 編集 (Edit) > APIキーの編集 (API key setting) screen and click "約定情報通知(WebSocket)" (Execution Notifications), "注文情報通知(WebSocket)" (Order Notifications) or "ポジション情報通知(WebSocket)" (Position Notifications) to call the Create Access Token API.
2020-04-08
- Added a new response property: timestamp
2020-04-01
- Changed: Private API limits
- Private API limits for GET and POST method are now separated.
- Maximum 3 GET API requests per second for the same account.
- Maximum 3 POST API requests per second for the same account.
- Private API limits for GET and POST method are now separated.
2020-02-26
- To use the API with the existing API keys, open your membership site > API > 編集 (Edit) > APIキーの編集 (API key setting) screen and click "約定情報通知(WebSocket)" (Execution Notifications) or "注文情報通知(WebSocket)" (Order Notifications) to call the Create Access Token API.
- Added a new response property: msgType
2020-02-12
- Request example of Swift has been added.
- WebSocket4Net version of C# request example has been added.
2020-01-23
- Added: Private WebSocket API Limiting
- Description of API usage restriction of Private WebSocket API to Limits section has been added.
2019
2019-11-27
- Added a new Trade parameter: option
2019-11-20
2019-10-23
- Please note that meaning of order status
WAITINGwill be valid andORDEREDwill be partially executed for stop limit orders.
- Added a new executionType:
STOPto the Parameter section. - Added a description of price to the Parameter section.
- Added a new executionType:
STOPto the Parameter section. - Added a description of price to the Parameter section.
- Added a new executionType:
STOPto the Parameter section. - Added a description of price to the Parameter section.
- Added a new executionType:
STOPto the Parameter section. - Added a description of status to the Parameter section.
- Added a new executionType:
STOPto the Parameter section. - Changed the description of status in the Response section.
2019-10-02
2019-09-18
2019-09-11
2019-08-28
- Added: Public WebSocket API limits
- Description of API usage restriction of Public WebSocket API to Limits section has been added.
2019-07-03
- Changed: Private API limits
- Private API limits are changed to once per 300 milliseconds.
2019-06-12
- Changed: Symbol parameter is changed from required to optional
- If symbol is not specified, now it returns all symbols' rates.