one-pro.js 8.4 KB

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