NAV Navbar
Node.js Python Go Ruby PHP Kotlin C# Rust Haskell

概要

GMOコインのAPIは、認証不要のPublic APIと、APIキーによる認証が必要なPrivate APIを提供しています。


//Node.js v10.15.3 にて動作確認したサンプルコードをRequest exampleに記載しています。


#Python 3.7.2 にて動作確認したサンプルコードをRequest exampleに記載しています。


//Go 1.12.5 にて動作確認したサンプルコードをRequest exampleに記載しています。


#Ruby 2.6.2 にて動作確認したサンプルコードをRequest exampleに記載しています。


//Kotlin 1.3.41 にて動作確認したサンプルコードをRequest exampleに記載しています。

<?php
//PHP 7.3.9 にて動作確認したサンプルコードをRequest exampleに記載しています。


//rustc 1.37.0 にて動作確認したサンプルコードをRequest exampleに記載しています。


--ghc 8.8.1 にて動作確認したサンプルコードをRequest exampleに記載しています。


//.NET Framework 4.7.2 にて動作確認したサンプルコードをRequest exampleに記載しています。

エンドポイント

バージョン

現在バージョン: v1

制限

リクエストの制限APIによりリクエスト回数に制限をかけております。

口座開設

口座をお持ちでない場合 無料口座開設

※当社での口座開設は日本国内に居住している個人のお客さまのみとなります。

APIキー作成

口座開設完了後、会員ページからAPIキーが作成できます。

APIキーを生成する際、機能ごとにパーミッションを設定することができます。

認証

var request   = require('request');
var crypto    = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp = Date.now().toString();
var method    = 'POST';
var endPoint  = 'https://END_POINT_URL';
var path      = '/v1/PATH';
var reqBody   = {};

var text = timestamp + method + path + JSON.stringify(reqBody);
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path,
    "method": method,
    "body": JSON.stringify(reqBody),
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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, &parameters);
    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 mut res = reqwest::Client::new()
        .post(&(endpoint.to_string() + path))
        .header("content-type", "application/json")
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .json(&parameters)
        .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
{
    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 client = new HttpClient())
        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 client.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();
    }
}

Private APIではAPIキーとAPIシークレットを使用してHTTPヘッダに下記の認証情報を含める必要があります。

Signatureの作成API-SIGNは、リクエスト時のUnix Timestamp,HTTPメソッド,リクエストのパス,リクエストボディを文字列として連結したものをHMAC-SHA256形式でAPIシークレットキーを使って署名した結果となります。

Public API

取引所ステータス

Request example:

var request = require('request');

var endPoint = 'https://api.coin.z.com/public';
var path     = '/v1/status';

request(endPoint + path, function (err, response, payload) {
    console.log(JSON.stringify(JSON.parse(payload), null, 2));
});
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/ioutil"
    "net/http"
    "encoding/json"
    "bytes"
)

func main() {
    endPoint := "https://api.coin.z.com/public"
    path := "/v1/status"

    response, _ := http.Get(endPoint + path)
    body, _ := ioutil.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);
#![deny(warnings)]

extern crate reqwest;

#[warn(unused_must_use)]
fn main() {
    status().unwrap();
}

fn status() -> Result<(), Box<dyn std::error::Error>> {
    let mut res = reqwest::get("https://api.coin.z.com/public/v1/status")?;
    res.copy_to(&mut std::io::stdout())?;

    Ok(())
}
{-# 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
{
    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";
        using (var client = new HttpClient())
        {
            return await client.GetStringAsync(endpoint + path);
        }
    }
}

Response example:

{
  "status": 0,
  "data": {
    "status": "OPEN"
  },
  "responsetime": "2019-03-19T02:15:06.001Z"
}

取引所の稼動状態を取得します。

Request

GET /public/v1/status

Parameters

無し

Response

Property Name Value Description
status string 取引所ステータス: MAINTENANCE PREOPEN OPEN

最新レート

Request example:

var request = require('request');

var endPoint = 'https://api.coin.z.com/public';
var path     = '/v1/ticker?symbol=BTC';

