前回の投稿で、「Zaif」のAPIを紹介しました。
今回はビットコイン取引所「coincheck」のAPIをC#で実装したサンプルを紹介します!
他の取引所のAPIについてはコチラ
コード
取引所と通信する基本部のコード
秘密キーによる署名と、HTTPによる応答を行うメソッドをC#で実装したものです。取引所サイトにHTTPでリクエストして、レスポンスとしてJSON形式のテキストを受け取ります。
/// <summary>coincheck取引所のAPIを実行します。
/// </summary>
/// <param name="http">取引所と通信する HttpClient。</param>
/// <param name="path">APIの通信URL(取引所サイトからの相対)。</param>
/// <param name="apiKey">APIキー。</param>
/// <param name="secret">秘密キー。</param>
/// <param name="method">APIのメソッド名。</param>
/// <param name="parameters">APIのパラメータのリスト(Key:パラメータ名, Value:パラメータの値)。</param>
/// <returns>レスポンスとして返されるJSON形式の文字列。</returns>
internal async Task<string> Send(HttpClient http, Uri path, string apiKey, string secret, string method, Dictionary<string, string> parameters = null)
{
if (parameters == null)
parameters = new Dictionary<string, string>();
// パラメータ文字列を作成
var content = new FormUrlEncodedContent(parameters);
string param = await content.ReadAsStringAsync();
// nonceにunixtimeを用いる
string nonce = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
// POSTするメッセージを作成
var uri = new Uri(http.BaseAddress, path);
string message = nonce + uri.ToString() + param;
// メッセージをHMACSHA256で署名
byte[] hash = new HMACSHA256(Encoding.UTF8.GetBytes(secret)).ComputeHash(Encoding.UTF8.GetBytes(message));
string sign = BitConverter.ToString(hash).ToLower().Replace("-", "");//バイト配列をを16進文字列へ
// HTTPヘッダをセット
http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("ACCESS-KEY", apiKey);
http.DefaultRequestHeaders.Add("ACCESS-NONCE", nonce);
http.DefaultRequestHeaders.Add("ACCESS-SIGNATURE", sign);
// 送信
HttpResponseMessage res;
if (method == "POST")
{
res = await http.PostAsync(path, content);
}
else if (method == "GET")
{
res = await http.GetAsync(path);
}
else
{
throw new ArgumentException("method は POST か GET を指定してください。", method);
}
//返答内容を取得
string text = await res.Content.ReadAsStringAsync();
//通信上の失敗
if (!res.IsSuccessStatusCode)
return "";
return text;
}
使用例
先に紹介した通信メソッドの使用例です。コード内のAPIキー(apiKey)と秘密キー(secret)は取引所から取得したものに置き換えてください。
板情報を取得する
//coincheck取引所にアクセスする HttpClient
HttpClient http = new HttpClient();
http.BaseAddress = new Uri("https://coincheck.com");
//板情報を取得
Uri path = new Uri("/api/order_books", UriKind.Relative);//APIの通信URL
string apiKey = "XXXXX";//APIキー
string secret = "XXXXX";//秘密キー
string method = "GET";//APIメソッド
string json = await Send(http, path, apiKey, secret, method);
資産を取得する
//coincheck取引所にアクセスする HttpClient
HttpClient http = new HttpClient();
http.BaseAddress = new Uri("https://coincheck.com");
//資産残高取得
Uri path = new Uri("/api/accounts/balance", UriKind.Relative);//APIの通信URL
string apiKey = "XXXXX";//APIキー
string secret = "XXXXX";//秘密キー
string method = "GET";//APIメソッド
string json = await Send(Http, path, apiKey, secret, method);
買い注文を出す
//coincheck取引所にアクセスする HttpClient
HttpClient http = new HttpClient();
http.BaseAddress = new Uri("https://coincheck.com");
//パラメータ
var param = new Dictionary<string, string>
{
{ "pair", "btc_jpy" },//取引する通貨の種類
{ "order_type", "buy" },//注文の売買の種類(買い:buy, 売り:sell)
{ "rate", "100000" },//ビットコインのレート
{ "amount", "0.01" },//ビットコインの注文量
};
//買い注文を出す
Uri path = new Uri("/api/exchange/orders", UriKind.Relative);//APIの通信URL
string apiKey = "XXXXX";//APIキー
string secret = "XXXXX";//秘密キー
string method = "POST";//APIメソッド
string json = await Send(http, path, apiKey, secret, method, param);
まとめ
こちがcoincheckのAPIのヘルプです。APIキーの取得についても書かれています。
https://coincheck.com/ja/documents/exchange/api
他の取引所のAPIについてはコチラ

