one-pro.js 7.3 KB

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