しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

RubyでBitflyer LightingのAPIを叩いてみる

ビットコインなどの仮想通貨取引所のBitflyerのAPIを試してみました。

ビットコイン取引所【bitFlyer Lightning】

準備

APIを叩くため、まずはrest-clientをBundlerで追加します。

source "https://rubygems.org"

gem "rest-client"

板情報の取得

/boardへのリクエストで板情報を取得できます。
こちらはHTTP Public APIなので、認証情報不要で使う事ができます。

require 'rest-client'
require 'json'

response = RestClient.get('https://api.bitflyer.jp/v1/board')
puts JSON.parse(response.body)

レスポンスは下の通りです。

f:id:llcc:20171209152245p:plain

BTC-FXの板情報の取得

BTC-FXの情報がほしい時はパラメータのproduct_codeにFX_BTC_JPYを指定します。

require 'rest-client'
require 'json'

response = RestClient.get('https://api.bitflyer.jp/v1/board?product_code=FX_BTC_JPY')
puts JSON.parse(response.body)

指定可能なproduct_codeはhttps://api.bitflyer.jp/v1/marketsを叩く事で取得できます。

f:id:llcc:20171209152709p:plain

チャット情報の取得

チャットはhttps://api.bitflyer.jp/v1/getchatsを叩く事で取得できます。

実際に注文する

実際に注文するためには認証情報が必要になります。
まずは下ページで新しいAPIキーを追加します。

ビットコイン取引所【bitFlyer Lightning】

権限は、今回は注文関連と建玉だけにします。

f:id:llcc:20171209153842p:plain

実際の注文処理は下の通りです。
POSTで注文情報を送る事で注文する事ができます。
API_KEYとAPI_SECRETは自分のものに置き換えて下さい。

require 'rest-client'
require 'json'

API_KEY = 'API_KEY'
API_SECRET = 'API_SECRET'

timestamp = Time.now.to_i.to_s
body = {
  product_code: 'FX_BTC_JPY',
  child_order_type: 'LIMIT',
  side: 'BUY',
  price: 1_800_000,
  size: 0.1,
}.to_json
path = '/v1/me/sendchildorder'
url = 'https://api.bitflyer.jp' + path
text = timestamp + 'POST' + path + body
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha256"), API_SECRET, text)

result = RestClient.post(url, body, {
  "ACCESS-KEY" => API_KEY,
  "ACCESS-TIMESTAMP" => timestamp,
  "ACCESS-SIGN" => sign,
  "Content-Type" => "application/json"
})

puts JSON.parse(result)

実際の画面を見ると注文が入っている事が分かります。

f:id:llcc:20171209163652p:plain