request(endPoint + path, function (err, response, payload) {
    console.log(JSON.stringify(JSON.parse(payload), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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);
#![deny(warnings)]

extern crate reqwest;

#[warn(unused_must_use)]
fn main() {
    ticker().unwrap();
}

fn ticker() -> Result<(), Box<dyn std::error::Error>> {
    let mut res = reqwest::get("https://api.coin.z.com/public/v1/ticker?symbol=BTC")?;
    res.copy_to(&mut std::io::stdout())?;

    Ok(())
}
{-# 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
{
    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";
        using (var client = new HttpClient())
        {
            return await client.GetStringAsync(endpoint + path);
        }
    }
}

Response example:

{
  "status": 0,
  "data": [
    {
      "ask": "750760",
      "bid": "750600",
      "high": "762302.7269572",
      "last": "756662.3802628",
      "low": "704874.663486",
      "symbol": "BTC",
      "timestamp": "2018-03-30T12:34:56.789Z",
      "volume": "194785.84845239"
    }
  ],
  "responsetime": "2019-03-19T02:15:06.014Z"
}

指定した銘柄の最新レートを取得します。
全銘柄分の最新レートを取得する場合はsymbolパラメータ指定無しでの実行をおすすめします。

Request

GET /public/v1/ticker

Parameters

Parameter Type Required Available Values
symbol string Optional 指定しない場合は全銘柄分の最新レートを返す。BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY

Response

Property Name Value Description
list.volume string 24時間の取引量

板情報

Request example:

var request = require('request');

var endPoint = 'https://api.coin.z.com/public';
var path     = '/v1/orderbooks?symbol=BTC';

request(endPoint + path, function (err, response, payload) {
    console.log(JSON.stringify(JSON.parse(payload), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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);
#![deny(warnings)]

extern crate reqwest;

#[warn(unused_must_use)]
fn main() {
    orderbooks().unwrap();
}

fn orderbooks() -> Result<(), Box<dyn std::error::Error>> {
    let mut res = reqwest::get("https://api.coin.z.com/public/v1/orderbooks?symbol=BTC")?;
    res.copy_to(&mut std::io::stdout())?;

    Ok(())
}
{-# 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
{
    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";
        using (var client = new HttpClient())
        {
            return await client.GetStringAsync(endpoint + path);
        }
    }
}

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

指定した銘柄の板情報(snapshot)を取得します。

Request

GET /public/v1/orderbooks

Parameters

Parameter Type Required Available Values
symbol string
Required
BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY

Response

Property Name Value Description
asks array 売り注文の情報
bids array 買い注文の情報

取引履歴

Request example:

var request = require('request');

var endPoint = 'https://api.coin.z.com/public';
var path     = '/v1/trades?symbol=BTC&page=1&count=10';

request(endPoint + path, function (err, response, payload) {
    console.log(JSON.stringify(JSON.parse(payload), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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);
#![deny(warnings)]

extern crate reqwest;

#[warn(unused_must_use)]
fn main() {
    trades().unwrap();
}

fn trades() -> Result<(), Box<dyn std::error::Error>> {
    let mut res = reqwest::get("https://api.coin.z.com/public/v1/trades?symbol=BTC&page=1&count=10")?;
    res.copy_to(&mut std::io::stdout())?;

    Ok(())
}
{-# 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
{
    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";
        using (var client = new HttpClient())
        {
            return await client.GetStringAsync(endpoint + path);
        }
    }
}

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

指定した銘柄の取引履歴を取得します。

Request

GET /public/v1/trades

Parameters

Parameter Type Required Available Values
symbol string
Required
BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
page number Optional 取得対象ページ: 指定しない場合は1を指定したとして動作する。
count number Optional 1ページ当りの取得件数: 指定しない場合は100(最大値)を指定したとして動作する。

Response

Property Name Value Description
price string 約定価格
side string 売買区分: BUY SELL
size string 約定数量
timestamp string 約定日時

Public WebSocket API

最新レート

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))
                }
            }
        }
    }
}
<?php

// 事前に以下のcomposerコマンドでratchet/pawlをインストールしておく必要があります。
// 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();
#![deny(warnings)]

extern crate tungstenite;
extern crate url;

use tungstenite::{connect, Message};
use url::Url;

fn main() {
    ticker_ws();
}

fn ticker_ws() {
    let (mut socket, _response) =
        connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");

    socket
        .write_message(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }".into()))
        .unwrap();
    loop {
        let msg = socket.read_message().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));
            }
        }
    }
}

