BIZ

Node.jsでbitFlyerAPIを使う

APIのドキュメントはここにあります。

サンプル

const axios = require('axios')
const config = require('./bitflyer.config')
const baseUrl = 'https://api.bitflyer.com'
const crypto = require('crypto')
function request(method, path, data) {
return new Promise((resolve, reject) => {
const [timestamp, body, sign] = createSign(method, path, data)
axios({
url: baseUrl + path,
method: method,
data: body,
headers: {
'ACCESS-KEY': config.key,
'ACCESS-TIMESTAMP': timestamp,
'ACCESS-SIGN': sign,
'Content-Type': 'application/json'
}
})
.then(res => resolve(res))
.catch(err => reject(err))
})
}
function createSign(method, path, data) {
const timestamp = Date.now().toString()
const body = (method === 'POST') ? JSON.stringify(data) : ''
const text = timestamp + method + path + body
const sign = crypto.createHmac('sha256', config.secret).update(text).digest('hex')
return [timestamp, body, sign]
}
exports.markets = () => {
return new Promise((resolve, reject) => {
const path = '/v1/markets'
axios.get(baseUrl + path)
.then(res => resolve(res.data))
.catch(err => reject(err))
})
}
exports.collateral = () => {
return new Promise((resolve, reject) => {
const path = '/v1/me/getcollateral'
request('GET', path, null)
.then(res => resolve(res.data))
.catch(err => reject(err))
})
}
exports.cancelAll = (product_code) => {
return new Promise((resolve, reject) => {
const path = '/v1/me/cancelallchildorders'
const data = { "product_code": product_code }
request('POST', path, data)
.then(res => resolve(res.data))
.catch(err => reject(err))
})
}

使い方

const bitflyer = require('./bitflyer')
bitflyer.markets()
.then(data => console.log(data))
.catch(err => console.log(err.message))
bitflyer.collateral()
.then(data => console.log(data.collateral))
.catch(err => console.log(err.message))
bitflyer.cancelAll('BTC_JPY')
.then(data => console.log('Canceled'))
.catch(err => console.log(err.message))

実行結果

[ { product_code: 'BTC_JPY' },
{ product_code: 'FX_BTC_JPY' },
{ product_code: 'ETH_BTC' },
{ product_code: 'BCH_BTC' },
{ product_code: 'BTCJPY28SEP2018', alias: 'BTCJPY_MAT2WK' },
{ product_code: 'BTCJPY21SEP2018', alias: 'BTCJPY_MAT1WK' },
{ product_code: 'BTCJPY28DEC2018', alias: 'BTCJPY_MAT3M' } ]
500
Canceled