概要
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://forex-api.coin.z.com/public
- Public WebSocket API:
wss://forex-api.coin.z.com/ws/public
- Private API:
https://forex-api.coin.z.com/private
- Private WebSocket API:
wss://forex-api.coin.z.com/ws/private
バージョン
現在バージョン: v1
制限
APIは以下のように制限をかけております。
Public WebSocket APIの制限
- 同一IPからのリクエスト(subscribe, unsubscribe)は、1秒間1回を上限とします。
Private APIの制限
- 制限はシステム負荷状況によって一時的に変更する場合があります。ご了承ください。
- 会員ページにてIP制限機能を有効にすると、API呼出ができるIPアドレスを制限することができます。
- APIキー発行時に指定した機能のみをAPIで呼び出すことができます。
説明 |
---|
同一アカウントからGETのAPI呼出は、1秒間に6回が上限です。 同一アカウントからPOSTのAPI呼出は、1秒間に1回が上限です。 |
Private WebSocket APIの制限
- 同一IPからのリクエスト(subscribe, unsubscribe)は、1秒間1回を上限とします。
- 会員ページにてIP制限機能を有効にすると、API呼出ができるIPアドレスを制限することができます。
- APIキー発行時に指定した機能のみをsubscribeすることができます。
その他
下記のいずれかの理由により、APIのご利用を制限させていただく場合があります。ご了承ください。
- 当社システム全体が高負荷となった場合に、自動で流量制限を実施させていただくため
- お客さまによるAPIのご利用方法が、当社システムへ負荷をかけている可能性があると当社が判断したため
- システムに負荷をかける目的での発注を繰り返していると当社が判断したため
口座開設
外国為替FX口座をお持ちでない場合 無料口座開設
APIキー作成
外国為替FX口座の開設完了後、会員ページから外国為替FXのAPIキーが作成できます。
APIキーを生成する際、機能ごとにパーミッションを設定することができます。
APIキー作成後はトライアル期間として30日間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://forex-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
外国為替FXステータス
Request example:
const axios = require('axios');
const endPoint = 'https://forex-api.coin.z.com/public';
const path = '/v1/status';
axios.get(endPoint + path)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
endPoint = 'https://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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"
}
外国為替FXの稼動状態を取得します。
Request
GET /public/v1/status
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
status | string | 外国為替FXステータス: MAINTENANCE CLOSE OPEN |
最新レート
Request example:
const axios = require('axios');
const endPoint = 'https://forex-api.coin.z.com/public';
const path = '/v1/ticker';
axios.get(endPoint + path)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
endPoint = 'https://forex-api.coin.z.com/public'
path = '/v1/ticker'
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://forex-api.coin.z.com/public"
path := "/v1/ticker"
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://forex-api.coin.z.com/public'
path = '/v1/ticker'
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://forex-api.coin.z.com/public"
var path = "/v1/ticker"
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://forex-api.coin.z.com/public';
$path = '/v1/ticker';
$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://forex-api.coin.z.com/public/v1/ticker").
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://forex-api.coin.z.com/public/v1/ticker"
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 = Ticker();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<string> Ticker()
{
const string endpoint = "https://forex-api.coin.z.com/public";
const string path = "/v1/ticker";
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://forex-api.coin.z.com/public"
let path : String = "/v1/ticker"
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": "137.644",
"bid": "137.632",
"symbol": "USD_JPY",
"timestamp": "2018-03-30T12:34:56.789671Z",
"status": "OPEN"
},
{
"symbol": "EUR_JPY",
"ask": "149.221",
"bid": "149.181",
"timestamp": "2023-05-19T02:51:24.516493Z",
"status": "OPEN"
}
],
"responsetime": "2019-03-19T02:15:06.014Z"
}
全銘柄分の最新レートを取得します。
Request
GET /public/v1/ticker
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
symbol | string | 取扱銘柄はこちら |
ask | string | 現在の買値 |
bid | string | 現在の売値 |
timestamp | string | 現在レートのタイムスタンプ |
status | string | 外国為替FXステータス: CLOSE OPEN |
KLine情報の取得
Request example:
const axios = require('axios');
const endPoint = 'https://forex-api.coin.z.com/public';
const path = '/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028';
axios.get(endPoint + path)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
endPoint = 'https://forex-api.coin.z.com/public'
path = '/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028'
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://forex-api.coin.z.com/public"
path := "/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028"
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://forex-api.coin.z.com/public'
path = '/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028'
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://forex-api.coin.z.com/public"
var path = "/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028"
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://forex-api.coin.z.com/public';
$path = '/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028';
$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://forex-api.coin.z.com/public/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028").
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://forex-api.coin.z.com/public/v1/klines"
let request
= setRequestMethod "GET"
$ setRequestSecure True
$ setRequestPort 443
$ setRequestQueryString [("symbol", Just "USD_JPY"), ("priceType", Just "ASK"), ("interval", Just "1min"), ("date", Just "20230708")]
$ 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://forex-api.coin.z.com/public";
const string path = "/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028";
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://forex-api.coin.z.com/public"
let path : String = "/v1/klines?symbol=USD_JPY&priceType=ASK&interval=1min&date=20231028"
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":"141.365",
"high":"141.368",
"low":"141.360",
"close":"141.362"
},
{
"openTime":"1618588860000",
"open":"141.362",
"high":"141.369",
"low":"141.361",
"close":"141.365"
}
],
"responsetime": "2023-07-08T22:28:07.980Z"
}
指定した銘柄の四本値を取得します。
Request
GET /public/v1/klines
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
priceType | string | Required |
BID ASK を指定 |
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 ※20231028以降を指定可能 日本時間朝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 | 終値 |
取引ルール
Request example:
const axios = require('axios');
const endPoint = 'https://forex-api.coin.z.com/public';
const path = '/v1/symbols';
axios.get(endPoint + path)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
import requests
import json
endPoint = 'https://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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": "USD_JPY",
"minOpenOrderSize": "10000",
"maxOrderSize": "500000",
"sizeStep": "1",
"tickSize": "0.001"
}
],
"responsetime": "2022-12-15T19:22:23.792Z"
}
取引ルールを取得します。
Request
GET /public/v1/symbols
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
symbol | string | 取扱銘柄はこちら |
minOpenOrderSize | string | 新規最小注文数量/回 |
maxOrderSize | string | 最大注文数量/回 |
sizeStep | string | 最小注文単位/回 |
tickSize | string | 注文価格の呼値 |
Public WebSocket API
- サーバーから1分に1回クライアントへpingを送り、3回連続でクライアントからの応答(pong)が無かった場合は、自動的に切断されます。
最新レート
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://forex-api.coin.z.com/ws/public/v1");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "ticker",
"symbol": "USD_JPY"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://forex-api.coin.z.com/ws/public/v1')
def on_open(self):
message = {
"command": "subscribe",
"channel": "ticker",
"symbol": "USD_JPY"
}
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://forex-api.coin.z.com/ws/public/v1"
origin := "https://forex-api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "ticker",
"symbol": "USD_JPY"
}`)
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://forex-api.coin.z.com/ws/public/v1")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "ticker",
:symbol => 'USD_JPY'
}
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://forex-api.coin.z.com/ws/public/v1"
var sendMsg = """
{"command": "subscribe",
"channel": "ticker",
"symbol": "USD_JPY"}
"""
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://forex-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": "USD_JPY" }');
}, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
#![deny(warnings)]
extern crate tungstenite;
extern crate url;
use tungstenite::{connect, Message};
use url::Url;
fn main() {
ticker_ws();
}
fn ticker_ws() {
let (mut socket, _response) =
connect(Url::parse("wss://forex-api.coin.z.com/ws/public/v1").unwrap()).expect("Can't connect");
socket
.write_message(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"USD_JPY\" }".into()))
.unwrap();
loop {
let msg = socket.read_message().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"USD_JPY\" }" :: 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 "forex-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://forex-api.coin.z.com/ws/public/v1";
const string message = "{ \"command\" : \"subscribe\", \"channel\": \"ticker\", \"symbol\": \"USD_JPY\" }";
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://forex-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\": \"USD_JPY\" }";
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://forex-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": "USD_JPY"
}
""")
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:
{
"symbol": "USD_JPY",
"ask": "140.534",
"bid": "140.502",
"timestamp": "2018-03-30T12:34:56.789984Z",
"status": "OPEN"
}
指定した銘柄の最新レートを受信します。
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 |
---|---|---|
symbol | string | 取扱銘柄はこちら |
ask | string | 現在の買値 |
bid | string | 現在の売値 |
timestamp | string | 現在レートのタイムスタンプ |
status | string | 外国為替FXステータス: CLOSE OPEN |
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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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": [
{
"equity": "120947776",
"availableAmount": "89717102",
"balance": "116884885",
"estimatedTradeFee": "766.5",
"margin": "31227908",
"marginRatio": "406.3",
"positionLossGain": "3884065.046",
"totalSwap": "178825.439",
"transferableAmount": "85654212"
}
],
"responsetime": "2019-03-19T02:15:06.055Z"
}
資産残高を取得します。
Request
GET /private/v1/account/assets
Parameters
無し
Response
Property Name | Value | Description |
---|---|---|
equity | string | 時価評価総額 |
availableAmount | string | 取引余力 |
balance | string | 現金残高 |
estimatedTradeFee | string | 見込み手数料 |
margin | string | 拘束証拠金 |
marginRatio | string | 証拠金維持率 |
positionLossGain | string | 評価損益 |
totalSwap | 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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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": [
{
"rootOrderId": 223456789,
"clientOrderId": "sygngz1234",
"orderId": 223456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "140",
"status": "EXECUTED",
"expiry" : "20201113",
"timestamp": "2020-10-14T20:18:59.343Z"
},
{
"rootOrderId": 123456789,
"orderId": 123456789,
"symbol": "CAD_JPY",
"side": "SELL",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "CLOSE",
"size": "10000",
"price": "110",
"status": "CANCELED",
"cancelType": "USER",
"expiry" : "20201113",
"timestamp": "2020-10-14T20:18:59.343Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.059Z"
}
指定した注文IDの注文情報を取得します。
rootOrderId
orderId
いずれか1つが必須です。2つ同時には設定できません。
Request
GET /private/v1/orders
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
rootOrderId | number | * |
rootOrderId orderId いずれか1つが必須※カンマ区切りで最大10件まで指定可能 |
orderId | number | * |
rootOrderId orderId いずれか1つが必須※カンマ区切りで最大10件まで指定可能 |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: NORMAL OCO IFD IFDOCO LOSSCUT |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
price | string | 注文価格 ※ LIMIT STOP の場合のみ返却 |
status | string | 注文ステータス: WAITING ORDERED MODIFYING CANCELED EXECUTED EXPIRED |
cancelType | string | 取消区分: USER INSUFFICIENT_COLLATERAL INSUFFICIENT_MARGIN SPEED OCO EXPIRATION PRICE_BOUND OUT_OF_SLIPPAGE_RANGE ※statusが CANCELED またはEXPIRED の場合のみ返却 |
expiry | 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://forex-api.coin.z.com/private';
const path = '/v1/activeOrders';
const parameters = '?symbol=USD_JPY&prevId=123456790&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://forex-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": "USD_JPY",
"prevId": 123456790,
"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://forex-api.coin.z.com/private"
path := "/v1/activeOrders"
parameters := "?symbol=USD_JPY&prevId=123456790&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://forex-api.coin.z.com/private'
path = '/v1/activeOrders'
parameters = {
:symbol => 'USD_JPY',
:prevId => 123456790,
: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://forex-api.coin.z.com/private"
var path = "/v1/activeOrders"
var parameters = "?symbol=USD_JPY&prevId=123456790&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://forex-api.coin.z.com/private';
$path = '/v1/activeOrders';
$parameters = '?symbol=USD_JPY&prevId=123456790&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://forex-api.coin.z.com/private";
let path = "/v1/activeOrders";
let parameters = json!({
"symbol": "USD_JPY",
"prevId": 123456790,
"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://forex-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 "USD_JPY"), ("prevId", Just "123456790"), ("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://forex-api.coin.z.com/private";
const string path = "/v1/activeOrders";
const string parameters = "?symbol=USD_JPY&prevId=123456790&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://forex-api.coin.z.com/private"
let path : String = "/v1/activeOrders"
let parameters = "?symbol=USD_JPY&prevId=123456790&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": {
"list": [
{
"rootOrderId": 123456789,
"orderId": 123456789,
"clientOrderId": "abc123",
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "135.5",
"status": "ORDERED",
"expiry": "20190418",
"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 | Optional | 取扱銘柄はこちら |
prevId | number | Optional | 注文IDを指定※ 指定しない場合は最新から取得 指定した場合は指定した値より小さい注文IDを持つデータを取得 |
count | number | Optional | 取得件数: 指定しない場合は100(最大値) |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
orderId | number | 注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: NORMAL OCO IFD IFDOCO |
executionType | string | 注文タイプ: LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
price | string | 注文価格 |
status | string | 注文ステータス: WAITING MODIFYING ORDERED |
expiry | 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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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": [
{
"amount":"16215.999",
"executionId": 92123912,
"clientOrderId": "aaaaa",
"orderId": 223456789,
"positionId": 2234567,
"symbol": "USD_JPY",
"side": "SELL",
"settleType": "CLOSE",
"size": "10000",
"price": "141.251",
"lossGain": "15730",
"fee": "-30",
"settledSwap":"515.999",
"timestamp": "2020-11-24T21:27:04.764Z"
},
{
"amount":"0",
"executionId": 72123911,
"clientOrderId": "bbbbb",
"orderId": 123456789,
"positionId": 1234567,
"symbol": "USD_JPY",
"side": "BUY",
"settleType": "OPEN",
"size": "10000",
"price": "141.269",
"lossGain": "0",
"fee": "0",
"settledSwap":"0",
"timestamp": "2020-11-24T19:47:51.234Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.081Z"
}
約定情報を取得します。
orderId
executionId
いずれか1つが必須です。2つ同時には設定できません。
Request
GET /private/v1/executions
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
orderId | number | * |
orderId executionId いずれか1つが必須 |
executionId | string | * |
orderId executionId いずれか1つが必須※ executionId のみカンマ区切りで最大10件まで指定可能 |
Response
Property Name | Value | Description |
---|---|---|
amount | string | 受渡金額 |
executionId | number | 約定ID |
clientOrderId | string | 顧客注文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 | 取引手数料 |
settledSwap | 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://forex-api.coin.z.com/private';
const path = '/v1/latestExecutions';
const parameters = '?symbol=USD_JPY&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://forex-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": "USD_JPY",
"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://forex-api.coin.z.com/private"
path := "/v1/latestExecutions"
parameters := "?symbol=USD_JPY&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://forex-api.coin.z.com/private'
path = '/v1/latestExecutions'
parameters = {
:symbol => 'USD_JPY',
: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://forex-api.coin.z.com/private"
var path = "/v1/latestExecutions"
var parameters = "?symbol=USD_JPY&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://forex-api.coin.z.com/private';
$path = '/v1/latestExecutions';
$parameters = '?symbol=USD_JPY&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://forex-api.coin.z.com/private";
let path = "/v1/latestExecutions";
let parameters = json!({
"symbol": "USD_JPY",
"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://forex-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 "USD_JPY"), ("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://forex-api.coin.z.com/private";
const string path = "/v1/latestExecutions";
const string parameters = "?symbol=USD_JPY&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://forex-api.coin.z.com/private"
let path : String = "/v1/latestExecutions"
let parameters = "?symbol=USD_JPY&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": {
"list": [
{
"amount":"16215.999",
"executionId": 92123912,
"clientOrderId": "ccccc",
"orderId": 223456789,
"positionId": 2234567,
"symbol": "USD_JPY",
"side": "SELL",
"settleType": "CLOSE",
"size": "10000",
"price": "141.251",
"lossGain": "15730",
"fee": "-30",
"settledSwap":"515.999",
"timestamp": "2020-11-24T21:27:04.764Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.086Z"
}
最新約定一覧を取得します。
- 直近1日分から最新100件の約定情報を返します。
Request
GET /private/v1/latestExecutions
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
count | number | Optional | 取得件数: 指定しない場合は100(最大値) |
Response
Property Name | Value | Description |
---|---|---|
amount | string | 受渡金額 |
executionId | number | 約定ID |
clientOrderId | string | 顧客注文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 | 取引手数料 |
settledSwap | 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://forex-api.coin.z.com/private';
const path = '/v1/openPositions';
const parameters = '?symbol=USD_JPY&prevId=123456790&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://forex-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": "USD_JPY",
"prevId": 123456790,
"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://forex-api.coin.z.com/private"
path := "/v1/openPositions"
parameters := "?symbol=USD_JPY&prevId=123456790&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://forex-api.coin.z.com/private'
path = '/v1/openPositions'
parameters = {
:symbol => 'USD_JPY',
:prevId => 123456790,
: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://forex-api.coin.z.com/private"
var path = "/v1/openPositions"
var parameters = "?symbol=USD_JPY&prevId=123456790&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://forex-api.coin.z.com/private';
$path = '/v1/openPositions';
$parameters = '?symbol=USD_JPY&prevId=123456790&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://forex-api.coin.z.com/private";
let path = "/v1/openPositions";
let parameters = json!({
"symbol": "USD_JPY",
"prevId": 123456790,
"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://forex-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 "USD_JPY"), ("prevId", Just "123456790"), ("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://forex-api.coin.z.com/private";
const string path = "/v1/openPositions";
const string parameters = "?symbol=USD_JPY&prevId=123456790&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://forex-api.coin.z.com/private"
let path : String = "/v1/openPositions"
let parameters = "?symbol=USD_JPY&prevId=123456790&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": {
"list": [
{
"positionId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"size": "10000",
"orderedSize": "0",
"price": "141.269",
"lossGain": "-1980",
"totalSwap":"0" ,
"timestamp": "2019-03-21T05:18:09.011Z"
}
]
},
"responsetime": "2019-03-19T02:15:06.095Z"
}
有効建玉一覧を取得します。
Request
GET /private/v1/openPositions
Parameters
- Parameter type: query
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Optional | 取扱銘柄はこちら |
prevId | number | Optional | 建玉IDを指定※ 指定しない場合は最新から取得 指定した場合は指定した値より小さい建玉IDを持つデータを取得 |
count | number | Optional | 取得件数: 指定しない場合は100(最大値) |
Response
Property Name | Value | Description |
---|---|---|
positionId | number | 建玉ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
size | string | 建玉数量 |
orderedSize | string | 注文中数量 |
price | string | 建玉レート |
lossGain | string | 評価損益 |
totalSwap | 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://forex-api.coin.z.com/private';
const path = '/v1/positionSummary';
const parameters = '?symbol=USD_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://forex-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": "USD_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://forex-api.coin.z.com/private"
path := "/v1/positionSummary"
parameters := "?symbol=USD_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://forex-api.coin.z.com/private'
path = '/v1/positionSummary'
parameters = {
:symbol => 'USD_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://forex-api.coin.z.com/private"
var path = "/v1/positionSummary"
var parameters = "?symbol=USD_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://forex-api.coin.z.com/private';
$path = '/v1/positionSummary';
$parameters = '?symbol=USD_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://forex-api.coin.z.com/private";
let path = "/v1/positionSummary";
let mut parameters = HashMap::new();
parameters.insert("symbol", "USD_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://forex-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 "USD_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://forex-api.coin.z.com/private";
const string path = "/v1/positionSummary";
const string parameters = "?symbol=USD_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://forex-api.coin.z.com/private"
let path : String = "/v1/positionSummary"
let parameters = "?symbol=USD_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": "140.043",
"positionLossGain": "2322204.675",
"side": "BUY",
"sumOrderedSize": "0",
"sumPositionSize": "1353339",
"sumTotalSwap": "161600.404",
"symbol": "USD_JPY"
},
{
"averagePositionRate": "140.082",
"positionLossGain": "-2588483.591",
"side": "SELL",
"sumOrderedSize": "20000",
"sumPositionSize": "1481339",
"sumTotalSwap": "-178353.217",
"symbol": "USD_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 |
sumOrderedSize | string | 合計注文中数量 |
sumPositionSize | string | 合計建玉数量 |
sumTotalSwap | 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://forex-api.coin.z.com/private';
const path = '/v1/speedOrder';
const reqBody = JSON.stringify({
symbol: "USD_JPY",
side: "BUY",
clientOrderId: "abc123",
size: "10000",
upperBound: "138",
isHedgeableze: "false"
})
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://forex-api.coin.z.com/private'
path = '/v1/speedOrder'
reqBody = {
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"size": "10000",
"upperBound": "138",
"isHedgeableze": "false"
}
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://forex-api.coin.z.com/private"
path := "/v1/speedOrder"
reqBody := (`{
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"size": "10000",
"upperBound": "138",
"isHedgeableze": "false"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/speedOrder'
reqBody = {
:symbol => 'USD_JPY',
:side => 'BUY',
:clientOrderId => 'abc123',
:size => '10000',
:upperBound => '138',
:isHedgeable => 'false'
}
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://forex-api.coin.z.com/private"
var path = "/v1/speedOrder"
var reqBody = """
{"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"size": "10000",
"upperBound": "138",
"isHedgeable": "false"
}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/speedOrder';
$reqBody = '{
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"size": "10000",
"upperBound": "138",
"isHedgeable": "false"
}';
$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() {
speedOrder().unwrap();
}
fn speedOrder() -> 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://forex-api.coin.z.com/private";
let path = "/v1/speedOrder";
let parameters = json!({
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"size": "10000",
"upperBound": "138",
"isHedgeable": false
});
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://forex-api.coin.z.com/private"
path :: S.String
path = "/v1/speedOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"size": "10000",
"upperBound": "138",
"isHedgeable": "false"}
|]
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 = speedOrder();
task.Wait();
Console.WriteLine(task.Result);
}
static async Task<String> speedOrder()
{
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://forex-api.coin.z.com/private";
const string path = "/v1/speedOrder";
var reqBody = "{ \"symbol\": \"USD_JPY\", " +
"\"side\": \"BUY\", " +
"\"clientOrderId\": \"abc123\", " +
"\"size\": \"10000\", " +
"\"upperBound\": \"138\", " +
"\"isHedgeable\": \"false\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/speedOrder"
let reqBodyStr = """
{
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"size": "10000",
"upperBound": "138",
"isHedgeable": "false"
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "sygngz1234",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "MARKET",
"settleType": "OPEN",
"size": "10000",
"status": "EXECUTED",
"timestamp": "2019-03-19T02:15:06.059Z"
}
],
"responsetime": "2019-03-19T02:15:06.069Z"
}
スピード注文をします。
Request
POST /private/v1/speedOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
side | string | Required |
BUY SELL |
clientOrderId | string | Optional | 顧客注文ID ※36文字以内の半角英数字の組合わせのみ使用可能 |
size | string | Required |
注文数量 |
lowerBound | string | Optional | 成立下限価格 ※side: SELL の場合に指定可能 |
upperBound | string | Optional | 成立上限価格 ※side: BUY の場合に指定可能 |
isHedgeable | bool | Optional | 両建てなし: false(デフォルト) 両建てあり:true |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: NORMAL |
executionType | string | 注文タイプ: MARKET |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
status | string | 注文ステータス: EXECUTED EXPIRED |
cancelType | string | 取消区分: PRICE_BOUND ※statusが EXPIRED の場合のみ返却 |
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 = 'POST';
const endPoint = 'https://forex-api.coin.z.com/private';
const path = '/v1/order';
const reqBody = JSON.stringify({
symbol: "USD_JPY",
side: "BUY",
size: "10000",
clientOrderId: "abc123",
executionType: "LIMIT",
limitPrice: "130"
})
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://forex-api.coin.z.com/private'
path = '/v1/order'
reqBody = {
"symbol": "USD_JPY",
"side": "BUY",
"size": "10000",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "130"
}
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://forex-api.coin.z.com/private"
path := "/v1/order"
reqBody := (`{
"symbol": "USD_JPY",
"side": "BUY",
"size": "10000",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "130"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/order'
reqBody = {
:symbol => 'USD_JPY',
:side => 'BUY',
:size => '10000',
:clientOrderId => 'abc123',
:executionType => 'LIMIT',
:limitPrice => '130'
}
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://forex-api.coin.z.com/private"
var path = "/v1/order"
var reqBody = """
{"symbol": "USD_JPY",
"side": "BUY",
"size": "10000",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "130"
}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/order';
$reqBody = '{
"symbol": "USD_JPY",
"side": "BUY",
"size": "10000",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "130"
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/order";
let parameters = json!({
"symbol": "USD_JPY",
"side": "BUY",
"size": "10000",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "130"
});
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://forex-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": "USD_JPY",
"side": "BUY",
"size": "10000",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "130" }
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/order";
var reqBody = "{ \"symbol\": \"USD_JPY\", " +
"\"side\": \"BUY\", " +
"\"size\": \"10000\", " +
"\"clientOrderId\": \"abc123\", " +
"\"executionType\": \"LIMIT\", " +
"\"limitPrice\": \"130\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/order"
let reqBodyStr = """
{
"symbol": "USD_JPY",
"side": "BUY",
"size": "10000",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "130"
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "130",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
}
],
"responsetime": "2019-03-19T02:15:06.059Z"
}
新規注文をします。
Request
POST /private/v1/order
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
side | string | Required |
BUY SELL |
size | string | Required |
注文数量 |
clientOrderId | string | Optional | 顧客注文ID ※36文字以内の半角英数字の組合わせのみ使用可能 |
executionType | string | Required |
MARKET LIMIT STOP OCO |
limitPrice | string | *executionTypeによる |
指値注文レート ※ LIMIT OCO の場合は必須 |
stopPrice | string | *executionTypeによる |
逆指値注文レート ※ STOP OCO の場合は必須 |
lowerBound | string | Optional | 成立下限価格 ※executionType: MARKET side: SELL の場合に指定可能 |
upperBound | string | Optional | 成立上限価格 ※executionType: MARKET side:BUY の場合に指定可能 |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: NORMAL OCO |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
settleType | string | 決済区分: OPEN |
size | string | 注文数量 |
price | string | 注文価格 ※ LIMIT STOP の場合のみ返却 |
status | string | 注文ステータス: WAITING EXECUTED EXPIRED |
cancelType | string | 取消区分: PRICE_BOUND OCO ※statusが EXPIRED の場合のみ返却 |
expiry | string | 注文有効期限 |
timestamp | string | 注文日時 |
IFD注文
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://forex-api.coin.z.com/private';
const path = '/v1/ifdOrder';
const reqBody = JSON.stringify({
symbol: "USD_JPY",
clientOrderId: "abc123",
firstSide: "BUY",
firstExecutionType: "LIMIT",
firstSize: "10000",
firstPrice: "130",
secondExecutionType: "LIMIT",
secondSize: "10000",
secondPrice: "145"
})
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://forex-api.coin.z.com/private'
path = '/v1/ifdOrder'
reqBody = {
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "130",
"secondExecutionType": "LIMIT",
"secondSize": "10000",
"secondPrice": "145"
}
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://forex-api.coin.z.com/private"
path := "/v1/ifdOrder"
reqBody := (`{
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "130",
"secondExecutionType": "LIMIT",
"secondSize": "10000",
"secondPrice": "145"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/ifdOrder'
reqBody = {
:symbol => 'USD_JPY',
:clientOrderId => 'abc123',
:firstSide => 'BUY',
:firstExecutionType => 'LIMIT',
:firstSize => '10000',
:firstPrice => '130',
:secondExecutionType => 'LIMIT',
:secondSize => '10000',
:secondPrice => '145'
}
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://forex-api.coin.z.com/private"
var path = "/v1/ifdOrder"
var reqBody = """
{"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "130",
"secondExecutionType": "LIMIT",
"secondSize": "10000",
"secondPrice": "145"
}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/ifdOrder';
$reqBody = '{
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "130",
"secondExecutionType": "LIMIT",
"secondSize": "10000",
"secondPrice": "145"
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/ifdOrder";
let parameters = json!({
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "130",
"secondExecutionType": "LIMIT",
"secondSize": "10000",
"secondPrice": "145"
});
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://forex-api.coin.z.com/private"
path :: S.String
path = "/v1/ifdOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "130",
"secondExecutionType": "LIMIT",
"secondSize": "10000",
"secondPrice": "145"}
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/ifdOrder";
var reqBody = "{ \"symbol\": \"USD_JPY\", " +
"\"clientOrderId\": \"abc123\", " +
"\"firstSide\": \"BUY\", " +
"\"firstExecutionType\": \"LIMIT\", " +
"\"firstSize\": \"10000\", " +
"\"firstPrice\": \"130\", " +
"\"secondExecutionType\": \"LIMIT\", " +
"\"secondSize\": \"10000\", " +
"\"secondPrice\": \"145\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/ifdOrder"
let reqBodyStr = """
{
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "130",
"secondExecutionType": "LIMIT",
"secondSize": "10000",
"secondPrice": "145"
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "IFD",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "130",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
},
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456790,
"symbol": "USD_JPY",
"side": "SELL",
"orderType": "IFD",
"executionType": "LIMIT",
"settleType": "CLOSE",
"size": "10000",
"price": "145",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
}
],
"responsetime": "2019-03-19T02:15:06.059Z"
}
IFD注文をします。
Request
POST /private/v1/ifdOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
clientOrderId | string | Optional | 顧客注文ID ※36文字以内の半角英数字の組合わせのみ使用可能 |
firstSide | string | Required |
BUY SELL ※firstSideで指定していない売買区分が2次注文の売買区分 |
firstExecutionType | string | Required |
LIMIT STOP |
firstSize | string | Required |
1次注文数量 |
firstPrice | string | Required |
1次注文レート |
secondExecutionType | string | Required |
LIMIT STOP |
secondSize | string | Required |
2次注文数量 |
secondPrice | string | Required |
2次注文レート |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: IFD |
executionType | string | 注文タイプ: LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
price | string | 注文価格 |
status | string | 注文ステータス: WAITING ORDERED EXECUTED |
expiry | string | 注文有効期限 |
timestamp | string | 注文日時 |
IFDOCO注文
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://forex-api.coin.z.com/private';
const path = '/v1/ifoOrder';
const reqBody = JSON.stringify({
symbol: "USD_JPY",
clientOrderId: "abc123",
firstSide: "BUY",
firstExecutionType: "LIMIT",
firstSize: "10000",
firstPrice: "135",
secondSize: "10000",
secondLimitPrice: "140",
secondStopPrice: "132"
})
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://forex-api.coin.z.com/private'
path = '/v1/ifoOrder'
reqBody = {
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "135",
"secondSize": "10000",
"secondLimitPrice": "140",
"secondStopPrice": "132"
}
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://forex-api.coin.z.com/private"
path := "/v1/ifoOrder"
reqBody := (`{
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "135",
"secondSize": "10000",
"secondLimitPrice": "140",
"secondStopPrice": "145"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/ifoOrder'
reqBody = {
:symbol => 'USD_JPY',
:clientOrderId => 'abc123',
:firstSide => 'BUY',
:firstExecutionType => 'LIMIT',
:firstSize => '10000',
:firstPrice => '135',
:secondSize => '10000',
:secondLimitPrice => '140',
:secondStopPrice => '132'
}
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://forex-api.coin.z.com/private"
var path = "/v1/ifoOrder"
var reqBody = """
{"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "135",
"secondSize": "10000",
"secondLimitPrice": "140",
"secondStopPrice": "132"
}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/ifoOrder';
$reqBody = '{
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "135",
"secondSize": "10000",
"secondLimitPrice": "140",
"secondStopPrice": "132"
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/ifoOrder";
let parameters = json!({
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "135",
"secondSize": "10000",
"secondLimitPrice": "140",
"secondStopPrice": "132"
});
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://forex-api.coin.z.com/private"
path :: S.String
path = "/v1/ifoOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "135",
"secondSize": "10000",
"secondLimitPrice": "140",
"secondStopPrice": "132"}
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/ifoOrder";
var reqBody = "{ \"symbol\": \"USD_JPY\", " +
"\"clientOrderId\": \"abc123\", " +
"\"firstSide\": \"BUY\", " +
"\"firstExecutionType\": \"LIMIT\", " +
"\"firstSize\": \"10000\", " +
"\"firstPrice\": \"135\", " +
"\"secondSize\": \"10000\", " +
"\"secondLimitPrice\": \"140\", " +
"\"secondStopPrice\": \"132\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/ifoOrder"
let reqBodyStr = """
{
"symbol": "USD_JPY",
"clientOrderId": "abc123",
"firstSide": "BUY",
"firstExecutionType": "LIMIT",
"firstSize": "10000",
"firstPrice": "135",
"secondSize": "10000",
"secondLimitPrice": "140",
"secondStopPrice": "132"
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "IFDOCO",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "135",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
},
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456790,
"symbol": "USD_JPY",
"side": "SELL",
"orderType": "IFDOCO",
"executionType": "LIMIT",
"settleType": "CLOSE",
"size": "10000",
"price": "140",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
},
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456791,
"symbol": "USD_JPY",
"side": "SELL",
"orderType": "IFDOCO",
"executionType": "STOP",
"settleType": "CLOSE",
"size": "10000",
"price": "132",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
}
],
"responsetime": "2019-03-19T02:15:06.059Z"
}
IFDOCO注文をします。
Request
POST /private/v1/ifoOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
symbol | string | Required |
取扱銘柄はこちら |
clientOrderId | string | Optional | 顧客注文ID ※36文字以内の半角英数字の組合わせのみ使用可能 |
firstSide | string | Required |
BUY SELL ※firstSideで指定していない売買区分が2次注文の売買区分 |
firstExecutionType | string | Required |
LIMIT STOP |
firstSize | string | Required |
1次注文数量 |
firstPrice | string | Required |
1次注文レート |
secondSize | string | Required |
2次注文数量 |
secondLimitPrice | string | Required |
2次指値注文レート |
secondStopPrice | string | Required |
2次逆指値注文レート |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: IFDOCO |
executionType | string | 注文タイプ: LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
price | string | 注文価格 |
status | string | 注文ステータス: WAITING ORDERED EXECUTED |
expiry | 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 = 'POST';
const endPoint = 'https://forex-api.coin.z.com/private';
const path = '/v1/changeOrder';
const reqBody = JSON.stringify({
orderId: 123456789,
price: "139"
})
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://forex-api.coin.z.com/private'
path = '/v1/changeOrder'
reqBody = {
"orderId": 123456789,
"price": "139"
}
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://forex-api.coin.z.com/private"
path := "/v1/changeOrder"
reqBody := (`{
"orderId": 123456789,
"price": "139"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/changeOrder'
reqBody = {
:orderId => 123456789,
:price => '139'
}
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://forex-api.coin.z.com/private"
var path = "/v1/changeOrder"
var reqBody = """
{"orderId": 123456789, "price": "139"}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/changeOrder';
$reqBody = '{
orderId: 123456789,
price: "139"
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/changeOrder";
let parameters = json!({
"orderId": 123456789,
"price": "139"
});
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://forex-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": 123456789,
"price": "139"
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/changeOrder";
var reqBody = "{ \"orderId\": 123456789, " +
"\"price\": \"139\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/changeOrder"
let reqBodyStr = """
{
"orderId": 123456789,
"price": "139"
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "139",
"status": "ORDERED",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
}
],
"responsetime": "2019-03-19T02:15:06.059Z"
}
注文変更をします。
orderId
clientOrderId
いずれか1つが必須です。2つ同時には設定できません。
Request
POST /private/v1/changeOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
orderId | number | * |
orderId clientOrderId いずれか1つが必須 |
clientOrderId | string | * |
orderId clientOrderId いずれか1つが必須 |
price | string | Required |
注文レート |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: NORMAL |
executionType | string | 注文タイプ: LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
price | string | 注文価格 |
status | string | 注文ステータス: ORDERED MODIFYING EXECUTED |
expiry | string | 注文有効期限 |
timestamp | string | 注文日時 |
OCO注文変更
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://forex-api.coin.z.com/private';
const path = '/v1/changeOcoOrder';
const reqBody = JSON.stringify({
"clientOrderId": "abc123",
"limitPrice": "140.525",
"stopPrice": "145.607"
})
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://forex-api.coin.z.com/private'
path = '/v1/changeOcoOrder'
reqBody = {
"clientOrderId": "abc123",
"limitPrice": "140.525",
"stopPrice": "145.607"
}
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://forex-api.coin.z.com/private"
path := "/v1/changeOcoOrder"
reqBody := (`{
"clientOrderId": "abc123",
"limitPrice": "140.525",
"stopPrice": "145.607"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/changeOcoOrder'
reqBody = {
:clientOrderId => 'abc123',
:limitPrice => '140.525',
:stopPrice => '145.607'
}
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://forex-api.coin.z.com/private"
var path = "/v1/changeOcoOrder"
var reqBody = """
{"clientOrderId": "abc123", "limitPrice": "140.525", "stopPrice": "145.607"}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/changeOcoOrder';
$reqBody = '{
clientOrderId: "abc123",
limitPrice: "140.525",
stopPrice: "145.607"
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/changeOcoOrder";
let parameters = json!({
"clientOrderId": "abc123",
"limitPrice": "140.525",
"stopPrice": "145.607"
});
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://forex-api.coin.z.com/private"
path :: S.String
path = "/v1/changeOcoOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"clientOrderId": "abc123",
"limitPrice": "140.525",
"stopPrice": "145.607"
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/changeOcoOrder";
var reqBody = "{ \"clientOrderId\": \"abc123\", " +
"\"limitPrice\": \"140.525\", " +
"\"stopPrice\": \"145.607\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/changeOcoOrder"
let reqBodyStr = """
{
"clientOrderId": "abc123",
"limitPrice": "140.525",
"stopPrice": "145.607"
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "OCO",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "140.525",
"status": "EXECUTED",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
},
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456790,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "OCO",
"executionType": "STOP",
"settleType": "OPEN",
"size": "10000",
"price": "145.607",
"status": "EXPIRED",
"cancelType": "OCO",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
}
],
"responsetime": "2019-03-19T02:15:06.059Z"
}
OCO注文変更をします。
rootOrderId
clientOrderId
いずれか1つが必須です。2つ同時には設定できません。-
limitPrice
stopPrice
両方もしくはどちらか1つが必須です。
Request
POST /private/v1/changeOcoOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
rootOrderId | number | * |
rootOrderId clientOrderId いずれか1つが必須 |
clientOrderId | string | * |
rootOrderId clientOrderId いずれか1つが必須 |
limitPrice | string | * |
指値注文レート ※ limitPrice stopPrice 両方もしくはどちらか1つ必須 |
stopPrice | string | * |
逆指値注文レート ※ limitPrice stopPrice 両方もしくはどちらか1つ必須 |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: OCO |
executionType | string | 注文タイプ: LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
price | string | 注文価格 |
status | string | 注文ステータス: ORDERED MODIFYING EXECUTED EXPIRED |
cancelType | string | 取消区分: OCO ※statusが EXPIRED の場合のみ返却 |
expiry | string | 注文有効期限 |
timestamp | string | 注文日時 |
IFD注文変更
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://forex-api.coin.z.com/private';
const path = '/v1/changeIfdOrder';
const reqBody = JSON.stringify({
"rootOrderId": 123456789,
"firstPrice": "136.201",
"secondPrice": "139.802"
})
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://forex-api.coin.z.com/private'
path = '/v1/changeIfdOrder'
reqBody = {
"rootOrderId": 123456789,
"firstPrice": "136.201",
"secondPrice": "139.802"
}
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://forex-api.coin.z.com/private"
path := "/v1/changeIfdOrder"
reqBody := (`{
"rootOrderId": 123456789,
"firstPrice": "136.201",
"secondPrice": "139.802"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/changeIfdOrder'
reqBody = {
:rootOrderId => 123456789,
:firstPrice => '136.201',
:secondPrice => '139.802'
}
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://forex-api.coin.z.com/private"
var path = "/v1/changeIfdOrder"
var reqBody = """
{"rootOrderId": 123456789, "firstPrice": "136.201", "secondPrice": "139.802"}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/changeIfdOrder';
$reqBody = '{
rootOrderId": 123456789,
firstPrice": "136.201",
secondPrice": "139.802"
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/changeIfdOrder";
let parameters = json!({
"rootOrderId": 123456789,
"firstPrice": "136.201",
"secondPrice": "139.802"
});
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://forex-api.coin.z.com/private"
path :: S.String
path = "/v1/changeIfdOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"rootOrderId": 123456789,
"firstPrice": "136.201",
"secondPrice": "139.802"
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/changeIfdOrder";
var reqBody = "{ \"rootOrderId\": 123456789, " +
"\"firstPrice\": \"136.201\", " +
"\"secondPrice\": \"139.802\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/changeIfdOrder"
let reqBodyStr = """
{
"rootOrderId": 123456789,
"firstPrice": "136.201",
"secondPrice": "139.802"
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "IFD",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "136.201",
"status": "ORDERED",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
},
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456790,
"symbol": "USD_JPY",
"side": "SELL",
"orderType": "IFD",
"executionType": "LIMIT",
"settleType": "CLOSE",
"size": "10000",
"price": "139.802",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
}
],
"responsetime": "2019-03-19T02:15:06.059Z"
}
IFD注文変更をします。
rootOrderId
clientOrderId
いずれか1つが必須です。2つ同時には設定できません。-
firstPrice
secondPrice
両方もしくはどちらか1つが必須です。
Request
POST /private/v1/changeIfdOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
rootOrderId | number | * |
rootOrderId clientOrderId いずれか1つが必須 |
clientOrderId | string | * |
rootOrderId clientOrderId いずれか1つが必須 |
firstPrice | string | * |
1次注文レート ※ firstPrice secondPrice 両方もしくはどちらか1つ必須 |
secondPrice | string | * |
2次注文レート ※ firstPrice secondPrice 両方もしくはどちらか1つ必須 |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: IFD |
executionType | string | 注文タイプ: LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
price | string | 注文価格 |
status | string | 注文ステータス: WAITING ORDERED MODIFYING EXECUTED |
expiry | string | 注文有効期限 |
timestamp | string | 注文日時 |
IFDOCO注文変更
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://forex-api.coin.z.com/private';
const path = '/v1/changeIfoOrder';
const reqBody = JSON.stringify({
"clientOrderId": "abc123",
"firstPrice": "142.3",
"secondLimitPrice": "136",
"secondStopPrice": "143.1"
})
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://forex-api.coin.z.com/private'
path = '/v1/changeIfoOrder'
reqBody = {
"clientOrderId": "abc123",
"firstPrice": "142.3",
"secondLimitPrice": "136",
"secondStopPrice": "143.1"
}
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://forex-api.coin.z.com/private"
path := "/v1/changeIfoOrder"
reqBody := (`{
"clientOrderId": "abc123",
"firstPrice": "142.3",
"secondLimitPrice": "136",
"secondStopPrice": "143.1"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/changeIfoOrder'
reqBody = {
:clientOrderId => 'abc123',
:firstPrice => '142.3',
:secondStopPrice => '136',
:stopPrice => '143.1'
}
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://forex-api.coin.z.com/private"
var path = "/v1/changeIfoOrder"
var reqBody = """
{"clientOrderId": "abc123", "firstPrice": "142.3", "secondLimitPrice": "136", "secondStopPrice": "143.1"}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/changeIfoOrder';
$reqBody = '{
clientOrderId: "abc123",
firstPrice: "142.3",
secondLimitPrice: "136",
secondStopPrice: "143.1"
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/changeIfoOrder";
let parameters = json!({
"clientOrderId": "abc123",
"firstPrice": "142.3",
"secondLimitPrice": "136",
"secondStopPrice": "143.1"
});
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://forex-api.coin.z.com/private"
path :: S.String
path = "/v1/changeIfoOrder"
main :: IO ()
main = do
posixTime <- getPOSIXTime
let epochTime = BS.pack . show . round $ posixTime
let timestamp = epochTime <> "000"
let requestBodyJson =
[Aeson.QQ.aesonQQ| {
"clientOrderId": "abc123",
"firstPrice": "142.3",
"secondLimitPrice": "136",
"secondStopPrice": "143.1"
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/changeIfoOrder";
var reqBody = "{ \"clientOrderId\": \"abc123\", " +
"\"firstPrice\": \"142.3\", " +
"\"secondLimitPrice\": \"136\", " +
"\"secondStopPrice\": \"143.1\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/changeIfoOrder"
let reqBodyStr = """
{
"clientOrderId": "abc123",
"firstPrice": "142.3",
"secondLimitPrice": "136",
"secondStopPrice": "143.1"
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "SELL",
"orderType": "IFDOCO",
"executionType": "LIMIT",
"settleType": "OPEN",
"size": "10000",
"price": "142.3",
"status": "ORDERED",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
},
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456790,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "IFDOCO",
"executionType": "LIMIT",
"settleType": "CLOSE",
"size": "10000",
"price": "136",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
},
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456791,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "IFDOCO",
"executionType": "STOP",
"settleType": "CLOSE",
"size": "10000",
"price": "143.1",
"status": "WAITING",
"expiry" : "20190418",
"timestamp": "2019-03-19T02:15:06.059Z"
}
],
"responsetime": "2019-03-19T02:15:06.059Z"
}
IFDOCO注文変更をします。
rootOrderId
clientOrderId
いずれか1つが必須です。2つ同時には設定できません。-
firstPrice
secondLimitPrice
secondStopPrice
の内全てもしくはいずれか1つ以上が必須です。
Request
POST /private/v1/changeIfoOrder
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
rootOrderId | number | * |
rootOrderId clientOrderId いずれか1つが必須 |
clientOrderId | string | * |
rootOrderId clientOrderId いずれか1つが必須 |
firstPrice | string | * |
1次注文レート ※ firstPrice secondLimitPrice secondStopPrice の内全てもしくはいずれか1つ以上必須 |
secondLimitPrice | string | * |
2次指値注文レート ※ firstPrice secondLimitPrice secondStopPrice の内全てもしくはいずれか1つ以上必須 |
secondStopPrice | string | * |
2次逆指値注文レート ※ firstPrice secondLimitPrice secondStopPrice の内全てもしくはいずれか1つ以上必須 |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: IFDOCO |
executionType | string | 注文タイプ: LIMIT STOP |
settleType | string | 決済区分: OPEN CLOSE |
size | string | 注文数量 |
price | string | 注文価格 |
status | string | 注文ステータス: WAITING ORDERED MODIFYING EXECUTED EXPIRED |
cancelType | string | 取消区分: OCO ※statusが EXPIRED の場合のみ返却 |
expiry | 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 = 'POST';
const endPoint = 'https://forex-api.coin.z.com/private';
const path = '/v1/cancelOrders';
const reqBody = JSON.stringify({
rootOrderIds: [123456789,223456789]
})
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://forex-api.coin.z.com/private'
path = '/v1/cancelOrders'
reqBody = {
"rootOrderIds": [123456789,223456789]
}
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://forex-api.coin.z.com/private"
path := "/v1/cancelOrders"
reqBody := (`{
"rootOrderIds": [123456789,223456789]
}`)
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://forex-api.coin.z.com/private'
path = '/v1/cancelOrders'
reqBody = {
:rootOrderIds => [123456789,223456789]
}
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://forex-api.coin.z.com/private"
var path = "/v1/cancelOrders"
var reqBody = """
{"rootOrderIds": [123456789,223456789]}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/cancelOrders';
$reqBody = '{
"rootOrderIds": [123456789,223456789]
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/cancelOrders";
let parameters = json!({
"rootOrderIds": [123456789,223456789]
});
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://forex-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| {
"rootOrderIds": [123456789,223456789] }
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/cancelOrders";
var reqBody = "{ \"rootOrderIds\": [123456789,223456789] }";
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://forex-api.coin.z.com/private"
let path : String = "/v1/cancelOrders"
let reqBodyStr = """
{
"rootOrderIds": [123456789,223456789]
}
"""
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": {
"success": [
{
"clientOrderId": "abc123",
"rootOrderId": 123456789
},
{
"rootOrderId": 223456789
}
]
},
"responsetime": "2019-03-19T01:07:24.557Z"
}
複数の注文を取消します。
rootOrderIds
clientOrderIds
いずれか1つが必須です。2つ同時には設定できません。- 最大10件まで注文を取消することができます。
Request
POST /private/v1/cancelOrders
Parameters
- Parameter content type:
application/json
Parameter | Type | Required | Available Values |
---|---|---|---|
rootOrderIds | array | * |
rootOrderIds clientOrderIds いずれか1つが必須※親注文IDを最大10件まで指定可能 |
clientOrderIds | array | * |
rootOrderIds clientOrderIds いずれか1つが必須※顧客注文IDを最大10件まで指定可能 |
Response
Property Name | Value | Description |
---|---|---|
success | array | 取消受付に成功した親注文IDと顧客注文ID ※顧客注文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://forex-api.coin.z.com/private';
const path = '/v1/cancelBulkOrder';
const reqBody = JSON.stringify({
symbols: ["USD_JPY","CAD_JPY"],
side: "BUY",
settleType: "OPEN"
})
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://forex-api.coin.z.com/private'
path = '/v1/cancelBulkOrder'
reqBody = {
"symbols": ["USD_JPY","CAD_JPY"],
"side": "BUY",
"settleType": "OPEN"
}
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://forex-api.coin.z.com/private"
path := "/v1/cancelBulkOrder"
reqBody := (`{
"symbols": ["USD_JPY","CAD_JPY"],
"side": "BUY",
"settleType": "OPEN"
}`)
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://forex-api.coin.z.com/private'
path = '/v1/cancelBulkOrder'
reqBody = {
:symbols => ['USD_JPY','CAD_JPY'],
:side => 'BUY',
:settleType => 'OPEN'
}
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://forex-api.coin.z.com/private"
var path = "/v1/cancelBulkOrder"
var reqBody = """
{"symbols": ["USD_JPY","CAD_JPY"],
"side": "BUY",
"settleType": "OPEN"
}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/cancelBulkOrder';
$reqBody = '{
"symbols": ["USD_JPY","CAD_JPY"],
"side": "BUY",
"settleType": "OPEN"
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/cancelBulkOrder";
let parameters = json!({
"symbols": ["USD_JPY","CAD_JPY"],
"side": "BUY",
"settleType": "OPEN"
});
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://forex-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": ["USD_JPY","CAD_JPY"],
"side": "BUY",
"settleType": "OPEN"
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/cancelBulkOrder";
var reqBody = "{ \"symbols\": [\"USD_JPY\",\"CAD_JPY\"], " +
"\"side\": \"BUY\", " +
"\"settleType\": \"OPEN\"}";
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://forex-api.coin.z.com/private"
let path : String = "/v1/cancelBulkOrder"
let reqBodyStr = """
{
"symbols": ["USD_JPY","CAD_JPY"],
"side": "BUY",
"settleType": "OPEN"
}
"""
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": {
"success": [
{
"clientOrderId": "abc123",
"rootOrderId": 123456789
},
{
"rootOrderId": 223456789
}
]
},
"responsetime": "2019-03-19T01:07:24.557Z"
}
一括で注文(通常注文、特殊注文いずれも)を取消します。
- 取消対象検索後に、対象注文を全て取消します。
- 1次注文が約定していないIFD、IFDOCOケースでは1次注文もしくは2次注文にsideとsettleTypeの両方が一致するものが1つでもあれば注文全体を取消します。
- 1次注文が約定しているIFD、IFDOCOケースでは2次注文にsideとsettleTypeの両方が一致するものがあれば2次注文を取消します。
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 ※指定時のみ指定された決済区分の注文を取消条件に追加 |
Response
Property Name | Value | Description |
---|---|---|
success | array | 取消受付に成功した親注文IDと顧客注文ID ※顧客注文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://forex-api.coin.z.com/private';
const path = '/v1/closeOrder';
const reqBody = JSON.stringify({
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "135.5",
"settlePosition": [
{
"positionId": 1000342,
"size": "10000"
}
]
})
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://forex-api.coin.z.com/private'
path = '/v1/closeOrder'
reqBody = {
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "135.5",
"settlePosition": [
{
"positionId": 1000342,
"size": "10000"
}
]
}
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://forex-api.coin.z.com/private"
path := "/v1/closeOrder"
reqBody := (`{
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "135.5",
"settlePosition": [
{
"positionId": 1000342,
"size": "10000"
}
]
}`)
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://forex-api.coin.z.com/private'
path = '/v1/closeOrder'
reqBody = {
:symbol => 'USD_JPY',
:side => 'BUY',
:clientOrderId => 'abc123',
:executionType => 'LIMIT',
:limitPrice => '135.5',
:settlePosition => [
{
:positionId => 1000342,
:size => '10000'
}
]
}
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://forex-api.coin.z.com/private"
var path = "/v1/closeOrder"
var reqBody = """
{
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "135.5",
"settlePosition": [
{
"positionId": 1000342,
"size": "10000"
}
]}
"""
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://forex-api.coin.z.com/private';
$path = '/v1/closeOrder';
$reqBody = '{
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "135.5",
"settlePosition": [
{
"positionId": 1000342,
"size": "10000"
}
]
}';
$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://forex-api.coin.z.com/private";
let path = "/v1/closeOrder";
let parameters = json!({
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "135.5",
"settlePosition": [
{
"positionId": 1000342,
"size": "10000"
}
]
});
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://forex-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": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "135.5",
"settlePosition": [
{
"positionId": 1000342,
"size": "10000"
}
]}
|]
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://forex-api.coin.z.com/private";
const string path = "/v1/closeOrder";
var reqBody = "{ \"symbol\": \"USD_JPY\", " +
"\"side\": \"BUY\", " +
"\"clientOrderId\": \"abc123\", " +
"\"executionType\": \"LIMIT\", " +
"\"limitPrice\": \"135.5\", " +
"\"settlePosition\": [ { \"positionId\": 1000342, \"size\": \"10000\" } ] }";
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://forex-api.coin.z.com/private"
let path : String = "/v1/closeOrder"
let reqBodyStr = """
{
"symbol": "USD_JPY",
"side": "BUY",
"clientOrderId": "abc123",
"executionType": "LIMIT",
"limitPrice": "135.5",
"settlePosition": [
{
"positionId": 1000342,
"size": "10000"
}
]
}
"""
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": [
{
"rootOrderId": 123456789,
"clientOrderId": "abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"side": "BUY",
"orderType": "NORMAL",
"executionType": "LIMIT",
"settleType": "CLOSE",
"size": "10000",
"price": "135.5",
"status": "WAITING",
"expiry": "20230418",
"timestamp": "2019-03-19T01:07:24.467Z"
}
],
"responsetime": "2019-03-19T01:07:24.557Z"
}
決済注文をします。
size
settlePosition
いずれか1つが必須です。2つ同時には設定できません。
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 OCO |
clientOrderId | string | Optional | 顧客注文ID ※36文字以内の半角英数字の組合わせのみ使用可能 |
size | string | * |
注文数量 建玉指定なし※size settlePosition いずれかのみ指定可能 |
limitPrice | string | *executionTypeによる |
注文レート ※ LIMIT OCO の場合は必須 |
stopPrice | string | *executionTypeによる |
注文レート ※ STOP OCO の場合は必須 |
lowerBound | string | Optional | 成立下限価格 ※executionType: MARKET side: SELL の場合に指定可能 |
upperBound | string | Optional | 成立下限価格 ※executionType: MARKET side: BUY の場合に指定可能 |
settlePostion | array | * |
複数建玉 複数指定可能※size settlePosition いずれかのみ指定可能※最大10件まで指定可能 |
settlePosition.positionId | number | * |
建玉ID |
settlePosition.size | string | * |
注文数量 |
Response
Property Name | Value | Description |
---|---|---|
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
side | string | 売買区分: BUY SELL |
orderType | string | 取引区分: NORMAL OCO |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
settleType | string | 決済区分: CLOSE |
size | string | 注文数量 |
price | string | 注文価格 ※ LIMIT STOP の場合のみ返却 |
status | string | 注文ステータス: WAITING EXECUTED EXPIRED |
cancelType | string | 取消区分: PRICE_BOUND OCO ※statusが EXPIRED の場合のみ返却 |
expiry | string | 注文有効期限 |
timestamp | string | 注文日時 |
Private WebSocket API
- サーバーから1分に1回クライアントへpingを送り、3回連続でクライアントからの応答(pong)が無かった場合は、自動的に切断されます。
- アクセストークンを取得・延長・削除するために専用のPrivate APIを使用します。
- Private WebSocket API接続時
Private WebSocket APIのエンドポイント + アクセストークン
で接続してください。
例:wss://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-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://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://forex-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://forex-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://forex-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://forex-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() {
execution_events_ws();
}
fn execution_events_ws() {
let (mut socket, _response) =
connect(Url::parse("wss://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.write_message(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"executionEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read_message().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"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 "forex-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://forex-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://forex-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://forex-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",
"amount": "-30",
"rootOrderId": 123456789,
"orderId": 123456789,
"clientOrderId": "abc123",
"executionId": 72123911,
"symbol": "USD_JPY",
"settleType": "OPEN",
"orderType": "NORMAL",
"executionType": "LIMIT",
"side": "BUY",
"executionPrice": "138.963",
"executionSize": "10000",
"positionId": 123456789,
"lossGain": "0",
"settledSwap": "0",
"fee": "-30",
"orderPrice": "140",
"orderExecutedSize": "10000",
"orderSize": "10000",
"msgType": "ER",
"orderTimestamp": "2019-03-19T02:15:06.081Z",
"executionTimestamp": "2019-03-19T02:15:06.081Z"
}
最新の約定情報通知を受信します。
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 |
amount | string | 受渡し金額 |
rootOrderId | number | 親注文ID |
orderId | number | 注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
executionId | number | 約定ID |
symbol | string | 取扱銘柄はこちら |
settleType | string | 決済区分: OPEN CLOSE |
orderType | string | 取引区分: NORMAL OCO IFD IFDOCO LOSSCUT |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
side | string | 売買区分: BUY SELL |
executionPrice | string | 約定レート |
executionSize | string | 約定数量 |
positionId | number | 建玉ID |
lossGain | string | 決済損益 |
settledSwap | string | 決済スワップ |
fee | string | 取引手数料 |
orderPrice | string | 注文価格 ※ LIMIT STOP の場合のみ返却 |
orderExecutedSize | string | 約定済み数量 |
orderSize | string | 注文数量 |
msgType | string | メッセージタイプ: ER |
orderTimestamp | string | 注文日時 |
executionTimestamp | string | 約定日時 |
unsubscribe
でリクエストした場合のResponseはありません。
注文情報通知
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://forex-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://forex-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://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://forex-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://forex-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://forex-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://forex-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() {
order_events_ws();
}
fn order_events_ws() {
let (mut socket, _response) =
connect(Url::parse("wss://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.write_message(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"orderEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read_message().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"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 "forex-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://forex-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://forex-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://forex-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",
"rootOrderId": 123456789,
"clientOrderId":"abc123",
"orderId": 123456789,
"symbol": "USD_JPY",
"settleType": "OPEN",
"orderType": "NORMAL",
"executionType": "LIMIT",
"side": "BUY",
"orderStatus": "ORDERED",
"orderTimestamp": "2019-03-19T02:15:06.081Z",
"orderPrice": "135",
"orderSize": "10000",
"expiry" : "20190418",
"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 |
rootOrderId | number | 親注文ID |
clientOrderId | string | 顧客注文ID ※設定した場合のみ返却 |
orderId | number | 注文ID |
symbol | string | 取扱銘柄はこちら |
settleType | string | 決済区分: OPEN CLOSE LOSS_CUT |
orderType | string | 取引区分: NORMAL OCO IFD IFDOCO LOSSCUT |
executionType | string | 注文タイプ: MARKET LIMIT STOP |
side | string | 売買区分: BUY SELL |
orderStatus | string | 注文ステータス: WAITING ORDERED CANCELED EXPIRED |
cancelType | string | 取消区分: USER INSUFFICIENT_COLLATERAL INSUFFICIENT_MARGIN SPEED OCO EXPIRATION PRICE_BOUND OUT_OF_SLIPPAGE_RANGE ※statusが CANCELED またはEXPIRED の場合のみ返却 |
orderTimestamp | string | 注文日時 |
orderPrice | string | 注文価格 ※ LIMIT STOP の場合のみ返却 |
orderSize | string | 注文数量 |
expiry | string | 注文有効期限 |
msgType | string | メッセージタイプ: NOR ROR COR |
unsubscribe
でリクエストした場合のResponseはありません。
ポジション情報通知
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://forex-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://forex-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://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://forex-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://forex-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://forex-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://forex-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() {
position_events_ws();
}
fn position_events_ws() {
let (mut socket, _response) =
connect(Url::parse("wss://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.write_message(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"positionEvents\" }".into()))
.unwrap();
loop {
let msg = socket.read_message().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"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 "forex-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://forex-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://forex-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://forex-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": "USD_JPY",
"side": "BUY",
"size": "500",
"orderdSize": "0",
"price": "139.772",
"lossGain": "-553.5",
"timestamp": "2019-03-19T02:15:06.094Z",
"totalSwap":"-34.4",
"msgType": "UPR"
}
最新のポジション情報通知を受信します。
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 | 評価損益 |
timestamp | string | 約定日時 |
totalSwap | string | 累計スワップ |
msgType | string | メッセージタイプ: OPR UPR CPR |
unsubscribe
でリクエストした場合のResponseはありません。
ポジションサマリー情報通知
Request example:
const WebSocket = require("ws");
const ws = new WebSocket("wss://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx");
ws.on("open", () => {
const message = JSON.stringify(
{
"command": "subscribe",
"channel": "positionSummaryEvents",
"option":"PERIODIC"
});
ws.send(message);
});
ws.on("message", (data) => {
console.log("WebSocket message: ", data);
});
import json
import websocket
websocket.enableTrace(True)
ws = websocket.WebSocketApp('wss://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx')
def on_open(self):
message = {
"command": "subscribe",
"channel": "positionSummaryEvents",
"option":"PERIODIC"
}
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://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
origin := "https://forex-api.coin.z.com"
sendMsg := (`{
"command": "subscribe",
"channel": "positionSummaryEvents",
"option":"PERIODIC"
}`)
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://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx")
ws.on :open do |event|
message = {
:command => "subscribe",
:channel => "positionSummaryEvents",
:option => "PERIODIC"
}
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://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx"
var sendMsg = """
{"command": "subscribe",
"channel": "positionSummaryEvents",
"option":"PERIODIC"}
"""
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://forex-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", "option" : "PERIODIC" }');
}, 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() {
position_events_ws();
}
fn position_events_ws() {
let (mut socket, _response) =
connect(Url::parse("wss://forex-api.coin.z.com/ws/private/v1/xxxxxxxxxxxxxxxxxxxx").unwrap()).expect("Can't connect");
socket
.write_message(Message::Text("{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\", \"option\": \"PERIODIC\" }".into()))
.unwrap();
loop {
let msg = socket.read_message().expect("Error reading message");
println!("{}", msg);
}
}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever, unless)
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.Socket (withSocketsDo)
import qualified Network.WebSockets as WS
import qualified Wuss as WSS (runSecureClient)
app :: WS.ClientApp ()
app conn = do
putStrLn "Connected!"
WS.sendTextData conn ("{ \"command\" : \"subscribe\", \"channel\": \"positionSummaryEvents\", \"option\": \"PERIODIC\" }" :: 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 "forex-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://forex-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://forex-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\", \"option\": \"PERIODIC\" }";
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://forex-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",
"option":"PERIODIC"
}
""")
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":"USD_JPY",
"side":"BUY",
"averagePositionRate":"138.877",
"positionLossGain":"3644808.1",
"sumOrderedSize":"8000",
"sumPositionSize":"1821000",
"sumTotalSwap": "167407.6",
"timestamp":"2020-06-24T09:53:19.702Z",
"msgType":"PERIODIC"
}
最新のポジションサマリー情報通知を受信します。
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 | 評価損益 |
sumOrderedSize | string | 注文中数量 |
sumPositionSize | string | 合計建玉数量 |
sumTotalSwap | string | 累計スワップ |
timestamp | string | 配信日時 |
msgType | string | メッセージタイプ: INIT UPDATE PERIODIC |
unsubscribe
でリクエストした場合のResponseはありません。
リファレンス
APIのパラメータやレスポンスにより返ってくる各種コードについて説明します。
パラメータ
パラメータの値とその内容について説明します。
symbol: 取扱銘柄名
Value | Description | Release date |
---|---|---|
USD_JPY | 米ドル/日本円 | 2023/04/26 |
EUR_JPY | ユーロ/日本円 | 2023/04/26 |
GBP_JPY | 英ポンド/日本円 | 2023/04/26 |
AUD_JPY | 豪ドル/日本円 | 2023/04/26 |
NZD_JPY | NZドル/日本円 | 2023/04/26 |
CAD_JPY | カナダドル/日本円 | 2023/04/26 |
CHF_JPY | スイスフラン/日本円 | 2023/04/26 |
TRY_JPY | トルコリラ/日本円 | 2023/08/05 |
ZAR_JPY | 南アフリカランド/日本円 | 2023/08/05 |
MXN_JPY | メキシコペソ/日本円 | 2023/08/05 |
EUR_USD | ユーロ/米ドル | 2023/04/26 |
GBP_USD | 英ポンド/米ドル | 2023/04/26 |
AUD_USD | 豪ドル/米ドル | 2023/04/26 |
NZD_USD | NZドル/米ドル | 2023/04/26 |
side: 売買区分
Value | Description |
---|---|
BUY | 買 |
SELL | 売 |
executionType: 注文タイプ
Value | Description |
---|---|
MARKET | 成行 |
LIMIT | 指値 |
STOP | 逆指値 |
HTTPステータスコード
Status Code | Description |
---|---|
200 | 処理が正常終了した場合に返ってくるコードです。 |
404 | URLが不正な場合などに返ってくるコードです。 |
503 | メンテナンス時にWebSocket APIを呼び出した場合に返ってくるコードです。 |
ステータスコード
Status Code | Description |
---|---|
0 | 処理が正常終了した場合に返ってくるコードです。 |
エラーコード
Error Code | Description |
---|---|
ERR-143 | 規制中のため取引できない場合に返ってきます。 |
ERR-148 | IFD、IFDOCO注文において新規注文数量より決済注文数量が多い場合に返ってきます。 |
ERR-189 | 決済注文において、決済可能保有数量を超えての数量の注文の場合に返ってきます。 |
ERR-200 | すでに有効注文があり、注文数量が発注可能な数量を超えている場合に返ってきます。決済注文を行いたい場合は、注文数量を変更するか、有効注文を取消したうえで、再度注文をしてください。 |
ERR-201 | 注文時に取引余力が不足している場合に返ってきます。 |
ERR-254 | 指定された建玉が存在しない場合に返ってきます。 |
ERR-414 | 決済注文において指定した銘柄と指定した建玉IDの銘柄が異なっている場合に返ってきます。 |
ERR-423 | 決済注文において注文数量が(指定した建玉、もしくは指定銘柄の建玉の)総建玉数量よりも大きい場合、もしくは総有効注文数量との合計が総建玉数量よりも大きい場合に返ってきます。 |
ERR-512 | 決済注文において同じ建玉IDを2つ以上指定した場合に返ってきます。 |
ERR-542 | OCO注文変更においてOCO注文以外の親注文IDや顧客注文IDを指定した場合に返ってきます。 |
ERR-595 | IFD、IFDOCO注文変更においてIFD、IFDOCO注文以外の親注文IDや顧客注文IDを指定した場合に返ってきます。 |
ERR-635 | 有効注文の件数が上限に達している場合に返ってきます。新規の注文をするためには、有効注文を取消したうえで、再度注文をしてください。 |
ERR-759 | 建玉の件数が上限に達している場合に新規注文を行うと返ってきます。 |
ERR-760 | 注文変更において変更前と後で注文レートが同じ場合に返ってきます。 |
ERR-761 | 指定可能な注文レートの範囲を超えた場合に返ってきます。 |
ERR-769 | 注文変更において変更元となる注文の有効期限が切れている場合に返ってきます。 |
ERR-786 | 設定した顧客注文IDがご自身の他の有効注文に使用されている場合に返ってきます。 |
ERR-5003 | API呼出上限を越えた場合に返ってきます。 |
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-5114 | 注文レートが呼値の単位を超えている場合に返ってきます。取引ルールの呼値をご確認ください。取引ルールはこちらよりご確認いただけます。 |
ERR-5122 | 指定された注文がすでに変更中、取消中、取消済、全量約定、失効のいずれかの状態であるため、注文の変更や取消ができない場合に返ってきます。 |
ERR-5123 | 指定された注文番号が存在しない場合に返ってきます。 |
ERR-5125 | APIの取引規制がかかっている場合に返ってきます。 |
ERR-5126 | 1回あたりの最大注文数量を超えている場合または最小注文数量を下回っている場合、または最大建玉数量を超過する場合に返ってきます。こちらより取引ルールをご確認ください。(APIの最小注文数量は会員ページ・アプリとは異なるのでご注意ください) |
ERR-5130 | 注文情報取得もしくは約定情報取得において指定した注文IDもしくは親注文IDが最大指定数量を超えている場合に返ってきます。 |
ERR-5132 | 約定情報取得において指定した約定IDが最大指定数量を超えている場合に返ってきます。 |
ERR-5201 | 定期メンテナンス時にPublic/Private APIを呼び出した場合に返ってきます。 |
ERR-5202 | 緊急メンテナンス時にPublic/Private APIを呼び出した場合に返ってきます。 |
ERR-5204 | リクエスト時に各APIのURLが不正な場合に返ってきます。 |
ERR-5206 | 注文変更を実行時に注文毎の変更可能回数が上限に達している場合に返ってきます。上限に達して更に注文変更を行いたい場合は、1度注文キャンセルをしてから新規に注文をしていただくようにお願い致します。 |
ERR-5207 | リクエストボディに指定されているsymbol、intervalまたはdateが不正な場合に返ってきます。 |
ERR-5208 | 約定情報取得において、orderId/executionIdが両方設定された場合に返ってきます。 |
ERR-5209 | 注文情報取得において、orderId/rootOrderIdが両方設定された場合に返ってきます。 |
ERR-5210 | 注文タイプと limitPrice/stopPriceが一致していない場合に返ってきます。 |
ERR-5211 | 売買区分と一致しない lowerBound/upperBound を指定した場合、もしくは指値や逆指値注文に lowerBound/upperBound を指定した場合に返ってきます。 |
ERR-5213 | 注文IDもしくは親注文IDと顧客注文IDどちらか一方を指定する箇所でどちらも指定している場合に返ってきます。 |
ERR-5214 | 決済注文において、建玉IDを指定している場合に注文数量を指定すると返ってきます。 |
ERR-5218 | 取引時間外のため注文が行えない場合に返ってきます。 |
ERR-5219 | 注文変更において通常注文以外の注文IDや顧客注文IDを指定した場合に返ってきます。 |
ERR-5220 | IFD注文において1次注文レートを2次注文レートより低く設定しなければならない場合に返ってきます。 |
ERR-5221 | IFD注文において1次注文レートを2次注文レートより高く設定しなければならない場合に返ってきます。 |
ERR-5222 | IFDOCO注文において1次注文レートを2次指値注文レートより低く設定しなければならない場合に返ってきます。 |
ERR-5223 | IFDOCO注文において1次注文レートを2次指値注文レートより高く設定しなければならない場合に返ってきます。 |
ERR-5224 | IFDOCO注文において1次注文レートを2次逆指値注文レートより高く設定しなければならない場合に返ってきます。 |
ERR-5225 | IFDOCO注文において1次注文レートを2次逆指値注文レートより低く設定しなければならない場合に返ってきます。 |
ERR-5226 | 逆指値の買い注文において、注文レートが現在レートより低い場合に返ってきます。 |
ERR-5227 | 逆指値の売り注文において、注文レートが現在レートより高い場合に返ってきます。 |
ERR-5228 | OCO売り注文において逆指値注文レートが指値注文レートを超えている場合に返ってきます。 |
ERR-5229 | OCO買い注文において逆指値注文レートが指値注文レートを下回っている場合に返ってきます。 |
フィードバック
APIについてご要望をお聞かせください。いただいたご要望につきましては、開発チームにて精査のうえ、順次開発、リリースしております。
APIについてのご要望は、こちらよりご連絡ください。
※APIに関するご質問などは、こちらよりお問い合わせください。内容によってはお時間をいただく場合がございます。あらかじめご了承ください。