price-monitor.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 TableKit = require('../../kit/table-kit')
  7. const PriceMonitorConfig = require('./config/price-monitor-config')
  8. const table = new TableKit(['pair', '1inch', 'binance', 'diff', 'percentage'])
  9. const showPrices = function(context, task) {
  10. const logger = task.logger
  11. const fileLogger = task.fileLogger
  12. const tokenMap = context.tokenMap
  13. table.printTitles()
  14. Object.keys(tokenMap).forEach((tokenHash) => {
  15. const token = tokenMap[tokenHash]
  16. const pair = token.exchange.pair
  17. const OneInchPrice = token.OneInchPrice ? token.OneInchPrice : NaN
  18. const BinancePrice = token.BinancePrice ? token.BinancePrice : NaN
  19. const DiffPrice = token.DiffPrice
  20. const percentage = NumKit.getSubFloat((DiffPrice / OneInchPrice) * 100, 2)
  21. // 价格非法的就不输出了
  22. // if ((() => {
  23. // return !OneInchPrice || !BinancePrice
  24. // })()) return
  25. const rows = [pair.toString(), OneInchPrice.toString(), BinancePrice.toString(), DiffPrice.toString(), percentage.toString()]
  26. // 需要输出到文件的打印逻辑
  27. const isLogToFile = (() => {
  28. return percentage > PriceMonitorConfig.percentageLimit
  29. })()
  30. table.showLine(rows, isLogToFile ? fileLogger : undefined)
  31. })
  32. table.printEndLine(logger)
  33. }
  34. const onTickFun = async function() {
  35. const task = this
  36. const context = task.context
  37. const tokenMap = context.tokenMap
  38. const tokenContractAddressList = Object.keys(tokenMap)
  39. // 搜集所有价格数据
  40. for (const tokenHash of tokenContractAddressList) {
  41. const toToken = tokenMap[tokenHash]
  42. const priceTick = toToken.exchange.priceTick
  43. const fromIerc20Token = Config.baseIerc20Token
  44. const amount = Config.baseTokenAmount
  45. const OneInchPrice = NumKit.getSubFloat(await OneInch.price(fromIerc20Token.contract, tokenHash, amount), priceTick)
  46. const BinancePrice = NumKit.getSubFloat(await BinanceSpot.realPrice(toToken.exchange.pair), priceTick)
  47. toToken.OneInchPrice = OneInchPrice
  48. toToken.BinancePrice = BinancePrice
  49. toToken.DiffPrice = BinancePrice - OneInchPrice
  50. if ((() => {
  51. return Math.abs(toToken.DiffPrice) < Math.pow(10, -priceTick)
  52. })()) {
  53. toToken.DiffPrice = 0
  54. } {
  55. toToken.DiffPrice = NumKit.getSubFloat(toToken.DiffPrice, priceTick)
  56. }
  57. }
  58. // 绘制帧
  59. showPrices(context, task)
  60. }
  61. const priceMonitor = new OneTask('PriceMonitor',5 * 1000, OneTask.baseInit, onTickFun)
  62. priceMonitor.Start()