const OneTask = require('../libs/one-task') const OneInch = require('../libs/web3/1inch') const BinanceSpot = require("../libs/binance/binance-spot"); const BinanceKit = require("../libs/binance/binance-kit"); const NumKit = require('../kit/num-kit') const TimeKit = require('../kit/time-kit') const TableKit = require('../kit/table-kit') const Context = require("../libs/context") const assert = require("assert"); const holdingHandler = async function(context, task, token, pair) { const config = context.config const fileLogger = task.fileLogger const binanceSpot = context.binanceSpot const accountAssetMap = context.accountAssetMap // 这两个逻辑只有可能满足一个 let isStopWin = token.BinancePrice > (token.orderPrice * (100 + config.stopWinPercentage) / 100) let isStopLoss = token.BinancePrice < (token.orderPrice * (100 - config.stopLossPercentage) / 100) assert.notEqual(isStopWin && isStopLoss, true, '止盈止损逻辑错误,请认真检查。') if (isStopWin || isStopLoss) { const orderPrice = token.orderPrice const orderAmount = token.orderAmount token.orderPrice = undefined token.orderAmount = undefined token.nextHandleTime = new Date().getTime() + config.stopLossHandleSpaceHours * (60 * 60 * 1000) try { const sellMarketRst = await binanceSpot.sellMarket(pair, orderAmount) const price = NumKit.getSubFloat(sellMarketRst.avgPrice, token.exchange.priceTick) const cummulativeQuoteQty = NumKit.getSubFloat(sellMarketRst.cummulativeQuoteQty, 6) // 交易数据持久化 await token.save() fileLogger.info(`[${isStopWin ? '盈+' : '损-'}]${pair}, ` .concat(`成交额${cummulativeQuoteQty}, 均价${orderPrice}->${price}, 卖出${orderAmount}个.`) ) } catch (e) { fileLogger.error(`[止${isStopWin ? '盈' : '损'}失败]${pair}, ${e}`) } } } const noHoldingHandler = async function(context, task, token, pair) { const config = context.config const fileLogger = task.fileLogger const binanceSpot = context.binanceSpot const accountAssetMap = context.accountAssetMap // 1. 获取base资产数量 const baseAssetAmount = accountAssetMap[config.baseIerc20Token.symbol] // 2. 判断余额是否够下单 if (config.baseTokenAmount > baseAssetAmount) { fileLogger.info(`[余额不足]${pair}, 需要: ${config.baseTokenAmount}, 剩余: ${baseAssetAmount}.`) token.nextHandleTime = new Date().getTime() + config.stopLossHandleSpaceHours * (60 * 60 * 1000) return } // 3. 下单获取成交信息 try { const buyMarketRst = await binanceSpot.buyMarket(pair, config.baseTokenAmount) token.cummulativeQuoteQty = NumKit.getSubFloat(buyMarketRst.cummulativeQuoteQty, 6) token.orderAmount = NumKit.getSubFloat(buyMarketRst.executedQty, token.exchange.lotSize) token.orderPrice = NumKit.getSubFloat(buyMarketRst.avgPrice, token.exchange.priceTick) // 关键数据持久化 await token.save() fileLogger.info(`[单]${pair}, 成交额${token.cummulativeQuoteQty}, 买入${token.orderAmount}个, 均价${token.orderPrice}.`) accountAssetMap[config.baseIerc20Token.symbol] -= token.cummulativeQuoteQty } catch (e) { fileLogger.error(`[下单失败]${pair}, ${e}`) } } const tradeLogic = async function(context, task) { const tokenMap = context.tokenMap // 逐对处理交易信息 for (const tokenHash of Object.keys(tokenMap)) { const token = tokenMap[tokenHash] const pair = token.exchange.pair // 价格非法判定 if (!token.BinancePrice || !token.OneInchPrice) continue; // 更新token的实际余额 // token.orderAmount = NumKit.getSubFloat(accountAssetMap[token.exchange.symbol], token.exchange.lotSize) // 卖出逻辑判定 if (token.orderPrice && token.orderAmount > Math.pow(10, -token.exchange.lotSize)) { await holdingHandler(context, task, token, pair) } else if (token.isLong) { await noHoldingHandler(context, task, token, pair) } } } const table = new TableKit(['pair', '1inch', 'binance', 'order price', 'profit(%)', 'next time'], 20) const showInfo = function(context, task) { const config = context.config const logger = task.logger const tokenMap = context.tokenMap const accountAssetMap = context.accountAssetMap table.printTitles() Object.keys(tokenMap).forEach((tokenHash) => { const token = tokenMap[tokenHash] const pair = token.exchange.pair const OneInchPrice = token.OneInchPrice ? token.OneInchPrice : NaN const BinancePrice = token.BinancePrice ? token.BinancePrice : NaN const DiffPrice = token.DiffPrice const percentage = NumKit.getSubFloat((DiffPrice / OneInchPrice) * 100, 2) const orderPrice = token.orderPrice ? token.orderPrice : '' const orderPercentage = orderPrice ? NumKit.getSubFloat(((BinancePrice - orderPrice) / orderPrice) * 100, 2) : '' const nextTimeStr = token.nextHandleTime ? TimeKit.getTimeByMillisecond(token.nextHandleTime) : '' // 价格非法判定 const priceCondition = (() => { return OneInchPrice && BinancePrice })() const rows = [pair.toString(), OneInchPrice.toString(), BinancePrice.toString(), orderPrice.toString(), orderPercentage.toString(), nextTimeStr] // 识别到在拉盘 token.isLong = (() => { const percentageCondition = percentage > config.percentageLimit const isNoPrevHandleTime = !token.nextHandleTime const isTimeCover = new Date().getTime() > token.nextHandleTime const timeCondition = isNoPrevHandleTime || isTimeCover return priceCondition && percentageCondition && timeCondition })() // 打印表格 table.showLine(rows, undefined) }) table.printEndLine(logger) logger.info(`${config.baseIerc20Token.symbol} asset amount: ${accountAssetMap[config.baseIerc20Token.symbol]}.`) logger.info('') } const priceHandler = async function(context, task) { const config = context.config const tokenMap = context.tokenMap const tokenContractAddressList = Object.keys(tokenMap) for (const tokenHash of tokenContractAddressList) { const toToken = tokenMap[tokenHash] const priceTick = toToken.exchange.priceTick const fromIerc20Token = config.baseIerc20Token const amount = config.baseTokenAmount const OneInchPrice = NumKit.getSubFloat(await OneInch.price(fromIerc20Token.contract, tokenHash, amount, fromIerc20Token.decimals), priceTick) const BinancePrice = NumKit.getSubFloat(await BinanceSpot.realPrice(toToken.exchange.pair), priceTick) toToken.OneInchPrice = OneInchPrice toToken.BinancePrice = BinancePrice toToken.DiffPrice = BinancePrice - OneInchPrice if ((() => { return Math.abs(toToken.DiffPrice) < Math.pow(10, -priceTick) })()) { toToken.DiffPrice = 0 } { toToken.DiffPrice = NumKit.getSubFloat(toToken.DiffPrice, priceTick) } } } const accountHandler = async function(context, task) { const accountInfoRst = await context.binanceSpot.accountInfo() context.accountAssetMap = BinanceKit.parseBalancesToAccountAssetMap(accountInfoRst.balances) } const onTickFun = async function() { const task = this const context = task.context // 搜集所有价格数据 await priceHandler(context, task) // 获取账户数据 await accountHandler(context, task) // 展示关键信息 showInfo(context, task) // 交易逻辑 await tradeLogic(context, task) } const context = new Context() const onePro = new OneTask('OnePro', context, OneTask.baseInit, onTickFun) onePro.setDelayTime(onePro.context.config.delay) onePro.Start().then(() => {})