bitFlyer自動取引botのコア部分(発注機能)Rubyソースコード
ビットコインをbitFlyer上で自動取引するbotのコア部分である発注機能(成行注文版)のRubyソースコードを公開します(エラーハンドリングが甘いですが、、間違いや改善点があれば教えてくださいm(_ _)m)。指値注文も、LIMITとpriceを指定すれば簡単に実装できます。product_codeを指定することで、現物にもFXにも使えます。ササッとアイデアを実装に落とし込めるのは、やはりRubyの強みですね。
#!/usr/bin/ruby
require 'uri'
require 'net/http'
require 'time'
require 'securerandom'
require 'base64'
require 'json'
API_KEY = '{{ YOUR API KEY }}'
API_SECRET = '{{ YOUR API SECRET }}'
def order(product_code, buy_sell, size)
timestamp = Time.now.to_i.to_s
uri = URI.parse("https://api.bitflyer.jp")
uri.path = "/v1/me/sendchildorder"body = '{
"product_code" : "' + product_code + '",
"child_order_type" : "MARKET",
"side" : "' + buy_sell + '",
"size" : ' + size.to_s + ',
"minute_to_expire" : 10000,
"time_in_force" : "GTC"
}'text = timestamp + 'POST' + uri.request_uri + body
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha256"), API_SECRET, text)
options = Net::HTTP::Post.new(uri.request_uri, initheader = {
"ACCESS-KEY" => API_KEY,
"ACCESS-TIMESTAMP" => timestamp,
"ACCESS-SIGN" => sign,
"Content-Type" => "application/json"
});
options.body = body
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
response = https.request(options)
result = JSON.parse(response.body)
if (result['status'] == -201) then
puts ' ' + product_code + ' ' + buy_sell + " You have reached the maximum amount of trades for your account class."
return false
end
if (result['child_order_acceptance_id'] == nil) then
puts ' ' + product_code + ' ' + buy_sell + " Insufficient funds"
return false
end
if (result['child_order_acceptance_id'] != nil) then
puts ' ' + product_code + ' ' + buy_sell + " id:" + result['child_order_acceptance_id'] + " size:" + size.to_s
end
return true
end