Response example:

{
  "channel":"ticker",
  "ask": "750760",
  "bid": "750600",
  "high": "762302.7269572",
  "last": "756662.3802628",
  "low": "704874.663486",
  "symbol": "BTC",
  "timestamp": "2018-03-30T12:34:56.789Z",
  "volume": "194785.84845239"
}

指定した銘柄の最新レートを受信します。
subscribe後、最新レートが配信されます。

Parameters

Property Name Type Required Available Values
command string
Required
subscribe unsubscribe
channel string
Required
ticker
symbol string
Required
BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY

Response

Property Name Value Description
channel string ticker
ask string 現在の売注文の最良気配値
bid string 現在の買注文の最良気配値
high string 最高気配値
last string 最終取引価格
low string 最低気配値
symbol string 銘柄名: BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
timestamp string 約定時のタイムスタンプ
volume string 24時間の取引量

板情報

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))
                }
            }
        }
    }
}
<?php

// 事前に以下のcomposerコマンドでratchet/pawlをインストールしておく必要があります。
// 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() {
    orderbooks_ws();
}

fn orderbooks_ws() {
    let (mut socket, _response) =
        connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");

    socket
        .write_message(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }".into()))
        .unwrap();
    loop {
        let msg = socket.read_message().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));
            }
        }
    }
}

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

指定した銘柄の板情報(snapshot)を受信します。
subscribe後、板情報が配信されます。

Parameters

Property Name Type Required Available Values
command string
Required
subscribe unsubscribe
channel string
Required
orderbooks
symbol string
Required
BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY

Response

Property Name Value Description
channel string orderbooks
asks array 売り注文の情報
bids array 買い注文の情報
symbol string 銘柄名: BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY

取引履歴

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))
                }
            }
        }
    }
}
<?php

// 事前に以下のcomposerコマンドでratchet/pawlをインストールしておく必要があります。
// 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() {
    trades_ws();
}

fn trades_ws() {
    let (mut socket, _response) =
        connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");

    socket
        .write_message(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }".into()))
        .unwrap();
    loop {
        let msg = socket.read_message().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));
            }
        }
    }
}

Response example:

{
  "channel":"trades",
  "price": "750760",
  "side": "BUY",
  "size": "0.1",
  "timestamp": "2018-03-30T12:34:56.789Z",
  "symbol": "BTC"
}

指定した銘柄の最新の取引履歴を受信します。
subscribe後、最新の取引履歴が配信されます。

Parameters

Property Name Type Required Available Values
command string
Required
subscribe unsubscribe
channel string
Required
trades
symbol string
Required
BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY

Response

Property Name Value Description
channel string trades
price string 約定価格
side string 売買区分: BUY SELL
size string 約定数量
timestamp string 約定日時
symbol string 銘柄名: BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY

Private API

余力情報を取得

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey     = 'YOUR_API_KEY';
var secretKey  = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().toString();
var method     = 'GET';
var endPoint   = 'https://api.coin.z.com/private';
var path       = '/v1/account/margin';

var text = timestamp + method + path;
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path,
    "method": method,
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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 mut res = reqwest::Client::new()
        .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
{
    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 client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": {
    "profitLoss": "8019",
    "actualProfitLoss": "5204923",
    "margin": "7298",
    "availableAmount": "5189523"
  },
  "responsetime": "2019-03-19T02:15:06.051Z"
}

余力情報を取得します。

Request

GET /private/v1/account/margin

Parameters

無し

Response

Property Name Value Description
profitLoss string 評価損益
actualProfitLoss string 時価評価総額
margin string 拘束証拠金
availableAmount string 取引余力

