binance-spot.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. const BinanceKit = require('./binance-kit')
  2. const HttpKit = require('../../kit/http-kit')
  3. const TimeKit = require("../../kit/time-kit");
  4. const HTTPRequest = require('request')
  5. const assert = require("assert");
  6. const isDev = process.env.USER === 'skyfffire'
  7. const proxy = 'http://localhost:9080'
  8. class BinanceSpot {
  9. static BASE_URL = 'https://api.binance.com'
  10. static TRADE_TYPE = {
  11. MARKET: 'MARKET'
  12. }
  13. static TRADE_SIDE = {
  14. BUY: 'buy',
  15. SELL: 'sell'
  16. }
  17. static PRICE = {
  18. MARKET: -1
  19. }
  20. static NETWORK = {
  21. BSC: 'BSC'
  22. }
  23. static BASE_TOKEN = {
  24. BUSD: 'BUSD'
  25. }
  26. constructor(apiKey, secretKey) {
  27. this.apiKey = apiKey
  28. this.secretKey = secretKey
  29. }
  30. static async realPrice(symbol='BNBBUSD', side=BinanceSpot.TRADE_SIDE.BUY) {
  31. const url = `${BinanceSpot.BASE_URL}/api/v3/depth?symbol=${symbol}&limit=${5}`
  32. const { data: rst } = await HttpKit.get(url)
  33. if (!rst || !rst.bids || !rst.asks || !rst.bids[0] || !rst.asks[0]) {
  34. return 0
  35. }
  36. if (side === BinanceSpot.TRADE_SIDE.SELL) {
  37. return parseFloat(rst.bids[0][0])
  38. } else {
  39. return parseFloat(rst.asks[0][0])
  40. }
  41. }
  42. static async exchangeInfo(symbols=['BNBBUSD', 'BTCBUSD']) {
  43. const url = `${BinanceSpot.BASE_URL}/api/v3/exchangeInfo?symbols=${BinanceKit.buildExchangeInfoSymbols(symbols)}`
  44. const { data: rst } = await HttpKit.get(url)
  45. return rst
  46. }
  47. async accountInfo() {
  48. const url = `${BinanceSpot.BASE_URL}/api/v3/account`
  49. let timestamp = new Date().getTime()
  50. let data = {
  51. timestamp: timestamp
  52. }
  53. let signature = BinanceKit.createSignature(this.secretKey, data)
  54. let finalQueryURL = BinanceKit.toFinalQueryURL(url, data, signature)
  55. let headers = {
  56. 'X-MBX-APIKEY': this.apiKey
  57. }
  58. const { data: rst } = await HttpKit.get(finalQueryURL, headers)
  59. return rst
  60. }
  61. async withdraw(amount, coin=BinanceSpot.BASE_TOKEN.BUSD,
  62. address='0xCfB3Cb29EeAE464ABD44E35d53e12c555705e824', network=BinanceSpot.NETWORK.BSC) {
  63. const url = `${BinanceSpot.BASE_URL}/sapi/v1/capital/withdraw/apply`
  64. let timestamp = new Date().getTime()
  65. let data = {
  66. timestamp: timestamp,
  67. coin: coin,
  68. address: address,
  69. amount: amount,
  70. network: network
  71. }
  72. let signature = BinanceKit.createSignature(this.secretKey, data)
  73. let finalQueryURL = BinanceKit.toFinalQueryURL(url, data, signature)
  74. let headers = {
  75. 'X-MBX-APIKEY': this.apiKey
  76. }
  77. const { data: rst } = await HttpKit.post(finalQueryURL, data, headers)
  78. return rst
  79. }
  80. async takeOrder(symbol='BTCUSDT', price, side, quantity, quoteOrderQty, type=BinanceSpot.TRADE_TYPE.MARKET) {
  81. const url = `${BinanceSpot.BASE_URL}/api/v3/order`
  82. let timestamp = new Date().getTime()
  83. let data = {
  84. timestamp: timestamp,
  85. symbol: symbol,
  86. side: side,
  87. type: type,
  88. recvWindow: 60 * 1000
  89. }
  90. // 区分买卖情况应该分别传入什么数量
  91. if (side === BinanceSpot.TRADE_SIDE.BUY) data['quoteOrderQty'] = quoteOrderQty
  92. else if (side === BinanceSpot.TRADE_SIDE.SELL) data['quantity'] = quantity
  93. // MARKET状态不传入price
  94. if (type !== 'MARKET') data['price'] = price
  95. let signature = BinanceKit.createSignature(this.secretKey, data)
  96. let finalQueryURL = BinanceKit.toFinalQueryURL(url, data, signature)
  97. let headers = {
  98. 'X-MBX-APIKEY': this.apiKey
  99. }
  100. const params = {
  101. url: finalQueryURL,
  102. method: 'POST',
  103. headers: headers,
  104. proxy: isDev ? proxy : undefined
  105. }
  106. let finish = false
  107. let rst = undefined
  108. HTTPRequest(params, function (error, response) {
  109. // 请求成功的处理逻辑
  110. if (!error) {
  111. rst = JSON.parse(response.body)
  112. } else {
  113. rst = error
  114. }
  115. finish = true
  116. })
  117. while (!finish) {
  118. await TimeKit.sleep(10)
  119. }
  120. return rst
  121. }
  122. async buy(pair, price, quoteOrderQty, type=BinanceSpot.TRADE_TYPE.MARKET) {
  123. return await this.takeOrder(
  124. pair,
  125. price,
  126. BinanceSpot.TRADE_SIDE.BUY,
  127. 0,
  128. quoteOrderQty,
  129. type)
  130. }
  131. async sell(pair, price, quantity, type=BinanceSpot.TRADE_TYPE.MARKET) {
  132. return await this.takeOrder(
  133. pair,
  134. price,
  135. BinanceSpot.TRADE_SIDE.SELL,
  136. quantity,
  137. 0,
  138. type)
  139. }
  140. async buyMarket(pair, quoteOrderQty) {
  141. const buyRst = await this.buy(pair, -1, quoteOrderQty)
  142. assert.notEqual(buyRst.executedQty, undefined, JSON.stringify(buyRst))
  143. const cummulativeQuoteQty = parseFloat(buyRst.cummulativeQuoteQty)
  144. // 计算扣除手续费后的实际成交数量
  145. let executedQty = 0
  146. for (const fill of buyRst.fills) {
  147. executedQty += parseFloat(fill.qty)
  148. // 扣除支付的手续费
  149. if (fill.commissionAsset !== 'BNB') executedQty -= parseFloat(fill.commission)
  150. }
  151. return {
  152. cummulativeQuoteQty: cummulativeQuoteQty,
  153. executedQty: executedQty,
  154. avgPrice: cummulativeQuoteQty / executedQty
  155. }
  156. }
  157. async sellMarket(pair, quantity) {
  158. const sellRst = await this.sell(pair, -1, quantity)
  159. assert.notEqual(sellRst.executedQty, undefined, JSON.stringify(sellRst))
  160. let cummulativeQuoteQty = parseFloat(sellRst.cummulativeQuoteQty)
  161. // 计算扣除手续费后的实际成交数量
  162. let executedQty = 0
  163. for (const fill of sellRst.fills) {
  164. executedQty += parseFloat(fill.qty)
  165. // 扣除支付的手续费
  166. if (fill.commissionAsset !== 'BNB') cummulativeQuoteQty -= parseFloat(fill.commission)
  167. }
  168. return {
  169. cummulativeQuoteQty: cummulativeQuoteQty,
  170. executedQty: executedQty,
  171. avgPrice: cummulativeQuoteQty / executedQty
  172. }
  173. }
  174. }
  175. module.exports = BinanceSpot