one-pro.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. const OneTask = require('../libs/one-task')
  2. const OneInch = require('../libs/web3/1inch')
  3. const BinanceSpot = require('../libs/binance/binance-spot')
  4. const Config = require('../config/config')
  5. const NumKit = require('../kit/num-kit')
  6. const TimeKit = require('../kit/time-kit')
  7. const TableKit = require('../kit/table-kit')
  8. const BinanceKit = require("../libs/binance/binance-kit");
  9. const orderHandler = async function(context, task) {
  10. const fileLogger = task.fileLogger
  11. const tokenMap = context.tokenMap
  12. const binanceSpot = context.binanceSpot
  13. const accountAssetMap = context.accountAssetMap
  14. // 逐对处理交易信息
  15. for (const tokenHash of Object.keys(tokenMap)) {
  16. const token = tokenMap[tokenHash]
  17. const pair = token.exchange.pair
  18. // 价格非法判定
  19. if (!token.BinancePrice || !token.OneInchPrice) continue;
  20. // 卖出逻辑判定
  21. if (token.orderPrice) {
  22. if (token.BinancePrice > token.orderPrice) {
  23. // 止盈逻辑
  24. const isStopWin = token.BinancePrice > (token.orderPrice * (100 + Config.stopWinPercentage) / 100)
  25. if (isStopWin) {
  26. const sellRst = await binanceSpot.sell(pair, -1, token.orderAmount)
  27. if (sellRst.executedQty) {
  28. const cummulativeQuoteQty = NumKit.getSubFloat(sellRst.cummulativeQuoteQty, 6)
  29. const executedQty = NumKit.getSubFloat(sellRst.executedQty, token.exchange.lotSize)
  30. const price = cummulativeQuoteQty / executedQty
  31. fileLogger.info(`[止盈]${pair}, price: ${token.orderPrice}->${price}, amount: ${token.orderAmount}.`)
  32. token.orderPrice = undefined
  33. token.nextHandleTime = new Date().getTime() + Config.stopWinHandleSpaceHours * (60 * 60 * 1000)
  34. fileLogger.info(`[订单]${pair}, volume:${cummulativeQuoteQty}, 买入${executedQty}, 均价${token.orderPrice}.`)
  35. } else {
  36. token.orderPrice = undefined
  37. token.nextHandleTime = new Date().getTime() + Config.stopWinHandleSpaceHours * (60 * 60 * 1000)
  38. fileLogger.error(`[止盈失败]${pair}, ${JSON.stringify(sellRst)}`)
  39. }
  40. }
  41. } else {
  42. // 止损逻辑
  43. const isStopLoss = token.BinancePrice < (token.orderPrice * (100 - Config.stopLossPercentage) / 100)
  44. if (isStopLoss) {
  45. const sellRst = await binanceSpot.sell(pair, -1, token.orderAmount)
  46. if (sellRst.executedQty) {
  47. const cummulativeQuoteQty = NumKit.getSubFloat(sellRst.cummulativeQuoteQty, 6)
  48. const executedQty = NumKit.getSubFloat(sellRst.executedQty, token.exchange.lotSize)
  49. const price = cummulativeQuoteQty / executedQty
  50. fileLogger.info(`[止损]${pair}, price: ${token.orderPrice}->${price}, amount: ${token.orderAmount}.`)
  51. token.orderPrice = undefined
  52. token.nextHandleTime = new Date().getTime() + Config.stopLossHandleSpaceHours * (60 * 60 * 1000)
  53. fileLogger.info(`[订单]${pair}, volume:${cummulativeQuoteQty}, 买入${executedQty}, 均价${token.orderPrice}.`)
  54. } else {
  55. token.orderPrice = undefined
  56. token.nextHandleTime = new Date().getTime() + Config.stopLossHandleSpaceHours * (60 * 60 * 1000)
  57. fileLogger.error(`[止损失败]${pair}, ${JSON.stringify(sellRst)}`)
  58. }
  59. }
  60. }
  61. } else if (token.isLong) {
  62. // 1. 获取base资产数量
  63. const baseAssetAmount = accountAssetMap[Config.baseIerc20Token.symbol]
  64. // 判断余额是否够下单
  65. if (Config.baseTokenAmount > baseAssetAmount) {
  66. fileLogger.info(`[下单失败]${pair}, volume: ${Config.baseTokenAmount}, asset: ${baseAssetAmount}.`)
  67. token.nextHandleTime = new Date().getTime() + Config.stopLossHandleSpaceHours * (60 * 60 * 1000)
  68. continue;
  69. }
  70. // 2. 下单获取成交数量以及平均价格
  71. const buyRst = await binanceSpot.buy(pair, -1, Config.baseTokenAmount)
  72. if (buyRst.executedQty) {
  73. const cummulativeQuoteQty = NumKit.getSubFloat(buyRst.cummulativeQuoteQty, 6)
  74. const executedQty = NumKit.getSubFloat(buyRst.executedQty, token.exchange.lotSize)
  75. token.orderAmount = executedQty
  76. token.orderPrice = cummulativeQuoteQty / executedQty
  77. fileLogger.info(`[订单]${pair}, volume:${cummulativeQuoteQty}, 买入${executedQty}, 均价${token.orderPrice}.`)
  78. accountAssetMap[Config.baseIerc20Token.symbol] = accountAssetMap[Config.baseIerc20Token.symbol] - cummulativeQuoteQty
  79. } else {
  80. fileLogger.error(`[下单失败]${JSON.stringify(buyRst)}`)
  81. }
  82. }
  83. }
  84. }
  85. const table = new TableKit(['pair', '1inch', 'binance', 'order price', 'profit(%)', 'next time'], 20)
  86. const showInfo = function(context, task) {
  87. const logger = task.logger
  88. const tokenMap = context.tokenMap
  89. table.printTitles()
  90. Object.keys(tokenMap).forEach((tokenHash) => {
  91. const token = tokenMap[tokenHash]
  92. const pair = token.exchange.pair
  93. const OneInchPrice = token.OneInchPrice ? token.OneInchPrice : NaN
  94. const BinancePrice = token.BinancePrice ? token.BinancePrice : NaN
  95. const DiffPrice = token.DiffPrice
  96. const percentage = NumKit.getSubFloat((DiffPrice / OneInchPrice) * 100, 2)
  97. const orderPrice = token.orderPrice ? token.orderPrice : ''
  98. const orderPercentage = orderPrice ? NumKit.getSubFloat(((BinancePrice - orderPrice) / orderPrice) * 100, 2) : ''
  99. const nextTimeStr = token.nextHandleTime ? TimeKit.getTimeByMillisecond(token.nextHandleTime) : ''
  100. // 价格非法判定
  101. const priceCondition = (() => {
  102. return OneInchPrice && BinancePrice
  103. })()
  104. const rows = [pair.toString(), OneInchPrice.toString(), BinancePrice.toString(),
  105. orderPrice.toString(), orderPercentage.toString(), nextTimeStr]
  106. // 识别到在拉盘
  107. token.isLong = (() => {
  108. const percentageCondition = percentage > Config.percentageLimit
  109. const isNoPrevHandleTime = !token.nextHandleTime
  110. const isTimeCover = new Date().getTime() > token.nextHandleTime
  111. const timeCondition = isNoPrevHandleTime || isTimeCover
  112. return priceCondition && percentageCondition && timeCondition
  113. })()
  114. // 打印表格
  115. table.showLine(rows, undefined)
  116. })
  117. table.printEndLine(logger)
  118. }
  119. const priceHandler = async function(context, task) {
  120. const tokenMap = context.tokenMap
  121. const tokenContractAddressList = Object.keys(tokenMap)
  122. for (const tokenHash of tokenContractAddressList) {
  123. const toToken = tokenMap[tokenHash]
  124. const priceTick = toToken.exchange.priceTick
  125. const fromIerc20Token = Config.baseIerc20Token
  126. const amount = Config.baseTokenAmount
  127. const OneInchPrice = NumKit.getSubFloat(await OneInch.price(fromIerc20Token.contract, tokenHash, amount), priceTick)
  128. const BinancePrice = NumKit.getSubFloat(await BinanceSpot.realPrice(toToken.exchange.pair), priceTick)
  129. toToken.OneInchPrice = OneInchPrice
  130. toToken.BinancePrice = BinancePrice
  131. toToken.DiffPrice = BinancePrice - OneInchPrice
  132. if ((() => {
  133. return Math.abs(toToken.DiffPrice) < Math.pow(10, -priceTick)
  134. })()) {
  135. toToken.DiffPrice = 0
  136. } {
  137. toToken.DiffPrice = NumKit.getSubFloat(toToken.DiffPrice, priceTick)
  138. }
  139. }
  140. }
  141. const accountHandler = async function(context, task) {
  142. const accountInfoRst = await context.binanceSpot.accountInfo()
  143. context.accountAssetMap = BinanceKit.parseBalancesToAccountAssetMap(accountInfoRst.balances)
  144. }
  145. const onTickFun = async function() {
  146. const task = this
  147. const context = task.context
  148. // 搜集所有价格数据
  149. await priceHandler(context, task)
  150. // 获取账户数据
  151. await accountHandler(context, task)
  152. // 展示关键信息
  153. showInfo(context, task)
  154. // 交易、订单处理
  155. await orderHandler(context, task)
  156. }
  157. const onePro = new OneTask('OnePro', Config.delay, OneTask.baseInit, onTickFun)
  158. onePro.Start()