資産残高を取得

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey     = 'YOUR_API_KEY';
var secretKey  = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().toString();
var method     = 'GET';
var endPoint   = 'https://api.coin.z.com/private';
var path       = '/v1/account/assets';

var text = timestamp + method + path;
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path,
    "method": method,
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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 mut res = reqwest::Client::new()
        .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
{
    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 client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": [
    {
      "symbol": "JPY",
      "amount": "993982448",
      "available": "993982448",
      "conversionRate": "1"
    },
    {
      "symbol": "BTC",
      "amount": "4.0002",
      "available": "4.0002",
      "conversionRate": "859614"
    }
  ],
  "responsetime": "2019-03-19T02:15:06.055Z"
}

資産残高を取得します。

Request

GET /private/v1/account/assets

Parameters

無し

Response

Property Name Value Description
symbol string 銘柄名: JPY BTC ETH BCH LTC XRP
amount string 残高
available string 利用可能金額(残高 - 出金予定額)
conversionRate string 円転レート

注文情報取得

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().toString();
var method     = 'GET';
var endPoint   = 'https://api.coin.z.com/private';
var path       = '/v1/orders';
var parameters = '?orderId=123456789';

var text = timestamp + method + path;
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path + parameters,
    "method": method,
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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 }

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

    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, _ := ioutil.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
}

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"

    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';

$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);

    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 mut res = reqwest::Client::new()
        .get(&(endpoint.to_string() + path))
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .query(&parameters)
        .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")]
        $ 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
{
    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";

        using (var client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": {
    "list": [
      {
        "rootOrderId": 123456789,
        "orderId": 123456789,
        "symbol": "BTC",
        "side": "BUY",
        "orderType": "NORMAL",
        "executionType": "MARKET",
        "settleType": "OPEN",
        "size": "1",
        "executedSize": "1",
        "price": "0",
        "status": "WAITING",
        "timeInForce": "FAK",
        "timestamp": "2019-03-19T02:15:06.059Z"
      }
    ]
  },
  "responsetime": "2019-03-19T02:15:06.059Z"
}

指定した注文IDの注文情報を取得します。
対象: 現物取引、レバレッジ取引

Request

GET /private/v1/orders

Parameters

Parameter Type Required Available Values
orderId number
Required

Response

Property Name Value Description
rootOrderId number 親注文ID
orderId number 注文ID
symbol string 銘柄名: BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
side string 売買区分: BUY SELL
orderType string 取引区分: NORMAL LOSSCUT
executionType string 注文タイプ: MARKET LIMIT STOP
settleType string 決済区分: OPEN CLOSE
size string 発注数量
executedSize string 約定数量
price string 注文価格 (MARKET注文の場合は空)
status string 注文ステータス: WAITING ORDERED MODIFYING CANCELLING CANCELED EXECUTED EXPIRED
※逆指値注文の場合はWAITINGが有効または一部約定
timeInForce string 執行数量条件: FAK FAS
timestamp string 注文日時

有効注文一覧

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().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 sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path + parameters,
    "method": method,
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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 mut res = reqwest::Client::new()
        .get(&(endpoint.to_string() + path))
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .query(&parameters)
        .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
{
    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 client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": {
    "pagination": {
      "currentPage": 1,
      "count": 30
    },
    "list": [
      {
        "rootOrderId": 123456789,
        "orderId": 123456789,
        "symbol": "BTC",
        "side": "BUY",
        "orderType": "NORMAL",
        "executionType": "LIMIT",
        "settleType": "OPEN",
        "size": "1",
        "executedSize": "0",
        "price": "840000",
        "status": "ORDERED",
        "timeInForce": "FAS",
        "timestamp": "2019-03-19T01:07:24.217Z"
      }
    ]
  },
  "responsetime": "2019-03-19T01:07:24.217Z"
}

有効注文一覧を取得します。
対象: 現物取引、レバレッジ取引

Request

GET /private/v1/activeOrders

Parameters

