This repository has been archived by the owner on Oct 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
binance.js
389 lines (356 loc) · 9.64 KB
/
binance.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
const process = require('process')
const fs = require('fs')
const Binance = require('node-binance-api')
const { round } = require('mathjs')
const config = require('./config')
const { sleep, log, dateFormat, tries, roundOrderPrice } = require('./utils')
const { knex, createTableIF } = require('./db')
Object.defineProperty(global, '__stack', {
get: function () {
var orig = Error.prepareStackTrace
Error.prepareStackTrace = function (_, stack) {
return stack
}
var err = new Error()
Error.captureStackTrace(err, arguments.callee)
var stack = err.stack
Error.prepareStackTrace = orig
return stack
},
})
Object.defineProperty(global, '__line', {
get: function () {
return __stack[1].getLineNumber()
},
})
Object.defineProperty(global, '__function', {
get: function () {
return __stack[1].getFunctionName()
},
})
const binance = new Binance().options({
APIKEY: config.api_key,
APISECRET: config.api_secret,
})
let weight = 0
const flag = false
function resetWeight() {
log(`${__function}: ${weight}`, flag)
weight = 0
}
function getWeight() {
return weight
}
/**
* 当前账户信息
* @document ./doc/futuresAccount.js
* @returns
*/
async function getAccount() {
const account = await binance.futuresAccount()
weight += 5
log(`${__function}: ${weight}`, flag)
// const { availableBalance } = account // 可用余额
return account
}
/**
* 当前账户Balance
* @returns
*/
async function getBalance() {
const result = await binance.futuresBalance()
weight += 5
log(`${__function}: ${weight}`, flag)
return result
}
/**
* @document ./doc/futuresAccount.js
* @returns
*/
async function getPosition() {
const result = await binance.futuresPositionRisk()
weight += 5
log(`${__function}: ${weight}`, flag)
return result
}
/**
* 当前所有币种价格
* @document ./doc/futuresPrices.js
* @returns
*/
async function getPrices() {
const result = await binance.futuresPrices()
return result
}
/**
* 当前币的挂单价格
*/
async function getPrice(symbol, limit = 50) {
const result = await binance.futuresDepth(symbol, { limit })
function avg(data) {
let num = 0
let sum = 0
data.map(item => {
sum += item[0] * item[1]
num += Number(item[1])
})
return num > 0 ? sum / num : 0
}
return {
buyPrice: roundOrderPrice(avg(result.bids), symbol), // 平均买单价格(低)
sellPrice: roundOrderPrice(avg(result.asks), symbol), // 平均卖单价格(高)
}
}
/**
* ma5 MA(5)=(收盘价1+收盘价2+收盘价3+收盘价4+收盘价5)/5
* 获取 kline 的前n个平均值
* @param string symbol
* @param string type
* @param number keys
*/
async function getKlineAvg(symbol, type, keys) {
const limit = Math.max(...keys) + 1
let result = await binance.futuresCandles(symbol, type, { limit })
result = result.map(item => Number(item[4])).reverse() // 获取最新到以前的收盘价
function avg(arr, key) {
return arr.slice(0, key).reduce((carry, item) => carry + item, 0) / key
}
return keys.map(key => avg(result, key))
}
/**
* 获取 kline 收盘价
* @param {*} symbol
* @param {*} type
*/
async function getKline(symbol, type, limit) {
let result = await binance.futuresCandles(symbol, type, { limit })
result = result.map(item => Number(item[4])).reverse() // 获取最新到以前的收盘价
return result
}
/**
* 获取 kline 原始数据
* @param {*} symbol
* @param {*} type
* @result
* @doc file://./doc/kline.js
*/
async function getKlineOrigin(symbol, type, limit) {
let result = await binance.futuresCandles(symbol, type, { limit })
result = result.reverse()
return result
}
/**
* 限价买入
* @param string symbol
* @param Number quantity
* @param number price
* @param {} otherOptions https://binance-docs.github.io/apidocs/futures/cn/#trade-3
*/
async function buyLimit(symbol, quantity, price, otherOptions) {
const result = await binance.futuresBuy(symbol, quantity, price, otherOptions) // 限定价格买入
weight += 1
log(`${__function}: ${weight}`, flag)
return result
}
/**
* 限价卖出
* @param string symbol
* @param Number quantity
* @param number price
* @param {} otherOptions https://binance-docs.github.io/apidocs/futures/cn/#trade-3
*/
async function sellLimit(symbol, quantity, price, otherOptions) {
const result = await binance.futuresSell(symbol, quantity, price, otherOptions) // 限定价格卖出
weight += 1
log(`${__function}: ${weight}`, flag)
return result
}
/**
* 市价买入
* @param string symbol
* @param Number quantity
* @param number price
* @param {} otherOptions https://binance-docs.github.io/apidocs/futures/cn/#trade-3
*/
async function buyMarket(symbol, quantity, otherOptions) {
const result = await binance.futuresMarketBuy(symbol, quantity, otherOptions) // 市价买入
weight += 1
log(`${__function}: ${weight}`, flag)
return result
}
/**
* 市价卖出
* @param string symbol
* @param Number quantity
* @param number price
* @param {} otherOptions https://binance-docs.github.io/apidocs/futures/cn/#trade-3
*/
async function sellMarket(symbol, quantity, otherOptions) {
const result = await binance.futuresMarketSell(symbol, quantity, otherOptions) // 市价卖出
weight += 1
log(`${__function}: ${weight}`, flag)
return result
}
/**
* 撤销订单
* @param string symbol
* @param Number orderId
* @param {} otherOptions https://binance-docs.github.io/apidocs/futures/cn/#trade-6
*/
async function cancelOrder(symbol, orderId) {
weight += 1
log(`${__function}: ${weight}`, flag)
if (orderId) {
const result = await binance.futuresCancel(symbol, { orderId })
return result
}
const result = await binance.futuresCancelAll(symbol)
return result
}
/**
* 订单状态
* @param string symbol
* @param Number orderId
* @param {} otherOptions https://binance-docs.github.io/apidocs/futures/cn/#trade-6
*/
async function orderStatus(symbol, orderId) {
const result = await binance.futuresOrderStatus(symbol, { orderId })
return result
}
/**
* 交易深度
* @param string symbol
* @param Number orderId
* @param {} otherOptions https://binance-docs.github.io/apidocs/futures/cn/#trade-6
*/
async function depth(symbol, limit = 50) {
weight += 2
const result = await binance.futuresDepth(symbol, { limit })
log(`${__function}: ${weight}`, flag)
return result
}
/**
* 交易合约倍数
* @param string symbol
* @param Number 1-125
* @doc https://binance-docs.github.io/apidocs/futures/cn/#trade-10
*/
async function leverage(symbol, number) {
weight += 1
const result = await binance.futuresLeverage(symbol, number)
log(`${__function}: ${weight}`, flag)
return result
}
/**
* 合约模式 全仓与 逐仓
* @param string symbol
* @param string marginType ENUM YES 保证金模式 ISOLATED(逐仓), CROSSED(全仓)
* @doc https://binance-docs.github.io/apidocs/futures/cn/#trade-10
*/
async function marginType(symbol, marginType = 'ISOLATED') {
weight += 1
const result = await binance.futuresMarginType(symbol, marginType)
log(`${__function}: ${weight}`, flag)
return result
}
/**
* 获取历史订单
* @param string symbol
* @doc https://binance-docs.github.io/apidocs/futures/cn/#user_data-7
*/
async function getOrders(symbol = null, params = {}) {
const result = await binance.futuresAllOrders(symbol, params)
return result
}
/**
* 获取当前挂单
* @param string symbol
* @doc https://binance-docs.github.io/apidocs/futures/cn/#user_data-4
*/
async function getOpenOrder(symbol, params = {}) {
if (symbol) {
weight += 1
log(`${__function}: ${weight}`, flag)
const result = await binance.futuresOpenOrders(symbol, params)
return result
}
weight += 40
log(`${__function}: ${weight}`, flag)
const result = await binance.futuresOpenOrders()
return result
}
/**
* 获取交易信息
* @param string symbol
* @doc https://binance-docs.github.io/apidocs/futures/cn/#user_data-4
*/
async function getExchangeInfo() {
const result = await binance.futuresExchangeInfo()
return result
}
/**
* 账户成交历史
* @param string symbol
* @param {startTime: number(13), endTime: number(13), limit: number} // startTime 和 endTime 的最大间隔为7天, limit 返回的结果集数量 默认值:500 最大值:1000
* @doc https://binance-docs.github.io/apidocs/futures/cn/#user_data-7
* @example doc/userTrades.js
*/
async function getTrades(symbol, params = {}) {
const result = await binance.futuresUserTrades(symbol, params)
return result
}
let lock = false
if (config.websocket) {
const dbFile = './data/data.db'
if (!fs.existsSync(dbFile)) {
fs.copyFileSync(dbFile + '.example', dbFile)
}
/**
* 更新数据库的币种数据信息 websocket 推送
*/
binance.futuresTickerStream(false, async prevDay => {
if (!lock) {
lock = true
for (let obj of prevDay) {
await tries(async () => {
await knex('symbols').where('symbol', obj.symbol).update({
percentChange: obj.percentChange,
close: obj.close,
open: obj.open,
low: obj.low,
updateTime: obj.eventTime,
lastClose: knex.raw('close'), // 上一次的收盘价
lastUpdateTime: knex.raw('updateTime'), // 上一次更新时间
})
})
log(`${obj.symbol}:${obj.percentChange}`, false)
}
lock = false
}
})
}
module.exports = {
resetWeight,
getWeight,
getAccount,
getBalance,
getPosition,
// getPrices,
getPrice,
getKlineAvg,
getKline,
getKlineOrigin,
buyLimit,
sellLimit,
buyMarket,
sellMarket,
cancelOrder,
// orderStatus,
depth,
leverage,
marginType,
getOrders,
getOpenOrder,
// getExchangeInfo,
// getTrades,
}