Edited at

Bitbank.cc APIでphpを使って注文を出してみる

More than 1 year has passed since last update.

Bitbank.cc APIでphpプログラムで売買したいと思い調査しました。

https://docs.bitbank.cc/

phpのライブラリが用意されてなかったのでベタ書きしてみました。

ハマったのはnonce値はtime()ではなくmicrotime(true)*10000だったというあたりです。


sample.php

// 設定

$coin = [
'jpy' => 0,
'btc' => 1,
'ltc' => 2,
'xrp' => 3,
'eth' => 4,
'mona' => 5,
'bcc' => 6,
];
$pair = 'bcc_jpy';
$public_api_end_point = 'https://public.bitbank.cc';
$private_api_end_point = 'https://api.bitbank.cc/v1';
$api_key = 'ビットバンクで発行したAPIキー';
$api_secret = 'ビットバンクで発行したAPIシークレット';

// 最終プライスを取得
$url = "{$public_api_end_point}/{$pair}/ticker";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$result = json_decode($response, true);
$last_price = $result['data']['last'];
//var_dump($last_price);

// 自身のファンド情報を取得
$ch = curl_init();
$query_params = ''; // ?xxx=xxx&xxx=xxx
$url = $private_api_end_point . '/user/assets' . $query_params;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$microtime = microtime(true) * 10000;
$text = $microtime . '/v1/user/assets' . $query_params;
$signature = hash_hmac('sha256', $text, $api_secret);
$header = [
'Content-Type: application/json',
'Accept: application/json',
"ACCESS-KEY: {$api_key}",
"ACCESS-NONCE: {$microtime}",
"ACCESS-SIGNATURE: {$signature}",
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($ch);
$result = json_decode($response, true);
$jpy_free_amount = $result['data']['assets'][$coin['jpy']]['free_amount'];
//var_dump($jpy_free_amount);

// 注文を出す
$query_params = [
'pair' => $pair,
'amount' => $amount,
'price' => $last_price,
'side' => 'buy', // 買い:buy 売り:sell
'type' => 'limit' // 指し値:limit 成り行き:market
];
$ch = curl_init();
$url = $private_api_end_point . '/user/spot/order';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($query_params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$microtime = microtime(true) * 10000;
$text = $microtime . json_encode($query_params);
$signature = hash_hmac('sha256', $text, $api_secret);
$header = [
'Content-Type: application/json',
'Accept: application/json',
"ACCESS-KEY: {$api_key}",
"ACCESS-NONCE: {$microtime}",
"ACCESS-SIGNATURE: {$signature}",
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($ch);
$result = json_decode($response, true);
//var_dump($result);


参考にさせて頂きました

https://qiita.com/bitrinjani/items/fff7e2bf6a2b8be6eac0