Parameter Type Required Available Values
symbol string
Required
BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
page number Optional 取得対象ページ: 指定しない場合は1を指定したとして動作する。
count number Optional 1ページ当りの取得件数: 指定しない場合は100(最大値)を指定したとして動作する。

Response

Property Name Value Description
rootOrderId number 親注文ID
orderId number 注文ID
symbol string 銘柄名: BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
side string 売買区分: BUY SELL
orderType string 取引区分: NORMAL LOSSCUT
executionType string 注文タイプ: MARKET LIMIT STOP
settleType string 決済区分: OPEN CLOSE
size string 発注数量
executedSize string 約定数量
price string 注文価格 (MARKET注文の場合は空)
status string 注文ステータス: WAITING ORDERED MODIFYING CANCELLING CANCELED EXECUTED EXPIRED
※逆指値注文の場合はWAITINGが有効または一部約定
timeInForce string 執行数量条件: FAK FAS
timestamp string 注文日時

約定情報取得

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().toString();
var method     = 'GET';
var endPoint   = 'https://api.coin.z.com/private';
var path       = '/v1/executions';
var parameters = '?orderId=123456789';

var text = timestamp + method + path;
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path + parameters,
    "method": method,
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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 = {
    "orderId": 123456789
}

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/ioutil"
    "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 := "?orderId=123456789"

    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, _ := ioutil.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 = {
  :orderId => 123456789
}

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 = "?orderId=123456789"

    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 = '?orderId=123456789';

$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() {
    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/executions";
    let mut parameters = HashMap::new();
    parameters.insert("orderId", 123456789);

    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 mut res = reqwest::Client::new()
        .get(&(endpoint.to_string() + path))
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .query(&parameters)
        .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 [("orderId", Just "123456789")]
        $ 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
{
    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 = "?orderId=123456789";

        using (var client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": {
    "list": [
      {
        "executionId": 72123911,
        "orderId": 123456789,
        "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"
}

約定情報を取得します。
対象: 現物取引、レバレッジ取引

Request

GET /private/v1/executions

Parameters

Parameter Type Required Available Values
orderId number
*
orderId executionId いずれか一つが必須。
executionId number
*
orderId executionId いずれか一つが必須。

Response

Property Name Value Description
executionId number 約定ID
orderId number 注文ID
symbol string 銘柄名: BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
side string 売買区分: BUY SELL
settleType string 決済区分: OPEN CLOSE
size string 約定数量
price string 約定レート
lossGain string 決済損益
fee string 取引手数料
timestamp string 約定日時

最新の約定一覧

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().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 sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path + parameters,
    "method": method,
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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 mut res = reqwest::Client::new()
        .get(&(endpoint.to_string() + path))
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .query(&parameters)
        .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
{
    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 client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": {
    "pagination": {
      "currentPage": 1,
      "count": 30
    },
    "list": [
      {
        "executionId": 72123911,
        "orderId": 123456789,
        "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"
}

最新約定一覧を取得します。
対象: 現物取引、レバレッジ取引

Request

GET /private/v1/latestExecutions

Parameters

Parameter Type Required Available Values
symbol string
Required
BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
page number Optional 取得対象ページ: 指定しない場合は1を指定したとして動作する。
count number Optional 1ページ当りの取得件数: 指定しない場合は100(最大値)を指定したとして動作する。

Response

Property Name Value Description
executionId number 約定ID
orderId number 注文ID
symbol string 銘柄名: BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
side string 売買区分: BUY SELL
settleType string 決済区分: OPEN CLOSE
size string 約定数量
price string 約定レート
lossGain string 決済損益
fee string 取引手数料
timestamp string 約定日時

建玉一覧を取得

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().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 sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path + parameters,
    "method": method,
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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 mut res = reqwest::Client::new()
        .get(&(endpoint.to_string() + path))
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .query(&parameters)
        .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
{
    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 client = new HttpClient())
        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 client.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();
    }
}

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": "10",
        "losscutPrice": "832243",
        "timestamp": "2019-03-19T02:15:06.094Z"
      }
    ]
  },
  "responsetime": "2019-03-19T02:15:06.095Z"
}

有効建玉一覧を取得します。
対象: レバレッジ取引

