forked from binance-exchange/binance-api-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.js
255 lines (220 loc) · 6.98 KB
/
http.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import crypto from 'crypto'
import zip from 'lodash.zipobject'
import 'isomorphic-fetch'
const BASE = 'https://api.binance.com'
const defaultGetTime = () => Date.now()
/**
* Build query string for uri encoded url based on json object
*/
const makeQueryString = q =>
q
? `?${Object.keys(q)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(q[k])}`)
.join('&')}`
: ''
/**
* Finalize API response
*/
const sendResult = call =>
call.then(res => Promise.all([res, res.json()])).then(([res, json]) => {
if (!res.ok) {
const error = new Error(json.msg || `${res.status} ${res.statusText}`)
error.code = json.code
throw error
}
return json
})
/**
* Util to validate existence of required parameter(s)
*/
const checkParams = (name, payload, requires = []) => {
if (!payload) {
throw new Error('You need to pass a payload object.')
}
requires.forEach(r => {
if (!payload[r] && isNaN(payload[r])) {
throw new Error(`Method ${name} requires ${r} parameter.`)
}
})
return true
}
/**
* Make public calls against the api
*
* @param {string} path Endpoint path
* @param {object} data The payload to be sent
* @param {string} method HTTB VERB, GET by default
* @param {object} headers
* @returns {object} The api response
*/
const publicCall = (path, data, method = 'GET', headers = {}) =>
sendResult(
fetch(`${BASE}/api${path}${makeQueryString(data)}`, {
method,
json: true,
headers,
}),
)
/**
* Factory method for partial private calls against the api
*
* @param {string} path Endpoint path
* @param {object} data The payload to be sent
* @param {string} method HTTB VERB, GET by default
* @returns {object} The api response
*/
const keyCall = ({ apiKey }) => (path, data, method = 'GET') => {
if (!apiKey) {
throw new Error('You need to pass an API key to make this call.')
}
return publicCall(path, data, method, {
'X-MBX-APIKEY': apiKey,
})
}
/**
* Factory method for private calls against the api
*
* @param {string} path Endpoint path
* @param {object} data The payload to be sent
* @param {string} method HTTB VERB, GET by default
* @param {object} headers
* @returns {object} The api response
*/
const privateCall = ({ apiKey, apiSecret, getTime = defaultGetTime }) => (
path,
data = {},
method = 'GET',
noData,
noExtra,
) => {
if (!apiKey || !apiSecret) {
throw new Error('You need to pass an API key and secret to make authenticated calls.')
}
return (data && data.useServerTime
? publicCall('/v1/time').then(r => r.serverTime)
: Promise.resolve(getTime())
).then(timestamp => {
if (data) {
delete data.useServerTime
}
const signature = crypto
.createHmac('sha256', apiSecret)
.update(makeQueryString({ ...data, timestamp }).substr(1))
.digest('hex')
const newData = noExtra ? data : { ...data, timestamp, signature }
return sendResult(
fetch(
`${BASE}${path.includes('/wapi') ? '' : '/api'}${path}${noData
? ''
: makeQueryString(newData)}`,
{
method,
headers: { 'X-MBX-APIKEY': apiKey },
json: true,
},
),
)
})
}
export const candleFields = [
'openTime',
'open',
'high',
'low',
'close',
'volume',
'closeTime',
'quoteVolume',
'trades',
'baseAssetVolume',
'quoteAssetVolume',
]
/**
* Get candles for a specific pair and interval and convert response
* to a user friendly collection.
*/
const candles = payload =>
checkParams('candles', payload, ['symbol']) &&
publicCall('/v1/klines', { interval: '5m', ...payload }).then(candles =>
candles.map(candle => zip(candleFields, candle)),
)
/**
* Create a new order wrapper for market order simplicity
*/
const order = (pCall, payload = {}, url) => {
const newPayload =
['LIMIT', 'STOP_LOSS_LIMIT', 'TAKE_PROFIT_LIMIT'].includes(payload.type) || !payload.type
? { timeInForce: 'GTC', ...payload }
: payload
return (
checkParams('order', newPayload, ['symbol', 'side', 'quantity']) &&
pCall(url, { type: 'LIMIT', ...newPayload }, 'POST')
)
}
/**
* Zip asks and bids reponse from order book
*/
const book = payload =>
checkParams('book', payload, ['symbol']) &&
publicCall('/v1/depth', payload).then(({ lastUpdateId, asks, bids }) => ({
lastUpdateId,
asks: asks.map(a => zip(['price', 'quantity'], a)),
bids: bids.map(b => zip(['price', 'quantity'], b)),
}))
const aggTrades = payload =>
checkParams('aggTrades', payload, ['symbol']) &&
publicCall('/v1/aggTrades', payload).then(trades =>
trades.map(trade => ({
aggId: trade.a,
price: trade.p,
quantity: trade.q,
firstId: trade.f,
lastId: trade.l,
timestamp: trade.T,
isBuyerMaker: trade.m,
wasBestPrice: trade.M,
})),
)
export default opts => {
const pCall = privateCall(opts)
const kCall = keyCall(opts)
return {
ping: () => publicCall('/v1/ping').then(() => true),
time: () => publicCall('/v1/time').then(r => r.serverTime),
exchangeInfo: () => publicCall('/v1/exchangeInfo'),
book,
aggTrades,
candles,
trades: payload =>
checkParams('trades', payload, ['symbol']) && publicCall('/v1/trades', payload),
tradesHistory: payload =>
checkParams('tradesHitory', payload, ['symbol']) && kCall('/v1/historicalTrades', payload),
dailyStats: payload => publicCall('/v1/ticker/24hr', payload),
prices: () =>
publicCall('/v1/ticker/allPrices').then(r =>
r.reduce((out, cur) => ((out[cur.symbol] = cur.price), out), {}),
),
avgPrice: payload => publicCall('/v3/avgPrice', payload),
allBookTickers: () =>
publicCall('/v1/ticker/allBookTickers').then(r =>
r.reduce((out, cur) => ((out[cur.symbol] = cur), out), {}),
),
order: payload => order(pCall, payload, '/v3/order'),
orderTest: payload => order(pCall, payload, '/v3/order/test'),
getOrder: payload => pCall('/v3/order', payload),
cancelOrder: payload => pCall('/v3/order', payload, 'DELETE'),
openOrders: payload => pCall('/v3/openOrders', payload),
allOrders: payload => pCall('/v3/allOrders', payload),
accountInfo: payload => pCall('/v3/account', payload),
myTrades: payload => pCall('/v3/myTrades', payload),
withdraw: payload => pCall('/wapi/v3/withdraw.html', payload, 'POST'),
withdrawHistory: payload => pCall('/wapi/v3/withdrawHistory.html', payload),
depositHistory: payload => pCall('/wapi/v3/depositHistory.html', payload),
depositAddress: payload => pCall('/wapi/v3/depositAddress.html', payload),
tradeFee: payload => pCall('/wapi/v3/tradeFee.html', payload).then(res => res.tradeFee),
assetDetail: payload => pCall('/wapi/v3/assetDetail.html', payload),
getDataStream: () => pCall('/v1/userDataStream', null, 'POST', true),
keepDataStream: payload => pCall('/v1/userDataStream', payload, 'PUT', false, true),
closeDataStream: payload => pCall('/v1/userDataStream', payload, 'DELETE', false, true),
}
}