概要
GMOコインのAPIは、認証不要のPublic APIと、APIキーによる認証が必要なPrivate APIを提供しています。
- クライアントからAPIへの全てのリクエストはHTTPS通信です。
- 現物取引とレバレッジ取引にのみ対応しています。
//Node.js v21.0.0 にて動作確認したサンプルコードをRequest exampleに記載しています。
#Python 3.12.0 にて動作確認したサンプルコードをRequest exampleに記載しています。
//Go 1.21.3 にて動作確認したサンプルコードをRequest exampleに記載しています。
#Ruby 3.2.2 にて動作確認したサンプルコードをRequest exampleに記載しています。
//Kotlin 1.9.10 にて動作確認したサンプルコードをRequest exampleに記載しています。
<?php
//PHP 8.2.11 にて動作確認したサンプルコードをRequest exampleに記載しています。
//rustc 1.73.0 にて動作確認したサンプルコードをRequest exampleに記載しています。
--ghc 9.8.1 にて動作確認したサンプルコードをRequest exampleに記載しています。
//.NET Framework 8.0.1 にて動作確認したサンプルコードをRequest exampleに記載しています。
//Swift 5.8.1 にて動作確認したサンプルコードをRequest exampleに記載しています。
エンドポイント
- Public API:
https://api.coin.z.com/public
- Public WebSocket API:
wss://api.coin.z.com/ws/public
- Private API:
https://api.coin.z.com/private
- Private WebSocket API:
wss://api.coin.z.com/ws/private
バージョン
現在バージョン: v1
制限
APIは以下のように制限をかけております。
Public WebSocket APIの制限
- 同一IPからのリクエスト(subscribe, unsubscribe)は、1秒間1回を上限とします。
Private APIの制限
- 先週の取引高に応じて、今週のPrivate APIの呼び出し上限値が決定いたします。
- 制限はシステム負荷状況によって一時的に変更する場合があります。ご了承ください。
- 会員ページにてIP制限機能を有効にすると、API呼出ができるIPアドレスを制限することができます。
- APIキー発行時に指定した機能のみをAPIで呼び出すことができます。
レベル | 取引高 | 呼出し上限 | 説明 |
---|---|---|---|
Tier 1 | 先週の取引高 < 1,000,000,000円 | 20req/s | 同一アカウントからGETのAPI呼出は、1秒間に20回が上限です。 同一アカウントからPOSTのAPI呼出は、1秒間に20回が上限です。 |
Tier 2 | 先週の取引高 >= 1,000,000,000円 | 30req/s | 同一アカウントからGETのAPI呼出は、1秒間に30回が上限です。 同一アカウントからPOSTのAPI呼出は、1秒間に30回が上限です。 |
※取引高は取引所における現物取引とレバレッジ取引が対象になります。
※取引高の集計期間は日本時間 先週日曜日6:00~今週日曜日5:59となります。
※Tierの更新は日本時間の日曜日6:00~6:30で実施されます。
Private WebSocket APIの制限
- 同一IPからのリクエスト(subscribe, unsubscribe)は、1秒間1回を上限とします。
- 会員ページにてIP制限機能を有効にすると、API呼出ができるIPアドレスを制限することができます。
- APIキー発行時に指定した機能のみをsubscribeすることができます。
その他
下記のいずれかの理由により、APIのご利用を制限させていただく場合があります。ご了承ください。
- 当社システム全体が高負荷となった場合に、自動で流量制限を実施させていただくため
- お客さまによるAPIのご利用方法が、当社システムへ負荷をかけている可能性があると当社が判断したため
- システムに負荷をかける目的での発注を繰り返していると当社が判断したため
口座開設
口座をお持ちでない場合 無料口座開設
APIキー作成
口座開設完了後、会員ページからAPIキーが作成できます。
APIキーを生成する際、機能ごとにパーミッションを設定することができます。
認証
Private API
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://END_POINT_URL';
const path = '/v1/PATH';
const reqBody = JSON.stringify({});
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://END_POINT_URL'
path = '/v1/PATH'
reqBody = {}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (res.json())
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://END_POINT_URL"
path := "/v1/PATH"
reqBody := (`{}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://END_POINT_URL'
path = '/v1/PATH'
reqBody = {}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://END_POINT_URL"
var path = "/v1/PATH"
var reqBody = """{}"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://END_POINT_URL';
$path = '/v1/PATH';
$reqBody = '{}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
order().unwrap();
}
fn order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://END_POINT_URL";
let path = "/v1/PATH";
let parameters = json!({});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://END_POINT_URL"
path :: S.String
path = "/v1/PATH"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {}
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Sample();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Sample()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://END_POINT_URL";
const string path = "/v1/PATH";
var reqBody = "{}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/PATH"
let reqBodyStr = """
{}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Private APIではAPIキーとAPIシークレットを使用してHTTPヘッダに下記の認証情報を含める必要があります。
- API-KEY: 会員ページで発行したアクセスキー
- API-TIMESTAMP: リクエスト時のUnix Timestamp
- API-SIGN: 後述する方法でリクエストごとに生成した署名
Signatureの作成API-SIGNは、リクエスト時のUnix Timestamp,HTTPメソッド,リクエストのパス,リクエストボディを文字列として連結したものをHMAC-SHA256形式でAPIシークレットキーを使って署名した結果となります。
Private WebSocket API
Private WebSocket APIではPrivate APIのアクセストークンの取得を使用してアクセストークンを取得します。このPrivate APIの認証方法は他のPrivate APIと同様です。
Public API
取引所ステータス
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/status';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/status'
response = requests.get(endPoint + path)
print(response.json())
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/status"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/status'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/status"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/status';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/status")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
response <- httpJSON "https://api.coin.z.com/public/v1/status"
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Status();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Status()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/status";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/status"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"status": "OPEN"
},
"responsetime": "2019-03-19T02:15:06.001Z"
}
取引所の稼動状態を取得します。
Request
GET /public/v1/status
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
status | string | 取引所ステータス: MAINTENANCE PREOPEN OPEN |
最新レート
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/ticker?symbol=BTC';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/ticker?symbol=BTC'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/ticker?symbol=BTC"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/ticker?symbol=BTC'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/ticker?symbol=BTC"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/ticker?symbol=BTC';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/ticker?symbol=BTC")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/ticker"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "BTC")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Ticker();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Ticker()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/ticker?symbol=BTC";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/ticker?symbol=BTC"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"ask": "750760",
"bid": "750600",
"high": "762302",
"last": "756662",
"low": "704874",
"symbol": "BTC",
"timestamp": "2018-03-30T12:34:56.789Z",
"volume": "194785.8484"
}
],
"responsetime": "2019-03-19T02:15:06.014Z"
}
指定した銘柄の最新レートを取得します。
全銘柄分の最新レートを取得する場合はsymbolパラメータ指定無しでの実行をおすすめします。
Request
GET /public/v1/ticker
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Optional | 指定しない場合は全銘柄分の最新レートを返す。取扱銘柄はこちら |
Response
Property Name | Value | Description |
---|---|---|
list.volume | string | 24時間の取引量 |
板情報
Request example:
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/orderbooks?symbol=BTC';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/orderbooks?symbol=BTC'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/orderbooks?symbol=BTC"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/orderbooks?symbol=BTC'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/orderbooks?symbol=BTC"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/orderbooks?symbol=BTC';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/orderbooks?symbol=BTC")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/orderbooks"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "BTC")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Orderbooks();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Orderbooks()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/orderbooks?symbol=BTC";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/orderbooks?symbol=BTC"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"asks": [
{
"price": "455659",
"size": "0.1"
}
],
"bids": [
{
"price": "455659",
"size": "0.1"
}
],
"symbol": "BTC"
},
"responsetime": "2019-03-19T02:15:06.026Z"
}
指定した銘柄の板情報(snapshot)を取得します。
Request
GET /public/v1/orderbooks
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
Response
Property Name | Value | Description |
---|---|---|
asks | array | 売り注文の情報(最良気配から昇順) |
bids | array | 買い注文の情報(最良気配から降順) |
取引履歴
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/trades?symbol=BTC&page=1&count=10';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/trades?symbol=BTC&page=1&count=10'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/trades?symbol=BTC&page=1&count=10"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/trades?symbol=BTC&page=1&count=10'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/trades?symbol=BTC&page=1&count=10"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/trades?symbol=BTC&page=1&count=10';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/trades?symbol=BTC&page=1&count=10")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/trades"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "BTC"), ("page", Just "1"), ("count", Just "10")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Trades();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Trades()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/trades?symbol=BTC&page=1&count=10";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/trades?symbol=BTC&page=1&count=10"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"currentPage": 1,
"count": 30
},
"list": [
{
"price": "750760",
"side": "BUY",
"size": "0.1",
"timestamp": "2018-03-30T12:34:56.789Z"
}
]
},
"responsetime": "2019-03-28T09:28:07.980Z"
}
指定した銘柄の取引履歴(取引日時の降順)を取得します。
Request
GET /public/v1/trades
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
page | number | Optional | 取得対象ページ: 指定しない場合は1を指定したとして動作する。 |
count | number | Optional | 1ページ当りの取得件数: 指定しない場合は100(最大値)を指定したとして動作する。 |
Response
Property Name | Value | Description |
---|---|---|
price | string | 約定価格 |
side | string | 売買区分: BUY SELL |
size | string | 約定数量 |
timestamp | string | 約定日時 |
KLine情報の取得
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/klines?symbol=BTC&interval=1min&date=20210417';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/klines?symbol=BTC&interval=1min&date=20210417'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/klines?symbol=BTC&interval=1min&date=20210417"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/klines?symbol=BTC&interval=1min&date=20210417'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/klines?symbol=BTC&interval=1min&date=20210417"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/klines?symbol=BTC&interval=1min&date=20210417';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/klines?symbol=BTC&interval=1min&date=20210417")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/klines"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "BTC"), ("interval", Just "1min"), ("date", Just "20210417")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Klines();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Klines()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/klines?symbol=BTC&interval=1min&date=20210417";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/klines?symbol=BTC&interval=1min&date=20210417"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"openTime":"1618588800000",
"open":"6418255",
"high":"6518250",
"low":"6318250",
"close":"6418253",
"volume":"0.0001"
},
{
"openTime":"1618588860000",
"open":"6418251",
"high":"6418252",
"low":"6415250",
"close":"6418245",
"volume":"0.0001"
}
],
"responsetime": "2019-03-28T09:28:07.980Z"
}
指定した銘柄の四本値と取引量(開始時刻の昇順)を取得します。
Request
GET /public/v1/klines
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
interval | string | Required |
1min 5min 10min 15min 30min 1hour 4hour 8hour 12hour 1day 1week 1month |
date | string | Required |
指定可能な日付フォーマット: YYYYMMDD YYYY YYYYMMDD で指定できるintervalの種類 : 1min 5min 10min 15min 30min 1hour ※20210415以降、指定可能です。日本時間朝6:00に新しい日付に切り替わります。YYYY で指定できるintervalの種類 : 4hour 8hour 12hour 1day 1week 1month ※当社取扱開始年以降、指定可能です。取扱開始日はこちら |
Response
Property Name | Value | Description |
---|---|---|
openTime | string | 開始時刻のunixタイムスタンプ(ミリ秒) |
open | string | 始値 |
high | string | 高値 |
low | string | 安値 |
close | string | 終値 |
volume | string | 取引量 |
取引ルール
Request example:
const axios = require('axios');
const endPoint = 'https://api.coin.z.com/public';
const path = '/v1/symbols';
axios.get(endPoint + path)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
.finally(function () {});
import requests
import json
endPoint = 'https://api.coin.z.com/public'
path = '/v1/symbols'
response = requests.get(endPoint + path)
print(json.dumps(response.json(), indent=2))
package main
import (
"fmt"
"io"
"net/http"
"encoding/json"
"bytes"
)
func main() {
endPoint := "https://api.coin.z.com/public"
path := "/v1/symbols"
response, _ := http.Get(endPoint + path)
body, _ := io.ReadAll(response.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'uri'
require 'json'
endPoint = 'https://api.coin.z.com/public'
path = '/v1/symbols'
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
var endPoint = "https://api.coin.z.com/public"
var path = "/v1/symbols"
var method = "GET"
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$endPoint = 'https://api.coin.z.com/public';
$path = '/v1/symbols';
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
extern crate reqwest;
fn main() {
let body = reqwest::blocking::get("https://api.coin.z.com/public/v1/symbols")
.expect("Failed")
.text();
println!("body = {:?}", body);
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy.Char8 as S8
import Network.HTTP.Simple
main :: IO ()
main = do
request' <- parseRequest "https://api.coin.z.com/public/v1/symbols"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Orderbooks();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Orderbooks()
{
const string endpoint = "https://api.coin.z.com/public";
const string path = "/v1/symbols";
return await HttpClient.GetStringAsync(endpoint + path);
}
}
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let endPoint : String = "https://api.coin.z.com/public"
let path : String = "/v1/symbols"
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"symbol": "BTC",
"minOrderSize": "0.0001",
"maxOrderSize": "5",
"sizeStep": "0.0001",
"tickSize": "1",
"takerFee": "0.0005",
"makerFee": "-0.0001"
},
{
"symbol": "BTC_JPY",
"minOrderSize": "0.01",
"maxOrderSize": "5",
"sizeStep": "0.01",
"tickSize": "1",
"takerFee": "0",
"makerFee": "0"
}
],
"responsetime": "2022-12-15T19:22:23.792Z"
}
取引ルールを取得します。
Request
GET /public/v1/symbols
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
symbol | string | 取扱銘柄はこちら |
minOrderSize | string | 最小注文数量/回 |
maxOrderSize | string | 最大注文数量/回 |
sizeStep | string | 最小注文単位/回 |
tickSize | string | 注文価格の呼値 |
takerFee | string | taker手数料 |
makerFee | string | maker手数料 |
Public WebSocket API
- サーバーから1分に1回クライアントへpingを送り、3回連続でクライアントからの応答(pong)が無かった場合は、自動的に切断されます。
最新レート
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/public/v1");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/public/v1')
def on_open(self):
message = {
"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/public/v1"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/public/v1")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "ticker",
:symbol => 'BTC'
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/public/v1"
var sendMsg = """
{"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// 事前に以下の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();
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/public/v1" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = Ticker();
task.Wait();
}
static async Task Ticker()
{
const string endpoint = "wss://api.coin.z.com/ws/public/v1";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/public/v1");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"BTC\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/public/v1")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "ticker",
"symbol": "BTC"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel":"ticker",
"ask": "750760",
"bid": "750600",
"high": "762302",
"last": "756662",
"low": "704874",
"symbol": "BTC",
"timestamp": "2018-03-30T12:34:56.789Z",
"volume": "194785.8484"
}
指定した銘柄の最新レートを受信します。
subscribe
後、最新レートが配信されます。
Parameters
- Parameter type: JSON
Property Name | Type | Required | Available Values |
---|---|---|---|
command | string | Required |
subscribe unsubscribe |
channel | string | Required |
ticker |
symbol | string | Required |
取扱銘柄はこちら |
Response
Property Name | Value | Description |
---|---|---|
channel | string | ticker |
ask | string | 現在の売注文の最良気配値 |
bid | string | 現在の買注文の最良気配値 |
high | string | 当日の最高値(最終取引価格) |
last | string | 最終取引価格 |
low | string | 当日の最安値(最終取引価格) |
symbol | string | 取扱銘柄はこちら |
timestamp | string | 約定時のタイムスタンプ |
volume | string | 24時間の取引量 |
unsubscribe
でリクエストした場合のResponseはありません。
板情報
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/public/v1");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/public/v1')
def on_open(self):
message = {
"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/public/v1"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/public/v1")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "orderbooks",
:symbol => 'BTC'
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/public/v1"
var sendMsg = """
{"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// 事前に以下の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() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/public/v1" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = Orderbooks();
task.Wait();
}
static async Task Orderbooks()
{
const string endpoint = "wss://api.coin.z.com/ws/public/v1";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/public/v1");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"orderbooks\", \"symbol\": \"BTC\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/public/v1")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "orderbooks",
"symbol": "BTC"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel":"orderbooks",
"asks": [
{"price": "455659","size": "0.1"},
{"price": "455658","size": "0.2"}
],
"bids": [
{"price": "455665","size": "0.1"},
{"price": "455655","size": "0.3"}
],
"symbol": "BTC",
"timestamp": "2018-03-30T12:34:56.789Z"
}
指定した銘柄の板情報(snapshot)を受信します。
subscribe
後、板情報が配信されます。
Parameters
- Parameter type: JSON
Property Name | Type | Required | Available Values |
---|---|---|---|
command | string | Required |
subscribe unsubscribe |
channel | string | Required |
orderbooks |
symbol | string | Required |
取扱銘柄はこちら |
Response
Property Name | Value | Description |
---|---|---|
channel | string | orderbooks |
asks | array | 売り注文の情報(最良気配から昇順) |
bids | array | 買い注文の情報(最良気配から降順) |
symbol | string | 取扱銘柄はこちら |
timestamp | string | 配信日時 |
unsubscribe
でリクエストした場合のResponseはありません。
取引履歴
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/public/v1");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "trades",
"symbol": "BTC"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/public/v1')
def on_open(self):
message = {
"command": "subscribe",
"channel": "trades",
"symbol": "BTC"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/public/v1"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "trades",
"symbol": "BTC"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/public/v1")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "trades",
:symbol => 'BTC'
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/public/v1"
var sendMsg = """
{"command": "subscribe",
"channel": "trades",
"symbol": "BTC"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// 事前に以下の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() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/public/v1" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = Trades();
task.Wait();
}
static async Task Trades()
{
const string endpoint = "wss://api.coin.z.com/ws/public/v1";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/public/v1");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"trades\", \"symbol\": \"BTC\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/public/v1")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "trades",
"symbol": "BTC"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel":"trades",
"price": "750760",
"side": "BUY",
"size": "0.1",
"timestamp": "2018-03-30T12:34:56.789Z",
"symbol": "BTC"
}
指定した銘柄の最新の取引履歴を受信します。
subscribe
後、最新の取引履歴が配信されます。
Parameters
- Parameter type: JSON
Property Name | Type | Required | Available Values |
---|---|---|---|
command | string | Required |
subscribe unsubscribe |
channel | string | Required |
trades |
symbol | string | Required |
取扱銘柄はこちら |
option | string | Optional | TAKER_ONLY ※optionが指定された場合、TAKERのデータのみを送信します。 ※同一銘柄で複数回subscribeした場合は後にsubscribeしたものが有効となります。 |
Response
Property Name | Value | Description |
---|---|---|
channel | string | trades |
price | string | 約定価格 |
side | string | 売買区分: BUY SELL |
size | string | 約定数量 |
timestamp | string | 約定日時 |
symbol | string | 取扱銘柄はこちら |
unsubscribe
でリクエストした場合のResponseはありません。
Private API
余力情報を取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/margin';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/margin'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/margin"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/margin'
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
import org.json.JSONObject
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/margin"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/margin';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
margin().unwrap();
}
fn margin() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/margin";
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/margin"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Margin();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Margin()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/margin";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/margin"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"actualProfitLoss": "68286188",
"availableAmount": "57262506",
"margin": "1021682",
"marginCallStatus": "NORMAL",
"marginRatio": "6683.6",
"profitLoss": "0",
"transferableAmount": "57262506"
},
"responsetime": "2019-03-19T02:15:06.051Z"
}
余力情報を取得します。
Request
GET /private/v1/account/margin
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
actualProfitLoss | string | 時価評価総額 |
availableAmount | string | 取引余力 |
margin | string | 拘束証拠金 |
marginCallStatus | string | 追証ステータス: NORMAL MARGIN_CALL LOSSCUT |
marginRatio | string | 証拠金維持率 |
profitLoss | string | 評価損益 |
transferableAmount | string | 振替可能額 |
資産残高を取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/assets';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/assets'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/assets"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/assets'
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/assets"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/assets';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/assets";
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/assets"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/assets";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/assets"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"amount": "993982448",
"available": "993982448",
"conversionRate": "1",
"symbol": "JPY"
},
{
"amount": "4.0002",
"available": "4.0002",
"conversionRate": "859614",
"symbol": "BTC"
}
],
"responsetime": "2019-03-19T02:15:06.055Z"
}
資産残高を取得します。
Request
GET /private/v1/account/assets
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
amount | string | 残高 |
available | string | 利用可能金額(残高 - 出金予定額) |
conversionRate | string | 円転レート(販売所での売却価格です。※販売所で取り扱いのない銘柄は、取引所現物での最終約定価格です。) |
symbol | string | 資産残高銘柄: 取扱銘柄はこちら ※取引所(現物取引)の取扱銘柄のみAPIでご注文いただけます。取扱銘柄はこちら |
取引高情報を取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/tradingVolume';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/tradingVolume'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/tradingVolume"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/tradingVolume'
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/tradingVolume"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/tradingVolume';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/tradingVolume";
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/tradingVolume"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/tradingVolume";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/tradingVolume"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"jpyVolume": "9988888",
"tierLevel": 1,
"limit": [
{
"symbol": "BTC/JPY",
"todayLimitOpenSize": "10000",
"takerFee": "0",
"makerFee": "0"
},
{
"symbol": "BTC",
"todayLimitBuySize": "98",
"todayLimitSellSize": "102",
"takerFee": "0.0015",
"makerFee": "-0.0007"
}
]
},
"responsetime": "2019-03-19T02:15:06.055Z"
}
取引高情報を取得します。
Request
GET /private/v1/account/tradingVolume
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
jpyVolume | string | 今週の取引高(日本円) |
tierLevel | number | 現在の取引高レベル: 1 2 |
limit.symbol | string | 取扱銘柄はこちら |
limit.todayLimitOpenSize | string | 1日の最大取引数量の残量(新規) ※レバレッジ銘柄の場合のみ |
limit.todayLimitBuySize | string | 1日の最大取引数量の残量(購入) ※現物銘柄の場合のみ |
limit.todayLimitSellSize | string | 1日の最大取引数量の残量(売却) ※現物銘柄の場合のみ |
limit.takerFee | string | Taker手数料 |
limit.makerFee | string | Maker手数料 |
日本円の入金履歴の取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/fiatDeposit/history';
const parameters = '?fromTimestamp=2024-03-01T00:00:00.000Z';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/fiatDeposit/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "fromTimestamp": "2024-03-01T00:00:00.000Z" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/fiatDeposit/history"
parameters := "?fromTimestamp=2024-03-01T00:00:00.000Z"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/fiatDeposit/history'
parameters = {
:fromTimestamp => '2024-03-01T00:00:00.000Z'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/fiatDeposit/history"
var parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/fiatDeposit/history';
$parameters = '?fromTimestamp=2024-03-01T00:00:00.000Z';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/fiatDeposit/history";
let mut parameters = HashMap::new();
parameters.insert("fromTimestamp", "2024-03-01T00:00:00.000Z");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/fiatDeposit/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("fromTimestamp", Just "2024-03-01T00:00:00.000Z")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/fiatDeposit/history";
const string parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/fiatDeposit/history"
let parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"amount": "50000",
"fee": "0",
"status": "EXECUTED",
"symbol": "JPY",
"timestamp": "2021-01-01T13:47:12.791Z"
}
],
"responsetime": "2024-02-28T11:48:57.996Z"
}
日本円の入金履歴を取得します。
Request
GET /private/v1/account/fiatDeposit/history
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
fromTimestamp | string | Required |
検索開始時刻(UTC時刻):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:00:00.000Z)※ fromTimestampのみ指定された場合、toTimestampは「fromTimestamp + 30分」となります。 |
toTimestamp | string | Optional | 検索終了時刻(UTC時刻):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:30:00.000Z)※ fromTimestampとtoTimestampの差は最大30分です。 |
Response
Property Name | Value | Description |
---|---|---|
amount | string | 金額 |
fee | string | 手数料 |
status | string | ステータス: EXECUTED |
symbol | string | 銘柄: JPY |
timestamp | string | 完了時刻(UTC時刻) |
日本円の出金履歴の取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/fiatWithdrawal/history';
const parameters = '?fromTimestamp=2024-03-01T00:00:00.000Z';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/fiatWithdrawal/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "fromTimestamp": "2024-03-01T00:00:00.000Z" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/fiatWithdrawal/history"
parameters := "?fromTimestamp=2024-03-01T00:00:00.000Z"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/fiatWithdrawal/history'
parameters = {
:fromTimestamp => '2024-03-01T00:00:00.000Z'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/fiatWithdrawal/history"
var parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/fiatWithdrawal/history';
$parameters = '?fromTimestamp=2024-03-01T00:00:00.000Z';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/fiatWithdrawal/history";
let mut parameters = HashMap::new();
parameters.insert("fromTimestamp", "2024-03-01T00:00:00.000Z");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/fiatWithdrawal/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("fromTimestamp", Just "2024-03-01T00:00:00.000Z")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/fiatWithdrawal/history";
const string parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/fiatWithdrawal/history"
let parameters = "?fromTimestamp=2024-03-01T00:00:00.000Z"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"amount": "50000",
"fee": "0",
"status": "EXECUTED",
"symbol": "JPY",
"timestamp": "2021-01-01T13:47:12.791Z"
}
],
"responsetime": "2024-02-28T11:48:57.996Z"
}
日本円の出金履歴を取得します。
Request
GET /private/v1/account/fiatWithdrawal/history
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
fromTimestamp | string | Required |
検索開始時刻(UTC時刻):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:00:00.000Z)※ fromTimestampのみ指定された場合、toTimestampは「fromTimestamp + 30分」となります。 |
toTimestamp | string | Optional | 検索終了時刻(UTC時刻):YYYY-MM-DDTHH:MM:SS.SSSZ format string (e.g. 2023-03-01T00:30:00.000Z)※ fromTimestampとtoTimestampの差は最大30分です。 |
Response
Property Name | Value | Description |
---|---|---|
amount | string | 金額 |
fee | string | 手数料 |
status | string | ステータス: EXECUTED |
symbol | string | 取扱銘柄はこちら: JPY |
timestamp | string | 完了時刻(UTC時刻) |
暗号資産の預入履歴の取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/deposit/history';
const parameters = '?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/deposit/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "symbol": "BTC", "fromTimestamp": "2024-03-01T00:00:00.000Z" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/deposit/history"
parameters := "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/deposit/history'
parameters = {
:symbol => 'BTC',
:fromTimestamp => '2024-03-01T00:00:00.000Z'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/deposit/history"
var parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/deposit/history';
$parameters = '?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/deposit/history";
let parameters = json!({
"symbol": "BTC",
"fromTimestamp": "2024-03-01T00:00:00.000Z"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/deposit/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC"), ("fromTimestamp", Just "2024-03-01T00:00:00.000Z")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/deposit/history";
const string parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/deposit/history"
let parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"address": "xxx",
"amount": "0.9503",
"status": "EXECUTED",
"symbol": "BTC",
"timestamp": "2021-10-05T06:04:46.241Z",
"txHash": "yyy"
}
],
"responsetime": "2024-02-28T12:20:07.103Z"
}
暗号資産の預入履歴を取得します。
Request
GET /private/v1/account/deposit/history
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
fromTimestamp | string | Required |
検索開始時刻(UTC時刻):YYYY-MM-DDTHH:MM:SS.SSSZフォーマットの文字列(例:2024-03-01T00:00:00.000Z)※ fromTimestampのみ指定された場合、toTimestampは「fromTimestamp + 30分」となります。 |
toTimestamp | string | Optional | 検索終了時刻(UTC時刻):YYYY-MM-DDTHH:MM:SS.SSSZフォーマットの文字列(例:2024-03-01T00:30:00.000Z)※ fromTimestampとtoTimestampの差は最大30分です。 |
Response
Property Name | Value | Description |
---|---|---|
address | string | アドレス |
amount | string | 数量 |
fee | string | 手数料 |
status | string | ステータス: EXECUTED |
symbol | string | 取扱銘柄はこちら |
timestamp | string | 完了時刻(UTC時刻) |
txHash | string | トランザクションハッシュ |
暗号資産の送付履歴の取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/withdrawal/history';
const parameters = '?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/history'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "symbol": "BTC", "fromTimestamp": "2024-03-01T00:00:00.000Z" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/withdrawal/history"
parameters := "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/withdrawal/history'
parameters = {
:symbol => 'BTC',
:fromTimestamp => '2024-03-01T00:00:00.000Z'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/withdrawal/history"
var parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/withdrawal/history';
$parameters = '?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
assets().unwrap();
}
fn assets() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/withdrawal/history";
let parameters = json!({
"symbol": "BTC",
"fromTimestamp": "2024-03-01T00:00:00.000Z"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/withdrawal/history"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC"), ("fromTimestamp", Just "2024-03-01T00:00:00.000Z")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Assets();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Assets()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/withdrawal/history";
const string parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/withdrawal/history"
let parameters = "?symbol=BTC&fromTimestamp=2024-03-01T00:00:00.000Z"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"address": "xxx",
"amount": "0.9503",
"status": "EXECUTED",
"symbol": "BTC",
"timestamp": "2021-10-05T06:04:46.241Z",
"txHash": "yyy"
}
],
"responsetime": "2024-02-28T12:20:07.103Z"
}
暗号資産の送付履歴を取得します。
Request
GET /private/v1/account/withdrawal/history
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
fromTimestamp | string | Required |
検索開始時刻(UTC時刻):YYYY-MM-DDTHH:MM:SS.SSSZフォーマットの文字列(例:2024-03-01T00:00:00.000Z)※ fromTimestampのみ指定された場合、toTimestampは「fromTimestamp + 30分」となります。 |
toTimestamp | string | Optional | 検索終了時刻(UTC時刻):YYYY-MM-DDTHH:MM:SS.SSSZフォーマットの文字列(例:2024-03-01T00:30:00.000Z)※ fromTimestampとtoTimestampの差は最大30分です。 |
Response
Property Name | Value | Description |
---|---|---|
address | string | アドレス |
amount | string | 数量 |
fee | string | 手数料 |
status | string | ステータス: EXECUTED |
symbol | string | 取扱銘柄はこちら |
timestamp | string | 完了時刻(UTC時刻) |
txHash | string | トランザクションハッシュ |
注文情報取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/orders';
const parameters = '?orderId=123456789,223456789';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/orders'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = { "orderId": "123456789,223456789" }
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/orders"
parameters := "?orderId=123456789,223456789"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/orders'
parameters = {
:orderId => '123456789,223456789'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/orders"
var parameters = "?orderId=123456789,223456789"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/orders';
$parameters = '?orderId=123456789,223456789';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
orders().unwrap();
}
fn orders() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/orders";
let mut parameters = HashMap::new();
parameters.insert("orderId", "123456789,223456789");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/orders"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("orderId", Just "123456789,223456789")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Orders();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Orders()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/orders";
const string parameters = "?orderId=123456789,223456789";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/orders"
let parameters = "?orderId=123456789,223456789"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"orderId": 223456789,
"rootOrderId": 223456789,
"symbol": "BTC_JPY",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "0.02",
"executedSize": "0.02",
"price": "1430001",
"losscutPrice": "0",
"status": "EXECUTED",
"timeInForce": "FAS",
"timestamp": "2020-10-14T20:18:59.343Z"
},
{
"rootOrderId": 123456789,
"orderId": 123456789,
"symbol": "BTC",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "1",
"executedSize": "0",
"price": "900000",
"losscutPrice": "0",
"status": "CANCELED",
"cancelType": "USER",
"timeInForce": "FAS",
"timestamp": "2019-03-19T02:15:06.059Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.059Z"
}
指定した注文IDの注文情報を取得します。
対象: 現物取引、レバレッジ取引
Request
GET /private/v1/orders
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
orderId | string | Required |
カンマ区切りで最大10件まで指定可能。 |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: NORMAL LOSSCUT |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 発注数量 |
executedSize | string | 約定数量 |
price | string | 注文価格 (MARKET 注文の場合は"0") |
losscutPrice | string | ロスカットレート (現物取引や未設定の場合は"0") |
status | string | 注文ステータス: WAITING ORDERED MODIFYING CANCELLING CANCELED EXECUTED EXPIRED ※逆指値注文の場合は WAITING が有効 |
cancelType | string | 取消区分: USER POSITION_LOSSCUT INSUFFICIENT_BALANCE INSUFFICIENT_MARGIN ACCOUNT_LOSSCUT MARGIN_CALL MARGIN_CALL_LOSSCUT EXPIRED_FAK EXPIRED_FOK EXPIRED_SOK EXPIRED_SELFTRADE ※statusが CANCELLING 、CANCELED またはEXPIRED の場合のみ返ってきます。 |
timeInForce | string | 執行数量条件: FAK FAS FOK (Post-onlyの場合はSOK ) |
timestamp | string | 注文日時 |
有効注文一覧
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/activeOrders';
const parameters = '?symbol=BTC&page=1&count=10';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/activeOrders'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"symbol": "BTC",
"page": 1,
"count": 10
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/activeOrders"
parameters := "?symbol=BTC&page=1&count=10"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/activeOrders'
parameters = {
:symbol => 'BTC',
:page => 1,
:count => 10
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/activeOrders"
var parameters = "?symbol=BTC&page=1&count=10"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/activeOrders';
$parameters = '?symbol=BTC&page=1&count=10';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
active_orders().unwrap();
}
fn active_orders() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/activeOrders";
let parameters = json!({
"symbol": "BTC",
"page": 1,
"count": 10
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/activeOrders"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC"), ("page", Just "1"), ("count", Just "10")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = ActiveOrders();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> ActiveOrders()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/activeOrders";
const string parameters = "?symbol=BTC&page=1&count=10";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/activeOrders"
let parameters = "?symbol=BTC&page=1&count=10"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"currentPage": 1,
"count": 30
},
"list": [
{
"rootOrderId": 123456789,
"orderId": 123456789,
"symbol": "BTC",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "1",
"executedSize": "0",
"price": "840000",
"losscutPrice": "0",
"status": "ORDERED",
"timeInForce": "FAS",
"timestamp": "2019-03-19T01:07:24.217Z"
}
]
},
"responsetime": "2019-03-19T01:07:24.217Z"
}
有効注文一覧を取得します。
対象: 現物取引、レバレッジ取引
Request
GET /private/v1/activeOrders
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
page | number | Optional | 取得対象ページ: 指定しない場合は1を指定したとして動作する。 |
count | number | Optional | 1ページ当りの取得件数: 指定しない場合は100(最大値)を指定したとして動作する。 |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: NORMAL LOSSCUT |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 発注数量 |
executedSize | string | 約定数量 |
price | string | 注文価格 (MARKET 注文の場合は"0") |
losscutPrice | string | ロスカットレート (現物取引や未設定の場合は"0") |
status | string | 注文ステータス: WAITING ORDERED MODIFYING CANCELLING ※逆指値注文の場合は WAITING が有効 |
timeInForce | string | 執行数量条件: FAK FAS FOK (Post-onlyの場合はSOK ) |
timestamp | string | 注文日時 |
約定情報取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/executions';
const parameters = '?executionId=72123911,92123912';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/executions'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"executionId": "72123911,92123912"
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/executions"
parameters := "?executionId=72123911,92123912"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/executions'
parameters = {
:executionId => '72123911,92123912'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/executions"
var parameters = "?executionId=72123911,92123912"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/executions';
$parameters = '?executionId=72123911,92123912';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
executions().unwrap();
}
fn executions() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/executions";
let mut parameters = HashMap::new();
parameters.insert("executionId", "72123911,92123912");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/executions"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("executionId", Just "72123911,92123912")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Executions();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Executions()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/executions";
const string parameters = "?executionId=72123911,92123912";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/executions"
let parameters = "?executionId=72123911,92123912"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"executionId": 92123912,
"orderId": 223456789,
"positionId": 1234567,
"symbol": "BTC_JPY",
"side": "BUY",
"settleType": "OPEN",
"size": "0.02",
"price": "1900000",
"lossGain": "0",
"fee": "223",
"timestamp": "2020-11-24T21:27:04.764Z"
},
{
"executionId": 72123911,
"orderId": 123456789,
"positionId": 1234567,
"symbol": "BTC",
"side": "BUY",
"settleType": "OPEN",
"size": "0.7361",
"price": "877404",
"lossGain": "0",
"fee": "323",
"timestamp": "2019-03-19T02:15:06.081Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.081Z"
}
約定情報を取得します。
対象: 現物取引、レバレッジ取引
orderId
executionId
いずれか一つが必須です。2つ同時には設定できません。
Request
GET /private/v1/executions
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
orderId | number | * |
orderId executionId いずれか一つが必須。 |
executionId | string | * |
orderId executionId いずれか一つが必須。executionId の場合のみカンマ区切りで最大10件まで指定可能。 |
Response
Property Name | Value | Description |
---|---|---|
executionId | number | 約定ID |
orderId | number | 注文ID |
positionId | number | 建玉ID ※レバレッジの場合のみ |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 約定数量 |
price | string | 約定レート |
lossGain | string | 決済損益 |
fee | string | 取引手数料※Takerの場合はプラスの値、Makerの場合はマイナスの値が返ってきます。 |
timestamp | string | 約定日時 |
最新の約定一覧
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/latestExecutions';
const parameters = '?symbol=BTC&page=1&count=100';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/latestExecutions'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"symbol": "BTC",
"page": 1,
"count": 100
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/latestExecutions"
parameters := "?symbol=BTC&page=1&count=100"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/latestExecutions'
parameters = {
:symbol => 'BTC',
:page => 1,
:count => 100
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/latestExecutions"
var parameters = "?symbol=BTC&page=1&count=100"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/latestExecutions';
$parameters = '?symbol=BTC&page=1&count=100';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
latest_executions().unwrap();
}
fn latest_executions() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/latestExecutions";
let parameters = json!({
"symbol": "BTC",
"page": 1,
"count": 100,
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/latestExecutions"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC"), ("page", Just "1"), ("count", Just "100")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = LatestExecutions();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> LatestExecutions()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/latestExecutions";
const string parameters = "?symbol=BTC&page=1&count=100";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/latestExecutions"
let parameters = "?symbol=BTC&page=1&count=100"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"currentPage": 1,
"count": 30
},
"list": [
{
"executionId": 72123911,
"orderId": 123456789,
"positionId": 1234567,
"symbol": "BTC",
"side": "BUY",
"settleType": "OPEN",
"size": "0.7361",
"price": "877404",
"lossGain": "0",
"fee": "323",
"timestamp": "2019-03-19T02:15:06.086Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.086Z"
}
最新約定一覧を取得します。
対象: 現物取引、レバレッジ取引
- 直近1日分の約定情報を返します。
Request
GET /private/v1/latestExecutions
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
page | number | Optional | 取得対象ページ: 指定しない場合は1を指定したとして動作する。 |
count | number | Optional | 1ページ当りの取得件数: 指定しない場合は100(最大値)を指定したとして動作する。 |
Response
Property Name | Value | Description |
---|---|---|
executionId | number | 約定ID |
orderId | number | 注文ID |
positionId | number | 建玉ID ※レバレッジの場合のみ |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 約定数量 |
price | string | 約定レート |
lossGain | string | 決済損益 |
fee | string | 取引手数料※Takerの場合はプラスの値、Makerの場合はマイナスの値が返ってきます。 |
timestamp | string | 約定日時 |
建玉一覧を取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/openPositions';
const parameters = '?symbol=BTC_JPY&page=1&count=100';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/openPositions'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"symbol": "BTC_JPY",
"page": 1,
"count": 100
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/openPositions"
parameters := "?symbol=BTC_JPY&page=1&count=100"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/openPositions'
parameters = {
:symbol => 'BTC_JPY',
:page => 1,
:count => 100
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/openPositions"
var parameters = "?symbol=BTC_JPY&page=1&count=100"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/openPositions';
$parameters = '?symbol=BTC_JPY&page=1&count=100';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
open_positions().unwrap();
}
fn open_positions() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/openPositions";
let parameters = json!({
"symbol": "BTC_JPY",
"page": 1,
"count": 100,
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/openPositions"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC_JPY"), ("page", Just "1"), ("count", Just "100")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = OpenPositions();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> OpenPositions()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/openPositions";
const string parameters = "?symbol=BTC_JPY&page=1&count=100";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/openPositions"
let parameters = "?symbol=BTC_JPY&page=1&count=100"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"pagination": {
"currentPage": 1,
"count": 30
},
"list": [
{
"positionId": 1234567,
"symbol": "BTC_JPY",
"side": "BUY",
"size": "0.22",
"orderdSize": "0",
"price": "876045",
"lossGain": "14",
"leverage": "4",
"losscutPrice": "766540",
"timestamp": "2019-03-19T02:15:06.094Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.095Z"
}
有効建玉一覧を取得します。
対象: レバレッジ取引
Request
GET /private/v1/openPositions
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
レバレッジ取扱銘柄はこちら |
page | number | Optional | 取得対象ページ: 指定しない場合は1を指定したとして動作する。 |
count | number | Optional | 1ページ当りの取得件数: 指定しない場合は100(最大値)を指定したとして動作する。 |
Response
Property Name | Value | Description |
---|---|---|
positionId | number | 建玉ID |
symbol | string | レバレッジ取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
size | string | 建玉数量 |
orderdSize | string | 発注中数量 |
price | string | 建玉レート |
lossGain | string | 評価損益 |
leverage | string | レバレッジ |
losscutPrice | string | ロスカットレート |
timestamp | string | 約定日時 |
建玉サマリーを取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'GET';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/positionSummary';
const parameters = '?symbol=BTC_JPY';
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.get(endPoint + path + parameters, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/positionSummary'
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
parameters = {
"symbol": "BTC_JPY"
}
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, params=parameters)
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "GET"
endPoint := "https://api.coin.z.com/private"
path := "/v1/positionSummary"
parameters := "?symbol=BTC_JPY"
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path+parameters, nil)
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'GET'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/positionSummary'
parameters = {
:symbol => 'BTC_JPY'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
uri.query = URI.encode_www_form(parameters)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "GET"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/positionSummary"
var parameters = "?symbol=BTC_JPY"
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path + parameters)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'GET';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/positionSummary';
$parameters = '?symbol=BTC_JPY';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
position_summary().unwrap();
}
fn position_summary() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "GET";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/positionSummary";
let mut parameters = HashMap::new();
parameters.insert("symbol", "BTC_JPY");
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.get(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.query(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "GET"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/positionSummary"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestQueryString [("symbol", Just "BTC_JPY")]
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = PositionSummary();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> PositionSummary()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "GET";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/positionSummary";
const string parameters = "?symbol=BTC_JPY";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path + parameters))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "GET"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/positionSummary"
let parameters = "?symbol=BTC_JPY"
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path + parameters)!)
request.httpMethod = method
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"list": [
{
"averagePositionRate": "715656",
"positionLossGain": "250675",
"side": "BUY",
"sumOrderQuantity": "2",
"sumPositionQuantity": "11.6999",
"symbol": "BTC_JPY"
}
]
},
"responsetime": "2019-03-19T02:15:06.102Z"
}
建玉サマリーを取得します。
対象: レバレッジ取引
- 指定した銘柄の建玉サマリーを売買区分(買/売)ごとに取得ができます。symbolパラメータ指定無しの場合は、保有している全銘柄の建玉サマリーを売買区分(買/売)ごとに取得します。
Request
GET /private/v1/positionSummary
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Optional | 指定しない場合は全銘柄分の建玉サマリーを返す。 レバレッジ取扱銘柄はこちら |
Response
Property Name | Value | Description |
---|---|---|
averagePositionRate | string | 平均建玉レート |
positionLossGain | string | 評価損益 |
side | string | 売買区分: BUY SELL |
sumOrderQuantity | string | 発注中数量 |
sumPositionQuantity | string | 建玉数量 |
symbol | string | レバレッジ取扱銘柄はこちら |
口座振替
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/account/transfer';
const reqBody = JSON.stringify({
amount: "100000",
transferType: "WITHDRAWAL"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/transfer'
reqBody = {
"amount": "100000",
"transferType": "WITHDRAWAL"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.get(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/account/transfer"
reqBody := (`{
"amount": "100000",
"transferType": "WITHDRAWAL"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/account/transfer'
reqBody = {
:amount => '100000',
:transferType => 'WITHDRAWAL'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Get.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/account/transfer"
var reqBody = """
{"amount": "100000",
"transferType": "WITHDRAWAL"
}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/account/transfer';
$reqBody = '{
"amount": "100000",
"transferType": "WITHDRAWAL"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
transfer().unwrap();
}
fn transfer() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/account/transfer";
let parameters = json!({
"amount": "100000",
"transferType": "WITHDRAWAL"
});
let text = format!("{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/account/transfer"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"amount": "100000",
"transferType": "WITHDRAWAL"
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = transfer();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> transfer()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/account/transfer";
var reqBody = "{ \"amount\": \"100000\", " +
"\"transferType\": \"WITHDRAWAL\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/account/transfer"
let reqBodyStr = """
{
"amount": "100000",
"transferType": "WITHDRAWAL"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [
{
"transferredAmount": "100000"
}
],
"responsetime": "2019-03-19T02:15:06.055Z"
}
暗号資産口座から外国為替FX口座へ、もしくは外国為替FXから暗号資産口座へ日本円を振替えます。
口座振替のリクエストは3分に1回が上限です。
Request
POST /private/v1/account/transfer
Parameters
- Parameter content type:
application/json
Property Name | Value | Description |
---|---|---|
amount | string | 振替金額(日本円) |
transferType | string | 振替区分: WITHDRAWAL DEPOSIT |
Response
Property Name | Value | Description |
---|---|---|
transferredAmount | string | 口座振替金額 |
注文
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/order';
const reqBody = JSON.stringify({
symbol: "BTC_JPY",
side: "BUY",
executionType: "LIMIT",
timeInForce: "FAS",
price: "430001",
losscutPrice: "30012",
size: "0.02"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/order'
reqBody = {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/order"
reqBody := (`{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/order'
reqBody = {
:symbol => 'BTC_JPY',
:side => 'BUY',
:executionType => 'LIMIT',
:timeInForce => 'FAS',
:price => '430001',
:losscutPrice => '30012',
:size => '0.02'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/order"
var reqBody = """
{"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/order';
$reqBody = '{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
order().unwrap();
}
fn order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/order";
let parameters = json!({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/order"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02" }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = Order();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> Order()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/order";
var reqBody = "{ \"symbol\": \"BTC_JPY\", " +
"\"side\": \"BUY\", " +
"\"executionType\": \"LIMIT\", " +
"\"timeInForce\": \"FAS\", " +
"\"price\": \"430001\", " +
"\"losscutPrice\": \"30012\", " +
"\"size\": \"0.02\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/order"
let reqBodyStr = """
{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "430001",
"losscutPrice": "30012",
"size": "0.02"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": "637000",
"responsetime": "2019-03-19T02:15:06.108Z"
}
新規注文をします。
対象: 現物取引、レバレッジ取引
- 現物取引: 買/売注文
- レバレッジ取引: 新規の買/売注文
Request
POST /private/v1/order
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
side | string | Required |
BUY SELL |
executionType | string | Required |
MARKET LIMIT STOP |
timeInForce | string | Optional | FAK FAS FOK ((Post-onlyの場合はSOK ) LIMIT の場合のみ設定可能 )※指定がない場合は成行と逆指値はFAK、指値はFASで注文されます。SOKが指定可能な銘柄はこちらの参照をお願いいたします。 |
price | string | *executionTypeによる |
LIMIT STOP の場合は必須、 MARKET の場合は不要。 |
losscutPrice | string | Optional | レバレッジ取引で、executionTypeが LIMIT または STOP の場合のみ設定可能。 |
size | string | Required |
|
cancelBefore | bool | Optional | true の場合、すでに有効注文がある場合に、有効注文の取消と成行注文を同時に行います。注文数量>発注可能数量の場合:注文数量≦発注可能数量となるまで、古い有効注文から順に取り消されます。注文数量≦発注可能数量の場合:有効注文の取消はされず、成行注文のみ実行されます。指定がない場合はfalse ※現物取引で、executionType:MARKET ,timeInforce:FAK ,side:SELL の場合にtrue を指定可能です。 |
Response
Property Name | Value | Description |
---|---|---|
data | string | 注文対象のorderId |
注文変更
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/changeOrder';
const reqBody = JSON.stringify({
orderId: 2,
price: "1201",
losscutPrice: "1000"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/changeOrder'
reqBody = {
"orderId": 2,
"price": "1201",
"losscutPrice": "1000"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/changeOrder"
reqBody := (`{
"orderId": 2,
"price": "1201",
"losscutPrice": "1000"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/changeOrder'
reqBody = {
:orderId => 2,
:price => '1201',
:losscutPrice => '1000'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/changeOrder"
var reqBody = """
{"orderId": 2, "price": "1201", "losscutPrice": "1000"}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/changeOrder';
$reqBody = '{
orderId: 2,
price: "1201",
losscutPrice: "1000"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
change_order().unwrap();
}
fn change_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/changeOrder";
let parameters = json!({
"orderId": 2,
"price": "1201",
"losscutPrice": "1000",
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/changeOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"orderId": 2,
"price": "1201",
"losscutPrice": "1000" }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = ChangeOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> ChangeOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/changeOrder";
var reqBody = "{ \"orderId\": 2, " +
"\"price\": \"1201\", " +
"\"losscutPrice\": \"1000\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/changeOrder"
let reqBodyStr = """
{
"orderId": 2,
"price": "1201",
"losscutPrice": "1000"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T01:07:24.557Z"
}
注文変更をします。
対象: 現物取引、レバレッジ取引
Request
POST /private/v1/changeOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
orderId | number | Required |
|
price | string | Required |
|
losscutPrice | string | Optional |
注文キャンセル
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/cancelOrder';
const reqBody = JSON.stringify({
orderId: 2
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelOrder'
reqBody = {
"orderId": 2
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/cancelOrder"
reqBody := (`{
"orderId": 2
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelOrder'
reqBody = {
:orderId => 2
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/cancelOrder"
var reqBody = """
{"orderId": 2}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/cancelOrder';
$reqBody = '{
"orderId": 2
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
cancel_order().unwrap();
}
fn cancel_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/cancelOrder";
let parameters = json!({
"orderId": 2
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/cancelOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"orderId": 2 }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CancelOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CancelOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/cancelOrder";
var reqBody = "{ \"orderId\": 2 }";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/cancelOrder"
let reqBodyStr = """
{
"orderId": 2
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T01:07:24.557Z"
}
注文取消をします。
対象: 現物取引、レバレッジ取引
Request
POST /private/v1/cancelOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
orderId | number | Required |
注文の複数キャンセル
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/cancelOrders';
const reqBody = JSON.stringify({
orderIds: [1,2,3,4]
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelOrders'
reqBody = {
"orderIds": [1,2,3,4]
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/cancelOrders"
reqBody := (`{
"orderIds": [1,2,3,4]
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelOrders'
reqBody = {
:orderIds => [1,2,3,4]
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/cancelOrders"
var reqBody = """
{"orderIds": [1,2,3,4]}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/cancelOrders';
$reqBody = '{
"orderIds": [1,2,3,4]
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
cancel_orders().unwrap();
}
fn cancel_orders() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/cancelOrders";
let parameters = json!({
"orderIds": [1,2,3,4]
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/cancelOrders"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"orderIds": [1,2,3,4] }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CancelOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CancelOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/cancelOrders";
var reqBody = "{ \"orderIds\": [1,2,3,4] }";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/cancelOrders"
let reqBodyStr = """
{
"orderIds": [1,2,3,4]
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": {
"failed": [
{
"message_code": "ERR-5122",
"message_string": "The request is invalid due to the status of the specified order.",
"orderId": 1
},
{
"message_code": "ERR-5122",
"message_string": "The request is invalid due to the status of the specified order.",
"orderId": 2
}
],
"success": [3,4]
},
"responsetime": "2019-03-19T01:07:24.557Z"
}
複数の注文を取消します。
対象: 現物取引、レバレッジ取引
- 最大10件まで注文を取消することができます。
Request
POST /private/v1/cancelOrders
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
orderIds | array | Required |
Response
Property Name | Value | Description |
---|---|---|
success | array | 取消受付に成功した注文ID |
failed | array | 取消受付に失敗した注文IDと失敗情報 |
注文の一括キャンセル
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/cancelBulkOrder';
const reqBody = JSON.stringify({
symbols: ["BTC","BTC_JPY"],
side: "BUY",
settleType: "OPEN",
desc: true
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelBulkOrder'
reqBody = {
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": True
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/cancelBulkOrder"
reqBody := (`{
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/cancelBulkOrder'
reqBody = {
:symbols => ['BTC','BTC_JPY'],
:side => 'BUY',
:settleType => 'OPEN',
:desc => true
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/cancelBulkOrder"
var reqBody = """
{"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/cancelBulkOrder';
$reqBody = '{
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
cancel_bulk_order().unwrap();
}
fn cancel_bulk_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/cancelBulkOrder";
let parameters = json!({
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/cancelBulkOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CancelOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CancelOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/cancelBulkOrder";
var reqBody = "{ \"symbols\": [\"BTC\",\"BTC_JPY\"], " +
"\"side\": \"BUY\", " +
"\"settleType\": \"OPEN\", " +
"\"desc\": true}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/cancelBulkOrder"
let reqBodyStr = """
{
"symbols": ["BTC","BTC_JPY"],
"side": "BUY",
"settleType": "OPEN",
"desc": true
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": [637000,637002],
"responsetime": "2019-03-19T01:07:24.557Z"
}
一括で注文を取消します
対象: 現物取引、レバレッジ取引
- 取消対象検索後に、最大10件まで注文を取消します。
Request
POST /private/v1/cancelBulkOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
symbols | array | Required |
取扱銘柄はこちら |
side | string | Optional | BUY SELL 指定時のみ、指定された売買区分の注文を取消対象にします。 |
settleType | string | Optional | OPEN CLOSE 指定時のみ、現物取引注文と指定された決済区分のレバレッジ取引注文を取消対象にします。 |
desc | bool | Optional | true の場合、注文日時が新しい注文から取消します。false の場合、注文日時が古い注文から取消します。指定がない場合はfalse |
Response
Property Name | Value | Description |
---|---|---|
data | array | 取消受付に成功した注文ID |
決済注文
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/closeOrder';
const reqBody = JSON.stringify({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/closeOrder'
reqBody = {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/closeOrder"
reqBody := (`{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/closeOrder'
reqBody = {
:symbol => 'BTC_JPY',
:side => 'BUY',
:executionType => 'LIMIT',
:timeInForce => 'FAS',
:price => '85201',
:settlePosition => [
{
:positionId => 1000342,
:size => '3.44'
}
]
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/closeOrder"
var reqBody = """
{"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/closeOrder';
$reqBody = '{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
close_order().unwrap();
}
fn close_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/closeOrder";
let parameters = json!({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/closeOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]}
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CloseOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CloseOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/closeOrder";
var reqBody = "{ \"symbol\": \"BTC_JPY\", " +
"\"side\": \"BUY\", " +
"\"executionType\": \"LIMIT\", " +
"\"timeInForce\": \"FAS\", " +
"\"price\": \"85201\", " +
"\"settlePosition\": [ { \"positionId\": 1000342, \"size\": \"3.44\" } ] }";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/closeOrder"
let reqBodyStr = """
{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"settlePosition": [
{
"positionId": 1000342,
"size": "3.44"
}
]
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": "637000",
"responsetime": "2019-03-19T01:07:24.557Z"
}
決済注文をします。
対象: レバレッジ取引
Request
POST /private/v1/closeOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
レバレッジ取扱銘柄はこちら |
side | string | Required |
BUY SELL |
executionType | string | Required |
MARKET LIMIT STOP |
timeInForce | string | Optional | FAK FAS FOK ((Post-onlyの場合はSOK ) LIMIT の場合のみ設定可能 )※指定がない場合は成行と逆指値はFAK、指値はFASで注文されます。SOKが指定可能な銘柄はこちらの参照をお願いいたします。 |
price | string | *executionTypeによる |
LIMIT STOP の場合は必須、 MARKET の場合は不要。 |
settlePosition.positionId | number | Required |
建玉は1つのみ指定可能。 |
settlePosition.size | string | Required |
建玉は1つのみ指定可能。 |
cancelBefore | bool | Optional | true の場合、すでに有効注文がある場合に、有効注文の取消と成行注文を同時に行います。注文数量>発注可能数量の場合:注文数量≦発注可能数量となるまで、古い有効注文から順に取り消されます。注文数量≦発注可能数量の場合:有効注文の取消はされず、成行注文のみ実行されます。指定がない場合はfalse ※executionType:MARKET ,timeInforce:FAK の場合にtrue を指定可能です。※複数の建玉に紐づいた注文については指定いただけません。 |
Response
Property Name | Value | Description |
---|---|---|
data | string | 決済注文対象のorderId |
一括決済注文
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/closeBulkOrder';
const reqBody = JSON.stringify({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/closeBulkOrder'
reqBody = {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/closeBulkOrder"
reqBody := (`{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/closeBulkOrder'
reqBody = {
:symbol => 'BTC_JPY',
:side => 'BUY',
:executionType => 'LIMIT',
:timeInForce => 'FAS',
:price => '85201',
:size => '3.44'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/closeBulkOrder"
var reqBody = """
{"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/closeBulkOrder';
$reqBody = '{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
close_bulk_order().unwrap();
}
fn close_bulk_order() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/closeBulkOrder";
let parameters = json!({
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/closeBulkOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44" }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = CloseBulkOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> CloseBulkOrder()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/closeBulkOrder";
var reqBody = "{ \"symbol\": \"BTC_JPY\", " +
"\"side\": \"BUY\", " +
"\"executionType\": \"LIMIT\", " +
"\"timeInForce\": \"FAS\", " +
"\"price\": \"85201\", " +
"\"size\": \"3.44\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/closeBulkOrder"
let reqBodyStr = """
{
"symbol": "BTC_JPY",
"side": "BUY",
"executionType": "LIMIT",
"timeInForce": "FAS",
"price": "85201",
"size": "3.44"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": "637000",
"responsetime": "2019-03-19T01:07:24.557Z"
}
一括決済注文をします。
対象: レバレッジ取引
Request
POST /private/v1/closeBulkOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
レバレッジ取扱銘柄はこちら |
side | string | Required |
BUY SELL |
executionType | string | Required |
MARKET LIMIT STOP |
timeInForce | string | Optional | FAK FAS FOK ((Post-onlyの場合はSOK ) LIMIT の場合のみ設定可能 )※指定がない場合は成行と逆指値はFAK、指値はFASで注文されます。SOKが指定可能な銘柄はこちらの参照をお願いいたします。 |
price | string | *executionTypeによる |
LIMIT STOP の場合は必須、 MARKET の場合は不要。 |
size | string | Required |
Response
Property Name | Value | Description |
---|---|---|
data | string | 一括決済注文対象のorderId |
ロスカットレート変更
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/changeLosscutPrice';
const reqBody = JSON.stringify({
"positionId": 305885,
"losscutPrice": "750000"
})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/changeLosscutPrice'
reqBody = {
"positionId": 305885,
"losscutPrice": "750000"
}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/changeLosscutPrice"
reqBody := (`{
"positionId": 305885,
"losscutPrice": "750000"
}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/changeLosscutPrice'
reqBody = {
:positionId => 305885,
:losscutPrice => '750000'
}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/changeLosscutPrice"
var reqBody = """
{"positionId": 305885, "losscutPrice": "750000"}
"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/changeLosscutPrice';
$reqBody = '{
"positionId": 305885,
"losscutPrice": "750000"
}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
change_losscut_price().unwrap();
}
fn change_losscut_price() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/changeLosscutPrice";
let parameters = json!({
"positionId": 305885,
"losscutPrice": "750000"
});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/changeLosscutPrice"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"positionId": 305885,
"losscutPrice": "750000" }
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = ChangeLosscutPrice();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> ChangeLosscutPrice()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/changeLosscutPrice";
var reqBody = "{ \"positionId\": 305885, " +
"\"losscutPrice\": \"750000\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/changeLosscutPrice"
let reqBodyStr = """
{
"positionId": 305885,
"losscutPrice": "750000"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T01:07:24.557Z"
}
建玉のロスカットレート変更をします。
対象: レバレッジ取引
Request
POST /private/v1/changeLosscutPrice
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
positionId | number | Required |
|
losscutPrice | string | Required |
Private WebSocket API
- サーバーから1分に1回クライアントへpingを送り、3回連続でクライアントからの応答(pong)が無かった場合は、自動的に切断されます。
- アクセストークンを取得・延長・削除するために専用のPrivate APIを使用します。
- Private WebSocket API接続時
Private WebSocket APIのエンドポイント + アクセストークン
で接続してください。
例:wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx
アクセストークンを取得
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'POST';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/ws-auth';
const reqBody = JSON.stringify({})
const text = timestamp + method + path + reqBody;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.post(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {}
text = timestamp + method + path + json.dumps(reqBody)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.post(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "POST"
endPoint := "https://api.coin.z.com/private"
path := "/v1/ws-auth"
reqBody := (`{}`)
text := timestamp + method + path + reqBody
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'POST'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {}
text = timestamp + method + path + reqBody.to_json
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Post.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "POST"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/ws-auth"
var reqBody = """{}"""
var text = timestamp + method + path + reqBody
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'POST';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/ws-auth';
$reqBody = '{}';
$text = $timestamp . $method . $path . $reqBody;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
ws_auth_post().unwrap();
}
fn ws_auth_post() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "POST";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/ws-auth";
let parameters = json!({});
let text = format!("{}{}{}{}", timestamp, method, path, ¶meters);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.post(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "POST"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/ws-auth"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {}
|]
let requestBodyBS = S8.toStrict $ encode requestBodyJson
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path <> requestBodyBS)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "POST"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WsAuthPost();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WsAuthPost()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "POST";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/ws-auth";
var reqBody = "{}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path + reqBody;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "POST"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/ws-auth"
let reqBodyStr = """
{}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path + reqBodyStr
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"data": "xxxxxxxxxxxxxxxxxxxx",
"responsetime": "2019-03-19T02:15:06.102Z"
}
Private WebSocket API用のアクセストークンを取得します。
- 有効期限は60分です。
- アクセストークンは最大5個まで発行できます。
- 発行上限を超えた場合、有効期限の近いトークンから順に削除されます。
- 発行済みのAPIキーを使ってアクセストークンを取得する場合、【会員ページ】-【API】-【編集】-【APIキーの編集】画面で「約定情報通知(WebSocket)」、「注文情報通知(WebSocket)」、「ポジション情報通知(WebSocket)」または「ポジションサマリー情報通知(WebSocket)」にチェックを入れてから、アクセストークンを取得します。
※APIキーの権限を編集する前に取得したアクセストークンには、編集後の権限設定は反映されませんので、ご注意ください。
Request
POST /private/v1/ws-auth
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
data | string | アクセストークン |
アクセストークンを延長
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'PUT';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/ws-auth';
const reqBody = JSON.stringify({
"token": "xxxxxxxxxxxxxxxxxxxx"
})
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
};
axios.put(endPoint + path, reqBody, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'PUT'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {
"token": "xxxxxxxxxxxxxxxxxxxx"
}
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.put(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "PUT"
endPoint := "https://api.coin.z.com/private"
path := "/v1/ws-auth"
reqBody := (`{
"token": "xxxxxxxxxxxxxxxxxxxx"
}`)
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'PUT'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {
:token => 'xxxxxxxxxxxxxxxxxxxx'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Put.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "PUT"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/ws-auth"
var reqBody = """
{"token": "xxxxxxxxxxxxxxxxxxxx"}
"""
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'PUT';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/ws-auth';
$reqBody = '{
"token": "xxxxxxxxxxxxxxxxxxxx"
}';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
ws_auth_put().unwrap();
}
fn ws_auth_put() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "PUT";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/ws-auth";
let parameters = json!({
"token": "xxxxxxxxxxxxxxxxxxxx"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.put(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "PUT"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/ws-auth"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"token": "xxxxxxxxxxxxxxxxxxxx" }
|]
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "PUT"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WsAuthPut();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WsAuthPut()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "PUT";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/ws-auth";
var reqBody = "{ \"token\": \"xxxxxxxxxxxxxxxxxxxx\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "PUT"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/ws-auth"
let reqBodyStr = """
{
"token": "xxxxxxxxxxxxxxxxxxxx"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T02:15:06.102Z"
}
Private WebSocket API用のアクセストークンを延長します。
- 延長前の残り有効期限に関わらず、新しい有効期限は60分となります。
Request
PUT /private/v1/ws-auth
Parameters
- Parameter type: JSON
Parameter | Type | Required | Available Values |
---|---|---|---|
token | string | Required |
アクセストークン |
アクセストークンを削除
Request example:
const axios = require('axios');
const crypto = require('crypto');
const apiKey = 'YOUR_API_KEY';
const secretKey = 'YOUR_SECRET_KEY';
const timestamp = Date.now().toString();
const method = 'DELETE';
const endPoint = 'https://api.coin.z.com/private';
const path = '/v1/ws-auth';
const reqBody = JSON.stringify({
"token": "xxxxxxxxxxxxxxxxxxxx"
})
const text = timestamp + method + path;
const sign = crypto.createHmac('sha256', secretKey).update(text).digest('hex');
const options = {
"headers": {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
},
"data": reqBody,
};
axios.delete(endPoint + path, options)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
import hmac
import hashlib
import time
from datetime import datetime
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
method = 'DELETE'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {
"token": "xxxxxxxxxxxxxxxxxxxx"
}
text = timestamp + method + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
headers = {
"API-KEY": apiKey,
"API-TIMESTAMP": timestamp,
"API-SIGN": sign
}
res = requests.delete(endPoint + path, headers=headers, data=json.dumps(reqBody))
print (json.dumps(res.json(), indent=2))
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"encoding/json"
"bytes"
)
func main() {
apiKey := "YOUR_API_KEY"
secretKey := "YOUR_SECRET_KEY"
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
method := "DELETE"
endPoint := "https://api.coin.z.com/private"
path := "/v1/ws-auth"
reqBody := (`{
"token": "xxxxxxxxxxxxxxxxxxxx"
}`)
text := timestamp + method + path
hc := hmac.New(sha256.New, []byte(secretKey))
hc.Write([]byte(text))
sign := hex.EncodeToString(hc.Sum(nil))
client := &http.Client{}
req, _ := http.NewRequest(method, endPoint+path, strings.NewReader(reqBody))
req.Header.Set("API-KEY", apiKey)
req.Header.Set("API-TIMESTAMP", timestamp)
req.Header.Set("API-SIGN", sign)
res, _ := client.Do(req)
body, _ := io.ReadAll(res.Body)
var buf bytes.Buffer
json.Indent(&buf, body, "", " ")
fmt.Println(buf.String())
}
require 'net/http'
require 'json'
require 'openssl'
require 'base64'
require 'date'
apiKey = 'YOUR_API_KEY'
secretKey = 'YOUR_SECRET_KEY'
timestamp = DateTime.now.strftime('%Q')
method = 'DELETE'
endPoint = 'https://api.coin.z.com/private'
path = '/v1/ws-auth'
reqBody = {
:token => 'xxxxxxxxxxxxxxxxxxxx'
}
text = timestamp + method + path
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, secretKey, text)
uri = URI.parse(endPoint + path)
req = Net::HTTP::Delete.new(uri.to_s)
req['API-KEY'] = apiKey
req['API-TIMESTAMP'] = timestamp
req['API-SIGN'] = sign
req.body = reqBody.to_json
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
puts JSON.pretty_generate(JSON.parse(response.body), :indent=>' ')
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
fun main() {
var apiKey = "YOUR_API_KEY"
var secretKey = "YOUR_SECRET_KEY"
var timestamp = Calendar.getInstance().timeInMillis.toString()
var method = "DELETE"
var endPoint = "https://api.coin.z.com/private"
var path = "/v1/ws-auth"
var reqBody = """
{"token": "xxxxxxxxxxxxxxxxxxxx"}
"""
var text = timestamp + method + path
var keySpec = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
var mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
var sign = mac.doFinal(text.toByteArray()).joinToString("") { String.format("%02x", it and 255.toByte()) }
var url = URL(endPoint + path)
var urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = method
urlConnection.addRequestProperty("API-KEY", apiKey)
urlConnection.addRequestProperty("API-TIMESTAMP", timestamp)
urlConnection.addRequestProperty("API-SIGN", sign)
urlConnection.doOutput = true
urlConnection.outputStream.write(reqBody.toByteArray())
BufferedReader(InputStreamReader(urlConnection.inputStream))
.readLines().forEach { line ->
println(JSONObject(line).toString(2))
}
}
<?php
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$timestamp = time() . '000';
$method = 'DELETE';
$endPoint = 'https://api.coin.z.com/private';
$path = '/v1/ws-auth';
$reqBody = '{
"token": "xxxxxxxxxxxxxxxxxxxx"
}';
$text = $timestamp . $method . $path;
$sign = hash_hmac('SHA256', $text, $secretKey);
$curl = curl_init($endPoint . $path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
$headers = array(
"Content-Type: application/json",
"API-KEY:" . $apiKey,
"API-TIMESTAMP:" . $timestamp,
"API-SIGN:" . $sign
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$response = curl_exec($curl);
curl_close($curl);
$json_res = json_decode($response);
echo json_encode($json_res, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
#![deny(warnings)]
extern crate reqwest;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate hex;
extern crate ring;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
use hex::encode as hex_encode;
use ring::hmac;
#[warn(unused_must_use)]
fn main() {
ws_auth_delete().unwrap();
}
fn ws_auth_delete() -> Result<(), Box<dyn std::error::Error>> {
let api_key = "YOUR_API_KEY";
let secret_key = "YOUR_SECRET_KEY";
let timestamp = get_timestamp();
let method = "DELETE";
let endpoint = "https://api.coin.z.com/private";
let path = "/v1/ws-auth";
let parameters = json!({
"token": "xxxxxxxxxxxxxxxxxxxx"
});
let text = format!("{}{}{}", timestamp, method, path);
let signed_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let sign = hex_encode(hmac::sign(&signed_key, text.as_bytes()).as_ref());
let client = reqwest::blocking::Client::new();
let mut res = client.delete(&(endpoint.to_string() + path))
.header("content-type", "application/json")
.header("API-KEY", api_key)
.header("API-TIMESTAMP", timestamp)
.header("API-SIGN", sign)
.json(¶meters)
.send()
.unwrap();
res.copy_to(&mut std::io::stdout())?;
Ok(())
}
fn get_timestamp() -> u64 {
let start = SystemTime::now();
let since_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards", );
since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000
}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Crypto.Hash.SHA256 as SHA256
import Data.Aeson (encode)
import Data.Aeson (Value)
import Data.Aeson.Encode.Pretty
import qualified Data.Aeson.QQ as Aeson.QQ
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as S8
import Data.Monoid ((<>))
import qualified Data.String as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Network.HTTP.Simple
apiKey :: B.ByteString
apiKey = "YOUR_API_KEY"
secretKey :: B.ByteString
secretKey = "YOUR_SECRET_KEY"
method :: B.ByteString
method = "DELETE"
endPoint :: S.String
endPoint = "https://api.coin.z.com/private"
path :: S.String
path = "/v1/ws-auth"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"token": "xxxxxxxxxxxxxxxxxxxx" }
|]
let sign = B16.encode $ SHA256.hmac secretKey (timestamp <> method <> BS.pack path)
let url = endPoint <> path
request' <- parseRequest url
let request
= setRequestMethod "DELETE"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestHeader "API-KEY" [apiKey]
$ setRequestHeader "API-TIMESTAMP" [timestamp]
$ setRequestHeader "API-SIGN" [sign]
$ setRequestBodyJSON requestBodyJson
$ request'
response <- httpJSON request
S8.putStrLn $ encodePretty (getResponseBody response :: Value)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
class Example
{
static readonly HttpClient HttpClient = new HttpClient();
public static void Main(string[] args)
{
var task = WsAuthDelete();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> WsAuthDelete()
{
const string apiKey = "YOUR_API_KEY";
const string secretKey = "YOUR_SECRET_KEY";
var timestamp = ((long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "000";
const string method = "DELETE";
const string endpoint = "https://api.coin.z.com/private";
const string path = "/v1/ws-auth";
var reqBody = "{ \"token\": \"xxxxxxxxxxxxxxxxxxxx\"}";
using (var request = new HttpRequestMessage(new HttpMethod(method), endpoint + path))
using (var content = new StringContent(reqBody))
{
var text = timestamp + method + path;
var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
var sign = ToHexString(hash);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
request.Headers.Add("API-KEY", apiKey);
request.Headers.Add("API-TIMESTAMP", timestamp);
request.Headers.Add("API-SIGN", sign);
var response = await HttpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
static string ToHexString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
import Foundation
import CommonCrypto
extension Data {
var prettyPrintedJSONString: NSString? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
extension String {
func hmac(secretKey: String) -> String {
let text = self.cString(using: String.Encoding.utf8)
let textLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let secretKeyStr = secretKey.cString(using: String.Encoding.utf8)
let secretKeyLen = Int(secretKey.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), secretKeyStr!, secretKeyLen, text!, textLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate()
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let apiKey = "YOUR_API_KEY"
let secretKey = "YOUR_SECRET_KEY"
let timestamp = String(Int64((Date().timeIntervalSince1970 * 1000.0).rounded()))
let method = "DELETE"
let endPoint : String = "https://api.coin.z.com/private"
let path : String = "/v1/ws-auth"
let reqBodyStr = """
{
"token": "xxxxxxxxxxxxxxxxxxxx"
}
"""
let reqBodyData = reqBodyStr.data(using: .utf8)!
let text = timestamp + method + path
let sign = text.hmac(secretKey: secretKey)
var request = URLRequest(url: URL(string: endPoint + path)!)
request.httpMethod = method
request.httpBody = reqBodyData
request.setValue(apiKey, forHTTPHeaderField: "API-KEY")
request.setValue(timestamp, forHTTPHeaderField: "API-TIMESTAMP")
request.setValue(sign, forHTTPHeaderField: "API-SIGN")
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
print(data!.prettyPrintedJSONString!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"status": 0,
"responsetime": "2019-03-19T02:15:06.102Z"
}
Private WebSocket API用のアクセストークンを削除します。
Request
DELETE /private/v1/ws-auth
Parameters
- Parameter type: JSON
Parameter | Type | Required | Available Values |
---|---|---|---|
token | string | Required |
アクセストークン |
約定情報通知
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "executionEvents"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "executionEvents"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "executionEvents"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "executionEvents"
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "executionEvents"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// 事前に以下の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/private/v1/xxxxxxxxxxxxxxxxxxxx")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "executionEvents" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/private/v1/xxxxxxxxxxxxxxxxxxxx" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = ExecutionEvents();
task.Wait();
}
static async Task ExecutionEvents()
{
const string endpoint = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "executionEvents"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel": "executionEvents",
"orderId": 123456789,
"executionId": 72123911,
"symbol": "BTC_JPY",
"settleType": "OPEN",
"executionType": "LIMIT",
"side": "BUY",
"executionPrice": "877404",
"executionSize": "0.5",
"positionId": 123456789,
"orderTimestamp": "2019-03-19T02:15:06.081Z",
"executionTimestamp": "2019-03-19T02:15:06.081Z",
"lossGain": "0",
"fee": "323",
"orderPrice": "877200",
"orderSize": "0.8",
"orderExecutedSize": "0.7",
"timeInForce": "FAS",
"msgType": "ER"
}
最新の約定情報通知を受信します。
subscribe
後、最新の約定情報通知が配信されます。
Parameters
- Parameter type: JSON
Property Name | Type | Required | Available Values |
---|---|---|---|
command | string | Required |
subscribe unsubscribe |
channel | string | Required |
executionEvents |
Response
Property Name | Value | Description |
---|---|---|
channel | string | executionEvents |
orderId | number | 注文ID |
executionId | number | 約定ID |
symbol | string | 取扱銘柄はこちら |
settleType | string | 決済区分: OPEN CLOSE |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
side | string | 売買区分: BUY SELL |
executionPrice | string | 約定レート |
executionSize | string | 約定数量 |
positionId | number | 建玉ID ※レバレッジの場合のみ |
orderTimestamp | string | 注文日時 |
executionTimestamp | string | 約定日時 |
lossGain | string | 決済損益 |
fee | string | 取引手数料※Takerの場合はプラスの値、Makerの場合はマイナスの値が返ってきます。 |
orderPrice | string | 注文価格 (MARKET 注文の場合は"0") |
orderSize | string | 注文数量 |
orderExecutedSize | string | 約定済み数量 |
timeInForce | string | 執行数量条件: FAK FAS FOK (Post-onlyの場合はSOK ) |
msgType | string | メッセージタイプ: ER |
unsubscribe
でリクエストした場合のResponseはありません。
注文情報通知
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "orderEvents"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "orderEvents"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "orderEvents"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "orderEvents"
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "orderEvents"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// 事前に以下の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/private/v1/xxxxxxxxxxxxxxxxxxxx")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "orderEvents" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/private/v1/xxxxxxxxxxxxxxxxxxxx" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = OrderEvents();
task.Wait();
}
static async Task OrderEvents()
{
const string endpoint = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "orderEvents"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel": "orderEvents",
"orderId": 123456789,
"symbol": "BTC_JPY",
"settleType": "OPEN",
"executionType": "LIMIT",
"side": "BUY",
"orderStatus": "CANCELED",
"cancelType": "USER",
"orderTimestamp": "2019-03-19T02:15:06.081Z",
"orderPrice": "876045",
"orderSize": "0.8",
"orderExecutedSize": "0",
"losscutPrice": "0",
"timeInForce": "FAS",
"msgType": "NOR"
}
最新の注文情報通知を受信します。
subscribe
後、最新の注文情報通知が配信されます。
Parameters
- Parameter type: JSON
Property Name | Type | Required | Available Values |
---|---|---|---|
command | string | Required |
subscribe unsubscribe |
channel | string | Required |
orderEvents |
Response
Property Name | Value | Description |
---|---|---|
channel | string | orderEvents |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
settleType | string | 決済区分: OPEN CLOSE LOSS_CUT |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
side | string | 売買区分: BUY SELL |
orderStatus | string | 注文ステータス: WAITING ORDERED CANCELED EXPIRED ※逆指値注文の場合は WAITING が有効 |
cancelType | string | 取消区分: USER POSITION_LOSSCUT INSUFFICIENT_BALANCE INSUFFICIENT_MARGIN ACCOUNT_LOSSCUT MARGIN_CALL MARGIN_CALL_LOSSCUT EXPIRED_FAK EXPIRED_FOK EXPIRED_SOK EXPIRED_SELFTRADE CLOSED_ORDER ※orderStatusが CANCELED またはEXPIRED の場合のみ返ってきます。取消区分: SOK_TAKER PRICE_LIMIT ※orderStatusが ORDERED の場合のみ返ってきます。 |
orderTimestamp | string | 注文日時 |
orderPrice | string | 注文価格 (MARKET 注文の場合は"0") |
orderSize | string | 注文数量 |
orderExecutedSize | string | 約定済み数量 |
losscutPrice | string | ロスカットレート (現物取引や未設定の場合は"0") |
timeInForce | string | 執行数量条件: FAK FAS FOK (Post-onlyの場合はSOK ) |
msgType | string | メッセージタイプ: NOR ROR COR ER |
unsubscribe
でリクエストした場合のResponseはありません。
ポジション情報通知
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "positionEvents"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "positionEvents"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "positionEvents"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "positionEvents"
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "positionEvents"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// 事前に以下の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/private/v1/xxxxxxxxxxxxxxxxxxxx")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "positionEvents" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/private/v1/xxxxxxxxxxxxxxxxxxxx" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = PositionEvents();
task.Wait();
}
static async Task PositionEvents()
{
const string endpoint = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "positionEvents"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel": "positionEvents",
"positionId": 1234567,
"symbol": "BTC_JPY",
"side": "BUY",
"size": "0.22",
"orderdSize": "0",
"price": "876045",
"lossGain": "14",
"leverage": "4",
"losscutPrice": "766540",
"timestamp": "2019-03-19T02:15:06.094Z",
"msgType": "OPR"
}
最新のポジション情報通知を受信します。
subscribe
後、最新のポジション情報通知が配信されます。
Parameters
- Parameter type: JSON
Property Name | Type | Required | Available Values |
---|---|---|---|
command | string | Required |
subscribe unsubscribe |
channel | string | Required |
positionEvents |
Response
Property Name | Value | Description |
---|---|---|
channel | string | positionEvents |
positionId | number | 建玉ID |
symbol | string | レバレッジ取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
size | string | 建玉数量 |
orderdSize | string | 発注中数量 |
price | string | 建玉レート |
lossGain | string | 評価損益 |
leverage | string | レバレッジ |
losscutPrice | string | ロスカットレート |
timestamp | string | 約定日時 |
msgType | string | メッセージタイプ: OPR UPR ULR CPR |
unsubscribe
でリクエストした場合のResponseはありません。
ポジションサマリー情報通知
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "positionSummaryEvents"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "positionSummaryEvents"
}
ws.send(json.dumps(message))
def on_message(self, message):
print(message)
ws.on_open = on_open
ws.on_message = on_message
ws.run_forever()
package main
import (
"fmt"
"golang.org/x/net/websocket"
"encoding/json"
"bytes"
)
func main() {
wsUrl := "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "positionSummaryEvents"
}`)
var receiveMsg string
ws, _ := websocket.Dial(wsUrl, "", origin)
websocket.Message.Send(ws, sendMsg)
for {
websocket.Message.Receive(ws, &receiveMsg)
var buf bytes.Buffer
json.Indent(&buf, []byte(receiveMsg), "", " ")
fmt.Println(buf.String())
}
}
require "faye/websocket"
require "eventmachine"
require 'json'
EM.run {
ws = Faye::WebSocket::Client.new("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "positionSummaryEvents"
}
ws.send(message.to_json)
end
ws.on :message do |event|
puts event.data
end
}
import io.ktor.client.HttpClient
import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.webSocket
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
fun main() {
var wsUrl = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "positionSummaryEvents"}
"""
val client = HttpClient {
install(WebSockets)
}
runBlocking {
client.webSocket(
urlString = wsUrl
) {
send(Frame.Text(sendMsg))
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> println(JSONObject(frame.readText()).toString(2))
else -> {}
}
}
}
}
}
<?php
// 事前に以下の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/private/v1/xxxxxxxxxxxxxxxxxxxx")->then(function (Ratchet\Client\WebSocket $conn) use ($connector, $loop) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "{$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('{ "command" : "subscribe", "channel" : "positionSummaryEvents" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
let (mut socket, _response) =
connect(Url::parse("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.send(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\" }" :: Text)
_ <- forkIO $ forever $ do
msg <- WS.receiveData conn
liftIO $ T.putStrLn msg
let loop = do
line <- T.getLine
unless (T.null line) $ WS.sendTextData conn line >> loop
loop
WS.sendClose conn ("msgData" :: Text)
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api.coin.z.com" 443 "/ws/private/v1/xxxxxxxxxxxxxxxxxxxx" app
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Example
{
public static void Main(string[] args)
{
var task = PositionSummaryEvents();
task.Wait();
}
static async Task PositionSummaryEvents()
{
const string endpoint = "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\" }";
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
var messageBytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true,
CancellationToken.None);
while (client.State == WebSocketState.Open)
{
var incomingData = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
}
}
// WebSocket4Net example
using System;
using WebSocket4Net;
class Example
{
static WebSocket websocket;
static void Main(string[] args)
{
websocket = new WebSocket("wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
websocket.Opened += Websocket_Opened;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Open();
Console.Read();
}
private static void Websocket_Opened(object sender, EventArgs e)
{
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\" }";
websocket.Send(message);
}
private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine(e.Message);
}
}
import Foundation
extension URLSessionWebSocketTask.Message {
var prettyPrintedJSONString: NSString? {
switch self {
case .string(let text):
guard let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
default:
return nil
}
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let url = URL(string: "wss://api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")!
let urlSession = URLSession(configuration: .default)
let webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
let message = URLSessionWebSocketTask.Message.string("""
{
"command": "subscribe",
"channel": "positionSummaryEvents"
}
""")
webSocketTask.send(message) { error in
if let error = error {
print(error)
}
}
webSocketTask.receive { result in
switch result {
case .failure(let error):
print(error)
case .success(let message):
print(message.prettyPrintedJSONString!)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
Response example:
{
"channel":"positionSummaryEvents",
"symbol":"BTC_JPY",
"side":"BUY",
"averagePositionRate":"1014484",
"positionLossGain":"18",
"sumOrderQuantity":"0.01",
"sumPositionQuantity":"0.03",
"timestamp":"2020-06-24T09:53:19.702Z",
"msgType":"UPDATE"
}
最新のポジションサマリー情報通知を受信します。
subscribe
後、最新のポジションサマリー情報通知が配信されます。
Parameters
- Parameter type: JSON
Property Name | Type | Required | Available Values |
---|---|---|---|
command | string | Required |
subscribe unsubscribe |
channel | string | Required |
positionSummaryEvents |
option | string | Optional | PERIODIC ※optionが指定された場合、5秒ごとにデータが送信されます。 ※複数回subscribeした場合は後にsubscribeしたものが有効となります。 |
Response
Property Name | Value | Description |
---|---|---|
channel | string | positionSummaryEvents |
symbol | string | レバレッジ取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
averagePositionRate | string | 平均建玉レート |
positionLossGain | string | 評価損益 |
sumOrderQuantity | string | 発注中数量 |
sumPositionQuantity | string | 建玉数量 |
timestamp | string | 配信日時 |
msgType | string | メッセージタイプ: INIT UPDATE PERIODIC |
unsubscribe
でリクエストした場合のResponseはありません。
ヒストリカルデータ
取引所における全ての取引履歴について、こちらからCSVファイルでダウンロードいただけます。
リファレンス
APIのパラメータやレスポンスにより返ってくる各種コードについて説明します。
パラメータ
パラメータの値とその内容について説明します。
symbol: 取扱銘柄名
Value | Description | Release date |
---|---|---|
BTC | ビットコイン(現物取引) | 2018/09/05 |
ETH | イーサリアム(現物取引) | 2019/01/30 |
BCH | ビットコインキャッシュ(現物取引) | 2019/01/30 |
LTC | ライトコイン(現物取引) | 2019/01/30 |
XRP | リップル(現物取引) | 2019/01/30 |
XEM | ネム(現物取引) | 2021/06/23 |
XLM | ステラルーメン(現物取引) | 2021/08/18 |
BAT | ベーシックアテンショントークン(現物取引) | 2022/03/30 |
XTZ | テゾス(現物取引) | 2022/06/08 |
QTUM | クアンタム(現物取引) | 2022/03/30 |
ENJ | エンジンコイン(現物取引) | 2022/06/08 |
DOT | ポルカドット(現物取引) | 2022/06/08 |
ATOM | コスモス(現物取引) | 2022/06/08 |
MKR | メイカー(現物取引) | 2022/07/13 |
DAI | ダイ(現物取引) | 2022/07/13 |
XYM | シンボル(現物取引) | 2021/10/20 |
MONA | モナコイン(現物取引) | 2021/12/01 |
FCR | FCRコイン(現物取引) | 2022/05/18 |
ADA | カルダノ(現物取引) | 2022/07/13 |
LINK | チェーンリンク(現物取引) | 2022/07/13 |
DOGE | ドージコイン(現物取引) | 2023/08/05 |
SOL | ソラナ(現物取引) | 2023/08/05 |
ASTR | アスター(現物取引) | 2023/03/22 |
Value | Description | Release date |
---|---|---|
BTC_JPY | ビットコイン/円(レバレッジ取引) | 2018/09/05 |
ETH_JPY | イーサリアム/円(レバレッジ取引) | 2019/01/30 |
BCH_JPY | ビットコインキャッシュ/円(レバレッジ取引) | 2019/01/30 |
LTC_JPY | ライトコイン/円(レバレッジ取引) | 2019/01/30 |
XRP_JPY | リップル/円(レバレッジ取引) | 2019/01/30 |
DOT_JPY | ポルカドット/円(レバレッジ取引) | 2024/04/13 |
ATOM_JPY | コスモス/円(レバレッジ取引) | 2024/04/13 |
ADA_JPY | カルダノ/円(レバレッジ取引) | 2024/04/13 |
LINK_JPY | チェーンリンク/円(レバレッジ取引) | 2024/04/13 |
DOGE_JPY | ドージコイン/円(レバレッジ取引) | 2024/04/13 |
SOL_JPY | ソラナ/円(レバレッジ取引) | 2024/04/13 |
symbol: 資産残高銘柄
Value | Description |
---|---|
JPY | 日本円 |
BTC | ビットコイン(販売所) |
ETH | イーサリアム(販売所) |
BCH | ビットコインキャッシュ(販売所) |
LTC | ライトコイン(販売所) |
XRP | リップル(販売所) |
XEM | ネム(取引所) |
XLM | ステラルーメン(販売所) |
BAT | ベーシックアテンショントークン(販売所) |
OMG | オーエムジー |
XTZ | テゾス(販売所) |
QTUM | クアンタム(販売所) |
ENJ | エンジンコイン(取引所) |
DOT | ポルカドット(販売所) |
ATOM | コスモス(販売所) |
MKR | メイカー(販売所) |
DAI | ダイ(販売所) |
XYM | シンボル(取引所) |
MONA | モナコイン(取引所) |
FCR | FCRコイン(取引所) |
ADA | カルダノ(販売所) |
LINK | チェーンリンク(販売所) |
DOGE | ドージコイン(販売所) |
SOL | ソラナ(販売所) |
FLR | フレア |
ASTR | アスター(取引所) |
FIL | ファイルコイン(販売所) |
SAND | ザ・サンドボックス(販売所) |
CHZ | チリーズ(販売所) |
AVAX | アバランチ(販売所) |
side: 売買区分
Value | Description |
---|---|
BUY | 買 |
SELL | 売 |
executionType: 注文タイプ
Value | Description |
---|---|
MARKET | 成行 |
LIMIT | 指値 |
STOP | 逆指値 |
timeInForce: 執行数量条件
Value | Description |
---|---|
FAK | 注文が一部約定後に未執行数量が残った場合、その残数量を失効とする条件 |
FAS | 注文が一部約定後に未執行数量が残った場合、その残数量を有効とする条件 |
FOK | 注文の全数量が直ちに約定しない場合、その全数量を失効とする条件 |
SOK | 指値注文においてMakerにならない場合、その全数量を失効とする条件(Post-only) |
timeInForceパラメータにSOK(Post-only)が指定可能な銘柄
Service | Description |
---|---|
取引所現物 | 全銘柄指定可能 |
取引所レバレッジ | BTC_JPY DOT_JPY ATOM_JPY ADA_JPY LINK_JPY DOGE_JPY SOL_JPY |
HTTPステータスコード
Status Code | Description |
---|---|
200 | 処理が正常終了した場合に返ってくるコードです。 |
404 | URLが不正な場合などに返ってくるコードです。 |
503 | メンテナンス時にWebSocket APIを呼び出した場合に返ってくるコードです。 |
ステータスコード
Status Code | Description |
---|---|
0 | 処理が正常終了した場合に返ってくるコードです。 |
エラーコード
Error Code | Description |
---|---|
ERR-70 | 決済注文において、指定された建玉の売買区分が誤っている場合に返ってきます。 |
ERR-189 | 決済注文において、決済可能保有数量を超えての数量の注文の場合に返ってきます。 |
ERR-200 | すでに有効注文があり、注文数量が発注可能な数量を超えている場合に返ってきます。決済注文を行いたい場合は、注文数量を変更するか、有効注文を取消したうえで、再度注文をしてください。 |
ERR-201 | 注文時に取引余力が不足している場合に返ってきます。 |
ERR-208 | 注文可能な保有数量が不足している場合に返ってきます。保有数量、有効注文を確認してください。 |
ERR-254 | 指定された建玉が存在しない場合に返ってきます。 |
ERR-422 | 一括決済注文において、建玉が存在しない場合に返ってきます。銘柄または売買区分が誤っていないか確認してください。 |
ERR-430 | 約定情報取得において、orderId/executionIdの設定が不正な場合に返ってきます。 |
ERR-554 | サーバーが利用不可能な状態の場合に返ってきます。 |
ERR-626 | サーバーへのアクセスが集中している場合に返ってきます。しばらく時間をおいてから再度お試しください。 |
ERR-635 | 有効注文の件数が上限に達している場合に返ってきます。新規の注文をするためには、有効注文を取消したうえで、再度注文をしてください。 |
ERR-682 | 追加証拠金が発生しているため、ご指定の操作が実行できない場合に返ってきます。 |
ERR-683 | 追加証拠金の処理が実行中のため、ご指定の操作が実行できない場合に返ってきます。 |
ERR-754 | 振替可能額よりも大きい値を振り替えようとした場合に返ってきます。 |
ERR-846 | fromTimestampとtoTimestampの差が最大30分よりも大きい場合に返ってきます。 |
ERR-5003 | API呼出上限を越えた場合に返ってきます。 |
ERR-5007 | リクエストヘッダーにAPI-TIMESTAMPが設定されていない場合、またはAPI-TIMESTAMPに設定されている値が数値でない場合に返されます。 リクエストヘッダーにAPI-TIMESTAMPが設定されていること、設定されている値がミリ秒単位のUNIX時間を表す数値であることをご確認ください。 |
ERR-5008 | リクエストヘッダーに設定されているAPI-TIMESTAMPが公開APIのシステム時刻より遅い場合に返ってきます。その場合、システム時間の更新をお試しください。 |
ERR-5009 | リクエストヘッダーに設定されているAPI-TIMESTAMPが公開APIのシステム時刻より早い場合に返ってきます。その場合、システム時間の更新をお試しください。 |
ERR-5010 | リクエストヘッダーに指定されているAPI-SIGN(Signature)に不正がある場合に返ってきます。認証情報についてご確認ください。 |
ERR-5011 | リクエストヘッダーにAPI-KEYが設定されていない場合に返ってきます。認証情報についてご確認ください。 |
ERR-5012 | API-KEYが認証エラーの場合などに返ってきます。 |
ERR-5014 | お客様のご確認、ご同意が必要な処理を実行する際に、お客様に未確認・未同意事項がある場合に返ってきます。 |
ERR-5106 | パラメーターが不正な場合に返ってきます。 |
ERR-5111 | リクエストボディに指定されているtimeInForceが誤っている場合に返ってきます。指定可能な値に関しては注文、決済注文または一括決済注文にてパラメーターのtimeInForceをご確認ください。 |
ERR-5114 | 小数点以下の桁数が有効桁数を超えている場合に返ってきます。取引ルールの最小注文単位をご確認ください。取引ルールはこちらよりご確認いただけます。 |
ERR-5118 | リクエストボディにlosscutPriceを指定できない場合に返ってきます。 |
ERR-5121 | 注文時の価格が低すぎて注文できない状態の場合に返ってきます。 |
ERR-5122 | 指定された注文がすでに変更中、取消中、取消済、全量約定、失効のいずれかの状態であるため、注文の変更や取消ができない場合に返ってきます。 |
ERR-5123 | 指定された注文番号が存在しない場合に返ってきます。 |
ERR-5125 | APIの取引規制がかかっている場合に返ってきます。 |
ERR-5126 | 1回あたりの最大注文数量を超えている場合または最小注文数量を下回っている場合に返ってきます。こちらより取引ルールをご確認ください。 |
ERR-5127 | お客様に取引規制がかかっている場合に返ってきます。 |
ERR-5129 | 逆指値注文で、即座に約定される価格が指定されている場合に返ってきます。(逆指値注文では、即座に約定される価格での注文はできません) |
ERR-5133 | 振替規制中のため口座振替が行えない場合に返ってきます。 |
ERR-5135 | 外国為替FX用口座が開設されていない場合に口座振替を行うと返ってきます。外国為替FX用口座開設後再度お試しください。 |
ERR-5201 | 定期メンテナンス時にPublic/Private APIを呼び出した場合に返ってきます。 |
ERR-5202 | 緊急メンテナンス時にPublic/Private APIを呼び出した場合に返ってきます。 |
ERR-5203 | 取引所プレオープン中に注文および注文変更した場合に返ってきます。 |
ERR-5204 | リクエスト時に各APIのURLが不正な場合に返ってきます。 |
ERR-5206 | 注文変更を実行時に注文毎の変更可能回数が上限に達している場合に返ってきます。上限に達して更に注文変更を行いたい場合は、1度注文キャンセルをしてから新規に注文をしていただくようにお願い致します。 |
ERR-5207 | リクエストボディに指定されているsymbol、intervalまたはdateが不正な場合に返ってきます。 |
ERR-5208 | 約定情報取得において、orderId/executionIdが両方設定された場合に返ってきます。 |
フィードバック
APIについてご要望をお聞かせください。いただいたご要望につきましては、開発チームにて精査のうえ、順次開発、リリースしております。
APIについてのご要望は、こちらよりご連絡ください。
※APIに関するご質問などは、こちらよりお問い合わせください。内容によってはお時間をいただく場合がございます。あらかじめご了承ください。
更新履歴
2024
2024-11-02 New
2024-06-01
2024-04-13
2024-03-02
- Private APIの制限を変更
- Tier2が適用される取引高の条件を1億円以上から10億円以上に引き上げました。
- Tier2のGET,POSTのリクエスト上限を1秒間30回に引き上げました。
2023
2023-12-16
2023-12-09
- Private APIの制限を変更
- Tier1のGET,POSTのリクエスト上限を1秒間20回に引き上げました。
2023-10-28
- ResponseにtransferableAmountを追加しました。
2023-10-21
- Private APIの制限を変更
- Tier2が適用される取引高の条件を10億以上から1億以上に引き下げました。
- Tier1のGET,POSTのリクエスト上限を1秒間10回に引き上げました。
- Tier2のGET,POSTのリクエスト上限を1秒間20回に引き上げました。
2023-09-16
- Responseの cancelTypeに
EXPIRED_SELFTRADE
を追加しました。
- Responseの cancelTypeに
EXPIRED_SELFTRADE
を追加しました。
2023-08-05
2023-07-29
2023-07-08
2023-05-13
- ResponseにTakerFeeとMakerFeeを追加しました。
2023-03-22
2023-01-18
2022
2022-12-21
2022-10-12
2022-07-13
2022-07-06
2022-06-08
2022-05-18
2022-04-08
- Private APIの制限を変更
- Tier2が適用される取引高の条件を20億以上から10億以上に引き下げました。
2022-03-30
2022-03-02
2022-02-16
2022-01-27
- Private APIの制限を変更
- 先週の取引高に応じて、今週のPrivate APIの呼び出し上限値が決定いたします。
2022-01-26
2021
2021-12-01
2021-10-20
2021-09-22
- ResponseにpositionIdを追加しました。
- ResponseにpositionIdを追加しました。
2021-09-08
- 指値注文の timeInForceに
FAK
を追加しました。
- 指値注文の timeInForceに
FAK
を追加しました。
- 指値注文の timeInForceに
FAK
を追加しました。
2021-08-18
2021-08-04
- ParameterのsymbolをOptionalに変更しました。
2021-07-14
2021-06-23
2021-05-26
- Private API上限を変更
- GETリクエストの上限を1秒間6回に変更しました。
- POSTリクエストの上限を1秒間6回に変更しました。
2021-05-19
2021-04-21
- ResponseにmarginCallStatusを追加しました。
- Responseの cancelTypeに
MARGIN_CALL
MARGIN_CALL_LOSSCUT
を追加しました。
- Responseの cancelTypeに
MARGIN_CALL
MARGIN_CALL_LOSSCUT
を追加しました。
2021-04-15
2021-03-10
- レスポンスにmarginRatioを追加しました。
2020
2020-12-16
- カンマ区切りで複数の約定IDを指定できるように変更しました。
- パラメータのexecutionIdのTypeをnumberからstringに変更しました。
- 最大10件まで指定可能です。
2020-12-09
- パラメータにcancelBeforeを追加しました。
- パラメータにcancelBeforeを追加しました。
2020-11-04
- カンマ区切りで複数の注文IDを指定できるように変更しました。
- パラメータのorderIdのTypeをnumberからstringに変更しました。
- 最大10件まで指定可能です。
2020-09-09
- Private WebSocket APIのアクセストークンの発行上限を1個から5個へ変更しました。
- 発行上限を超えた場合、有効期限の近いトークンから順に削除されます。
2020-09-02
- パラメータにtimeInForceを追加しました。
- パラメータにtimeInForceを追加しました。
- パラメータにtimeInForceを追加しました。
Responseの cancelTypeに
EXPIRED_FAK
EXPIRED_FOK
EXPIRED_SOK
を追加しました。Responseの timeInForceに
FOK
SOK
を追加しました。
- Responseの timeInForceに
FOK
SOK
を追加しました。
- Responseの timeInForceに
FOK
SOK
を追加しました。
Responseの cancelTypeに
EXPIRED_FAK
EXPIRED_FOK
EXPIRED_SOK
CLOSED_ORDER
PRICE_LIMIT
SOK_TAKER
を追加しました。Responseの timeInForceに
FOK
SOK
を追加しました。
2020-08-12
- subscribe時のパラメータに定期配信のoptionを追加しました。
- ResponseにmsgTypeを追加しました。
2020-08-05
- Responseの cancelTypeに
INSUFFICIENT_BALANCE
INSUFFICIENT_MARGIN
ACCOUNT_LOSSCUT
を追加しました。
- Responseの cancelTypeに
INSUFFICIENT_BALANCE
INSUFFICIENT_MARGIN
ACCOUNT_LOSSCUT
を追加しました。
2020-07-28
- 取引所における全ての取引履歴について、CSVファイルでダウンロードいただけます。
2020-07-15
- パラメータにlosscutPriceを追加しました。
2020-07-08
- 発行済みのAPIキーを使ってアクセストークンを取得する場合、【会員ページ】-【API】-【編集】-【APIキーの編集】画面で「約定情報通知(WebSocket)」、「注文情報通知(WebSocket)」、「ポジション情報通知(WebSocket)」または「ポジションサマリー情報通知(WebSocket)」にチェックを入れてから、アクセストークンを取得します。
2020-06-24
- レスポンスにcancelTypeを追加しました。
- レスポンスにcancelTypeを追加しました。
2020-05-27
- パラメータにlosscutPriceを追加しました。
- レスポンスにlosscutPriceを追加しました。
- レスポンスにlosscutPriceを追加しました。
- レスポンスにlosscutPriceを追加しました。
2020-04-28
- 発行済みのAPIキーを使ってアクセストークンを取得する場合、【会員ページ】-【API】-【編集】-【APIキーの編集】画面で「約定情報通知(WebSocket)」、「注文情報通知(WebSocket)」または「ポジション情報通知(WebSocket)」にチェックを入れてから、アクセストークンを取得します。
2020-04-08
- レスポンスにtimestampを追加しました。
2020-04-01
- Private API上限を変更
- Private APIについて、GETとPOSTで個別に呼び出し上限を設定しました。
- GETリクエストの上限を1秒間3回に変更しました。
- POSTリクエストの上限を1秒間3回に変更しました。
- Private APIについて、GETとPOSTで個別に呼び出し上限を設定しました。
2020-02-26
- 発行済みのAPIキーを使ってアクセストークンを取得する場合、【会員ページ】-【API】-【編集】-【APIキーの編集】画面で「約定情報通知(WebSocket)」または「注文情報通知(WebSocket)」にチェックを入れてから、アクセストークンを取得します。
- ResponseにmsgTypeを追加しました。
2020-02-12
- Request exampleにSwiftを追加しました。
- C#にWebSocket4Netを使用した例を追加しました。
2020-01-23
- Private WebSocket API上限を追加
- Private WebSocket APIのリクエスト上限についての記述を追加しました。
2019
2019-11-27
- subscribe時のパラメータにoptionを追加しました。
2019-11-20
2019-10-23
- 逆指値注文の場合は注文ステータス
WAITING
が有効、ORDERED
が一部約定になりますので、ご注意ください。
- Parameterの executionTypeに
STOP
を追加しました。 - Parameterの priceの説明を変更しました。
- Parameterの executionTypeに
STOP
を追加しました。 - Parameterの priceの説明を変更しました。
- Parameterの executionTypeに
STOP
を追加しました。 - Parameterの priceの説明を変更しました。
- Parameterの executionTypeに
STOP
を追加しました。 - Parameterの statusの説明を変更しました。
- Responseの executionTypeに
STOP
を追加しました。 - Responseの statusの説明を変更しました。
2019-10-02
2019-09-18
2019-09-11
2019-08-28
- Public WebSocket API上限を追加
- Public WebSocket APIのリクエスト上限についての記述を追加しました。
2019-07-03
- Private API上限を変更
- Private APIの上限を最大300ミリ秒1回に変更しました。
2019-06-12
- symbolパラメータをoptionalに変更
- symbolを指定しない場合は全銘柄分の最新レートを返すように変更しました。