Request

GET /private/v1/openPositions

Parameters

Parameter Type Required Available Values
symbol string
Required
BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
page number Optional 取得対象ページ: 指定しない場合は1を指定したとして動作する。
count number Optional 1ページ当りの取得件数: 指定しない場合は100(最大値)を指定したとして動作する。

Response

Property Name Value Description
positionId number 建玉ID
symbol string 銘柄名: BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
side string 売買区分: BUY SELL
size string 建玉数量
orderdSize string 発注中数量
price string 建玉レート
lossGain string 評価損益
leverage string レバレッジ
losscutPrice string ロスカットレート
timestamp string 約定日時

建玉サマリーを取得

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().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 sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path + parameters,
    "method": method,
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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 mut res = reqwest::Client::new()
        .get(&(endpoint.to_string() + path))
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .query(&parameters)
        .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
{
    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 client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": {
    "list": [
      {
        "symbol": "BTC_JPY",
        "side": "BUY",
        "sumPositionQuantity": "11.6999",
        "sumOrderQuantity": "2",
        "averagePositionRate": "715656",
        "positionLossGain": "250675"
      }
    ]
  },
  "responsetime": "2019-03-19T02:15:06.102Z"
}

建玉サマリーを取得します。
対象: レバレッジ取引

Request

GET /private/v1/positionSummary

Parameters

Parameter Type Required Available Values
symbol string
Required
BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY

Response

Property Name Value Description
symbol string 銘柄名: BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
side string 売買区分: BUY SELL
sumPositionQuantity string 建玉数量
sumOrderQuantity string 発注中数量
averagePositionRate string 平均建玉レート
positionLossGain string 評価損益

注文

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().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",
    price: "430001",
    size: "0.02"
}

var text = timestamp + method + path + JSON.stringify(reqBody);
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path,
    "method": method,
    "body": JSON.stringify(reqBody),
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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",
    "price": "430001",
    "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/ioutil"
    "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",
        "price": "430001",
        "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, _ := ioutil.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',
  :price => '430001',
  :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",
            "price": "430001",
            "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",
    "price": "430001",
    "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",
        "price": "430001",
        "size": "0.02"
    });

    let text = format!("{}{}{}{}", timestamp, method, path, &parameters);
    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 mut res = reqwest::Client::new()
        .post(&(endpoint.to_string() + path))
        .header("content-type", "application/json")
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .json(&parameters)
        .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",
      "price": "430001",
      "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.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

class Example
{
    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\", " +
                      "\"price\": \"430001\", " +
                      "\"size\": \"0.02\"}";

