import { hmac , nonce , safeQueryStringStringify } from '../util' ; import WebClient from '../WebClient' ; import { SendChildOrderRequest , SendChildOrderResponse , CancelChildOrderRequest , CancelChildOrderResponse , ChildOrdersParam , ChildOrdersResponse , ExecutionsResponse , ExecutionsParam , Execution , BalanceResponse , BoardResponse , ChildOrder , Balance } from './types' ; export default class BrokerApi { private readonly baseUrl = 'https://api.bitflyer.jp' ; private readonly webClient : WebClient = new WebClient ( this . baseUrl ) ; constructor ( private readonly key , private readonly secret ) { } async sendChildOrder ( request ) { const path = '/v1/me/sendchildorder' ; return new SendChildOrderResponse ( await this . post < SendChildOrderResponse , SendChildOrderRequest > ( path , request ) ) ; } async cancelChildOrder ( request ) { const path = '/v1/me/cancelchildorder' ; return await this . post < CancelChildOrderResponse , CancelChildOrderRequest > ( path , request ) ; } async getChildOrders ( param ) { const path = '/v1/me/getchildorders' ; const response = await this . get < ChildOrdersResponse , ChildOrdersParam > ( path , param ) ; return response . map ( x => new ChildOrder ( x ) ) ; } async getExecutions ( param ) { const path = '/v1/me/getexecutions' ; const response = await this . get < ExecutionsResponse , ExecutionsParam > ( path , param ) ; return response . map ( x => new Execution ( x ) ) ; } async getBalance ( ) { const path = '/v1/me/getbalance' ; const response = await this . get < BalanceResponse > ( path ) ; return response . map ( x => new Balance ( x ) ) ; } async getBoard ( ) { const path = '/v1/board' ; return new BoardResponse ( await this . webClient . fetch < BoardResponse > ( path , undefined , false ) ) ; } private async call < R > ( path , method , body = '' ) { const n = nonce ( ) ; const message = n + method + path + body ; const sign = hmac ( this . secret , message ) ; const headers = { 'Content-Type' : 'application/json' , 'ACCESS-KEY' : this . key , 'ACCESS-TIMESTAMP' : n , 'ACCESS-SIGN' : sign } ; const init = { method , headers , body } ; return await this . webClient . fetch < R > ( path , init ) ; } private async post < R , T > ( path , requestBody ) { const method = 'POST' ; const body = JSON . stringify ( requestBody ) ; return await this . call < R > ( path , method , body ) ; } private async get < R , T = never > ( path , requestParam ? ) { const method = 'GET' ; let pathWithParam = path ; if ( requestParam ) { const param = safeQueryStringStringify ( requestParam ) ; pathWithParam += `?${ param }` ; } return await this . call < R > ( pathWithParam , method ) ; } }