one-pro.js 8.1 KB

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