        using (var client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": "637000",
  "responsetime": "2019-03-19T02:15:06.108Z"
}

新規注文をします。
対象: 現物取引、レバレッジ取引

Request

POST /private/v1/order

Parameters

Parameter Type Required Available Values
symbol string
Required
BTC ETH BCH LTC XRP BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
side string
Required
BUY SELL
executionType string
Required
MARKET LIMIT STOP
price string
*executionTypeによる
LIMIT STOP の場合は必須、 MARKET の場合は不要。
size string
Required

Response

Property Name Value Description
data string 注文対象のorderId

注文変更

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().toString();
var method     = 'POST';
var endPoint   = 'https://api.coin.z.com/private';
var path       = '/v1/changeOrder';
var reqBody    = {
    orderId: 2,
    price: "1201"
}

var text = timestamp + method + path + JSON.stringify(reqBody);
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path,
    "method": method,
    "body": JSON.stringify(reqBody),
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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"
}

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/ioutil"
    "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"
    }`)

    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, _ := ioutil.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'
}

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

    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"
}';

$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",
    });

    let text = format!("{}{}{}{}", timestamp, method, path, &parameters);
    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 mut res = reqwest::Client::new()
        .post(&(endpoint.to_string() + path))
        .header("content-type", "application/json")
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .json(&parameters)
        .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" }
    |]
  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
{
    public static void Main(string[] args)
    {
        var task = ChangeOrder();
        task.Wait();
        Console.WriteLine(task.Result);
    }

   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();
    }

    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\"}";

        using (var client = new HttpClient())
        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 client.SendAsync(request);
            return await response.Content.ReadAsStringAsync();
        }
    }
}

Response example:

{
  "status": 0,
  "responsetime": "2019-03-19T01:07:24.557Z"
}

注文変更をします。
対象: 現物取引、レバレッジ取引

Request

POST /private/v1/changeOrder

Parameters

Parameter Type Required Available Values
orderId number
Required
price string
Required

注文キャンセル

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().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 + JSON.stringify(reqBody);
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path,
    "method": method,
    "body": JSON.stringify(reqBody),
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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/ioutil"
    "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, _ := ioutil.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 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/cancelOrder";
    let parameters = json!({
        "orderId": 2
    });

    let text = format!("{}{}{}{}", timestamp, method, path, &parameters);
    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 mut res = reqwest::Client::new()
        .post(&(endpoint.to_string() + path))
        .header("content-type", "application/json")
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .json(&parameters)
        .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.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

class Example
{
    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 client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "responsetime": "2019-03-19T01:07:24.557Z"
}

注文取消をします。
対象: 現物取引、レバレッジ取引

Request

POST /private/v1/cancelOrder

Parameters

Parameter Type Required Available Values
orderId number
Required

決済注文

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().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",
    "price": "85201",
    "settlePosition": [
        {
            "positionId": 1000342,
            "size": "3.44"
        }
    ]
}

var text = timestamp + method + path + JSON.stringify(reqBody);
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path,
    "method": method,
    "body": JSON.stringify(reqBody),
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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",
    "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/ioutil"
    "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",
        "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, _ := ioutil.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',
  :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",
               "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",
    "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",
        "price": "85201",
        "settlePosition": [
            {
                "positionId": 1000342,
                "size": "3.44"
            }
        ]
    });

    let text = format!("{}{}{}{}", timestamp, method, path, &parameters);
    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 mut res = reqwest::Client::new()
        .post(&(endpoint.to_string() + path))
        .header("content-type", "application/json")
        .header("API-KEY", api_key)
        .header("API-TIMESTAMP", timestamp)
        .header("API-SIGN", sign)
        .json(&parameters)
        .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",
      "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.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

class Example
{
    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\", " +
                      "\"price\": \"85201\", " +
                      "\"settlePosition\": [ { \"positionId\": 1000342, \"size\": \"3.44\" } ] }";

        using (var client = new HttpClient())
        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 client.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();
    }
}

Response example:

{
  "status": 0,
  "data": "637000",
  "responsetime": "2019-03-19T01:07:24.557Z"
}

決済注文をします。
対象: レバレッジ取引

Request

POST /private/v1/closeOrder

Parameters

Parameter Type Required Available Values
symbol string
Required
BTC_JPY ETH_JPY BCH_JPY LTC_JPY XRP_JPY
side string
Required
BUY SELL
executionType string
Required
MARKET LIMIT STOP
price string
*executionTypeによる
LIMIT STOP の場合は必須、 MARKET の場合は不要。
settlePosition.positionId number
Required
建玉は1つのみ指定可能。
settlePosition.size string
Required
建玉は1つのみ指定可能。

Response

Property Name Value Description
data string 決済注文対象のorderId

一括決済注文

Request example:

var request = require('request');
var crypto  = require('crypto');

var apiKey    = 'YOUR_API_KEY';
var secretKey = 'YOUR_SECRET_KEY';

var timestamp  = Date.now().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",
    "price": "85201",
    "size": "3.44"
}

var text = timestamp + method + path + JSON.stringify(reqBody);
var sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
var options = {
    "url": endPoint + path,
    "method": method,
    "body": JSON.stringify(reqBody),
    "headers": {
        "API-KEY": apiKey,
        "API-TIMESTAMP": timestamp,
        "API-SIGN": sign
    }
};

request(options, function (err, response, body) {
    console.log(JSON.stringify(JSON.parse(body), null, 2));
});
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",
    "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/ioutil"
    "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",
        "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, _ := ioutil.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',
  :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