one-pro.js 7.5 KB

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